Arduino – Buffered, Non-Blocking Serial Packet Manager

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 SerialManager library:

  • Provides a buffered write method that I have not yet found in other libraries (processor can work on other things while serial port pushes out a packet of data)
  • Provides a built in checksum calculation which can reduce errors in transmission and can be tedious to manage
  • Provides built-in packet header search and hides it in the library code so the user code becomes more readable (can be disabled for sending raw packets)

This project is now hosted on Google Code

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

Example usage

#include <SerialManager.h>
#include <ByteBuffer.h>
 
SerialManager serial = SerialManager(256, 256);
ByteBuffer send_buffer;
 
int SEND_MODE = 0;
 
void setup()
{
  // initialize the serial communication:
  serial.init(0, 9600);
  serial.setPacketHandler(handlePacket);
 
  // Initialize the send buffer that we will use to send data
  send_buffer.init(30);
}
 
void loop() {
  serial.update();
 
  // If we are not busy sending then lets send something
  if( !serial.isBusySending() ){
    // Send some dummy data
    send_buffer.clear();
    send_buffer.put(17);
    send_buffer.putInt(300);
    send_buffer.putLong(-100000);
    send_buffer.putFloat(3.14);    
 
    // We can either send a packet with a header and checksum (niiice)
    if(SEND_MODE == 0)
      serial.sendSerialPacket( &send_buffer );
 
    // Or if we are sending to say a device that uses a custom protocol,
    // we can send a raw byte buffer to it
    if(SEND_MODE == 1)
      serial.sendRawSerial( &send_buffer );
 
    // Or if we just want to simply send one byte we can do that,
    if(SEND_MODE == 2)
      serial.sendSerialByte(16);
 
  }
}
 
void handlePacket(ByteBuffer* packet){
  // Here we could do anything we want to the data but for now we will just send it back
  send_buffer.clear();
  while( packet->getSize() > 0 )
    send_buffer.put( packet->get() );
  serial.sendSerialPacket( &send_buffer );
}

About Siggi