In communication design, considering the flexibility of the protocol often leads to designing protocols as “variable length”.
An example is shown in the figure below: the communication protocol frame of the Ruimi LoRa terminal.
If a system receives the above “variable length” protocol frame, there will be a challenge—how to efficiently receive and parse it.
To simplify system design, we strongly recommend using a “state machine” to parse UART data frames, and to perform the parsing work in the ISR (Interrupt Service Routine), only submitting the entire data frame to the process for handling when the last byte (0x0D) is received.
The principle of this parsing state machine is shown in the figure below:
So, can the ISR handle this state machine in time? The answer is: so easy! Because it only has 3 actions, the computational load is very small:
Compare received data -> Update state variables -> Store received data, with only 3 statements in C language, translating to no more than 10 machine instructions.
The code listing is as follows:
Some screenshots from electronic books
【Complete Set of Hardware Learning Materials Collection】