A Simple Serial Parser Using A State Machine
This note illustrates how to decode or parse incoming serial data with an example. Transmitting one byte serially to a microcontroller is simple.The easiest way to do this is to interrupt the controller when a byte arrives on the receive pin. There is no need to parse or separate data as whatever comes in, is assigned to a variable. But what if there is more than one byte that needs to be received.How would you go about separating all the bytes and put them into their respective variables?
The example illustrated here is to parse direction,steering angle and speed sent from a PC to a microcontroller, in this case a Microchip PIC16F876A. Parsing in this example is based on the idea of a state machine. If you need to know more about state machines, the following link may be helpful:
Microchip forums : Most efficient way to “decode” serial data?
Most of the code used here is based on feature article by Glen Worstell on a “Ham Radio Repeater Locator” using a Garmin GPSMAP 295.
Links : Here
code : Here (ftp).
In this example, my PC transmits a serial string “$122133200″ where :
$ : Start of String(SOS)
122: Direction(Note 1)
133: Steering Angle
200: Speed
In my microcontroller the incoming string is compared byte by byte with a parser string “$dddtttsss” using a state machine where :
$ : Start of String(SOS)
ddd: Direction
ttt: Steering Angle
sss: Speed
The State Machine:

State 0: The state machine does nothing until a “$” or Start of String(SOS) is received.
State 1: “$” received.If not goto State 0.
State 2: The parser knows that the next(second) byte coming in has to be a Direction parameter, because of the “d” in the parser string If a number comes in, it is stored. If anyhing anything other than a number is received, it is discarded and the machine returns to State 0. This continues for 2 more bytes.
State 3: The fifth byte is the steering angle, represented by a “t” in the parser string.Ths same for the sixth and seventh bytes. State 4: The eighth byte is the Speed, known by the “s” in the parser.
The state machine is reset or restarted after the tenth byte.
If you declare the direction,steering angle and Speed as an int8 or a char, the final value for each parameter would be :
for direction:
direction = direction * 10 + received byte.
Direction = 0*10 + 1 = 1
Direction = 1*10 + 2 = 12
Direction = 12*10 + 2= 122

The following source code is for the Micrchip PIC16F876A, written in CCS.
Code : Here
