Arduino Serial Part 4: ASCII data and using markers to separate data

In part 3 we sent and received single characters to control LEDs using a fairly simple technique. If all you need is to remotely turn a few things on and off then this method is probably the best. It is simple, easy to program, and reliable. Sometimes though single characters are not enough and we need to use more complex commands or we may want to send sensor data that comprises more than one character.

In this post I look at a few different techniques for sending complex data and commands; starting with functions that are built in the Arduino language and moving to our own functions that, IMHO, perform better and allow for better code.


Multiple Characters

A common mistake a lot of beginners make is to test data before they have it. When receiving more than one character via serial, it is easy to assume that all the data arrives at one time. It does not. When a device sends “HELLO” it is sent one character at a time and received one character at a time. The receiving device then has to put all the characters together to form the word “HELLO”. By Arduino standards serial is very slow and the Arduino is capable of performing thousands of tasks in the time it takes to receive all the characters. This means if you are not careful your code can start checking the received data before you have actually received it.

Another problem I have seen is thinking a reads all the available data. It doesn’t. It reads one character or byte only and it is up to you to read all the data and put it together.

Continue reading