SerialBuffered is a helpful class which wraps Serial and provides read buffering and timeouts.
I built it to deal with a serial camera, which spits out whole images as a single serial stream, and which I wanted to run at the highest baud rate possible. I had an implementation which used Serial, but I found that I often dropped incoming bytes if (for example) I did any debug logging at all. During the time the logging was doing its work, the mbed had filled its hardware buffer (which is only 16 bytes) and data was being lost.
SerialBuffered uses an interrupt handler, so it will catch data at all times. It maintains a circular buffer to store the stuff in. The buffer size is up to the caller, but it needs to be at least as big as the largest backlog of inbound data that will ever occur.
For the camera example, I set the buffer to be as large as a whole image frame, which was the worst possible case. If you are pushed for memory, you may want to experiment to find the smallest buffer that works for you reliably.
It also provides timeouts, which by default are set to 1 second. SerialBuffered::getc() will return -1 when it has failed to read because a timeout intervened. I found that debugging was a lot less painful when my app timed out when I made a mistake, instead of hanging up in a plain getc().
Here's the code, and a tiny test app to illustrate usage:
To move your project from Serial to SerialBuffered, just add the .cpp and .h to your project, and change Serial to SerialBuffered in your variable declarations. You will also want to add a check for -1 to the return value from getc().
If you're reading in a block of bytes, you may want to use the handy readBytes method, which will read in a whole bufferful of bytes for you in one go.
Please log in to post a comment.