There are many times when you need to design a protocol that retrieves multiple pieces of data in a single instance. You can do this by serially sending a string from your computer and letting the Arduino decide which part of the string means what. In this example, I am going to show a protocol I designed to get strings of varying lengths to the Arduino at irregular intervals decided by the computer. This particular example is a python script that prompts the user for a string and sends it to a serial-enabled LCD screen connected to the Arduino. Here is the package for download.
Because the computer decides when to send the information, hand-shaking is useless. I have decided to use a header byte to tell the Arduino that a string is coming in and the next bytes will be the data. Then I send the same header byte after the string is sent to tell the Arduino that the string transmission is over. Here is what the python side looks like:
ser.write(HEADER) #header byte
ser.write(data)
ser.write(HEADER)
For the HEADER constant, I chose ‘~’ considering I wouldn’t use that in any string literal I am sending. You can choose whatever is right for your protocol from an ASCII chart. Now for the Arduino side. First you need to establish a special “blocking” function for your serial port. A blocking function blocks everything until the serial event is completed. So, if you are trying to read a byte, it will wait until you receive the byte to move on:
byte nextByte() {
while(1) {
if(Serial.available() > 0) {
byte b = Serial.read();
return b;
}
}
}
This function waits until info is available in the buffer, then reads and returns the byte treating the buffer like a fast FIFO queue. Now, as for the main loop, you have 2 options. If your Arduino has stuff to do other than read serial data, you want to start off the main loop with:
if(Serial.available() > 0){
// do serial communications
}
// do what the Arduino needs to do all the time
Since this example is dedicated only to reading serial information. I started with my blocking function nextByte(). So, we check to see if this is the header byte ‘~’, or 126 on the ASCII chart. If it is, we go into the read loop:
char charIn = 0;
byte i = 0;
while (charIn != 126) { // wait for header again
charIn = nextByte();
stringIn[i] = charIn;
i += 1;
}
This is a pretty simple loop, it keeps reading bytes into the string until the header byte comes again, then we break the loop. From there, we can null out the string:
for (int j=i-1; j<16; j++) {
stringIn[j] = ' '; // null out string
}
The rest of the code is self-explanatory. You should be able to easily hack it to your liking.