Arduino – Circular Byte Buffer

As I have been playing with the Arduino hardware platform, I have become more and more convinced of its usefulness. I generally appreciate all efforts to standardize in hardware and […]

As I have been playing with the Arduino hardware platform, I have become more and more convinced of its usefulness. I generally appreciate all efforts to standardize in hardware and am excited about the large community this platform has received.

I quickly realized that were I to use this for my projects I would need an efficient storage of bytes that I couldn’t find in the community libraries as well as a buffered serial write which also hadn’t been implemented to my knowledge. I created these libraries and decided to share them here if anyone would be interested in using them.

These are the properties of the ByteBuffer library:

  • Provides an efficient storage of bytes in a circular bytebuffer (stored as an array)
  • Provides access to data from the head and tail of the buffer (get() and getFromBack(), putInt() and putIntInFront() etc.)
  • Provides a nice way of converting bytes into larger datatypes, example: put(b1); put(b2); put(b3); put(b4); long data = getLong();
  • Convenient method to have a one process write values to the end of a buffer and have another process handle bytes from the beginning of the buffer whenever it gets around to it

This project is now hosted on Google Code

https://code.google.com/p/arduino-buffered-serial/ 

Example usage

#include <ByteBuffer.h>
 
/*
  Silly program that emulates buffered processing
  using a circular bytebuffer
 */
 
ByteBuffer buffer;
 
void setup()
{
  // Initialize the buffer with a capacity for 256 bytes
  buffer.init(256);
 
  // Init serial just to debug
  Serial.begin(9600);
}
 
int cnt = 0;
void loop() {
  cnt++;
 
  // Every 100th update
  if( cnt%100 == 0 ){
    buffer.clear();
    buffer.put(200);					// Put one byte at end
    buffer.putInt(2000);				// Put one int at end
    buffer.putLong(20000);				// Put one long at end
    buffer.putFloatInFront(200000);	// Put one float at beginning
  }
 
  // Every 100th update	(20 updates offset)
  if( (cnt+20)%100 == 0 ){
    Serial.println("Received following bytes");
      while( buffer.getSize() > 0 )
        Serial.println(buffer.get(), DEC);
    Serial.println("");
  }
}

About Siggi