Skip to content

Software Circular Buffers

Pascal Roobrouck edited this page Jan 20, 2017 · 4 revisions

In the Mooov controller a number of buffers are used, the most important one being the motionBuffer. All buffers are implemented with the same scheme using a:

  • head : index of the oldest item in the buffer
  • level : how many items are in the buffer
  • length : how many items can the buffer hold

Circular buffers diagram

I prefer this mechanism over a 'head' and 'tail' pointer, as I find the math more logical and simple.

For a FIFO (First In First Out)

  • Read from bufferHead
  • Write to (bufferHead + bufferLevel) % bufferLength

For a LIFO (Last In First Out)

  • Read from (bufferHead + bufferLevel -1) % bufferLength
  • Write to (bufferHead + bufferLevel) % bufferLength

underrun, overflow

empty buffer? test for (bufferLevel == 0)
full buffer? test for (bufferLevel == bufferLength)