Circular buffers?
Hugh
Posts: 362
Hi,
Is there a consensus on the best way to use circular buffers? If I want to push a byte received from a serial port through an array of bytes named 'data', is this the way to do it?
I ask because if I print to the serial terminal any one element of the array (e.g., data[0], data[1], etc.,) individually I can see the data scrolling through. If I print data[0], data[1], data[2] and data[3] as a group there are gaps (some data is missing). Is it not the done thing to use bytemove with the same source and destination?
Is there a consensus on the best way to use circular buffers? If I want to push a byte received from a serial port through an array of bytes named 'data', is this the way to do it?
repeat bytemove (@data, @data + 1, 10) data[10] := serial.rx
I ask because if I print to the serial terminal any one element of the array (e.g., data[0], data[1], etc.,) individually I can see the data scrolling through. If I print data[0], data[1], data[2] and data[3] as a group there are gaps (some data is missing). Is it not the done thing to use bytemove with the same source and destination?
Comments
The FullDuplexSerial object does this for you.
But in your example it would maybe be an option to use the buffer of the serial driver directly, because it is already there, so why add another one?
But maybe I simply did not understand the problem good enough because I did not understand what you wrote after the code example.
Draw it on a piece of paper with (say) 16 values in a buffer and two variables, head and tail. Both start at zero. If data comes in, head moves up one. If data goes out, tail moves up one. For 16 values in the buffer, mask the top 28 bits to zero and then both head and tail automatically loop around from 15 to zero (Binary xxxx1111 to xxxx0000). If head = tail, then the buffer is empty. Buffer loop around is easiest if the number of values in the buffer is a multiple of 2, eg 2,4,8,16.
spin:
c/c++
And in Tracy Allen's four port serial driver:
The "cmpsub" statement does for any number what "add" does for powers of two (at least in this application).
While agree non-powers of two are easy to use, I've always used powers of two in my circular buffers (which I also learned about here on the forum).