As a continuation to my Raspberry Pi and Arduino communication post, I thought I’d do the same but opposite way. This time, I thought it would be nice to make a proper Arduino library to make the process more streamlined.
To make communication more robust, I decided to implement a more formal communication over serial to enable applications that have some idea if a command sent to Arduino was successfully carried out or not, and also introduce basic error recovery if invalid commands or wrong number of parameters are received.
If you haven’t worked with Arduino libraries before, I suggest you to familiarize yourself with this basic tutorial or the other one at Arduino Playground. If you’re not familiar with
AnalogWrite(), a quick peek to Arduino PWM Tutorial may also be in order.
Serial communication protocol
I wanted to make a simple formal protocol to send commands and hex, byte or word-sized parameters related to that command over serial line to the Arduino. For the protocol, I had these requirements:
- Text-based, so communication can be emulated with Arduino IDE’s “Serial Monitor” tool
- Size-efficient to speed up communications with slow baud rates
- Support for at least a few dozen commands and free number of parameters
- Success and error messages from Arduino
- Capability to return to known state after invalid commands, invalid number of arguments, communication errors or breakdowns
After some consideration, I chose to select non-overlapping sets of symbols from the ASCII character set for commands, parameters, control characters and success/error messages:
- Small letters (a-z) for commands (26 should be enough for everyone, right?)
- Numbers 0-9 and capital letters A-F to send parameters as hex-encoded values
- Newline to mark end of command and parameters (either ‘\r’ + ‘\n’ or just ‘\n’)
- Capital letters O, K, and R for success (OK) and error (RR) indications
With non-overlapping characters used for different things, detecting errors in sent commands becomes easier, as any “non-expected” character marks an error situation and as status messages OK and RR do not appear in commands, implementing two-way communication (commands to both directions) is easy later on.
Continue reading PiSerial Arduino Communication Library