UART RX Interrupt Best Practises
What are the best practices for handling received packets using UART in interrupt mode?
The way I am currently working, I have a global receive buffer and then perform all processing of this buffer inside my RxCpltCallback function and although it works, it doesn't seem right to me.
I can think of two ways I could improve on this but I would like it if someone could weigh in for me:
-
Use a secondary processing buffer: I can create a secondary global "processing buffer" and copy the received data into this buffer in the interrupt callback function, and then process this second buffer in the main body of my code. This will allow me to begin receiving again immediately in the callback, but there is the obvious problem of the secondary buffer being overwritten in the middle of processing if more data comes in.
-
**Raise a flag upon completion:**In the interrupt callback, I could raise a flag and then process the received packet inside the main body. After processing, I would then begin trying to receive data again. This eliminates the need for two buffers (I could even have a single local buffer but I would still require a global flag) and if I attempt to send data before I start trying to receive again, I believe it will just sit in a transmission buffer on the transmitting device until it can be received. Please correct me if my understanding here is wrong.
I appreciate any and all input or if you have ideas for better/nicer ways of handling things.
Posted Aug 31, 2023, 3:16 PM UTC
In my experience you want to keep ISRs as fast as possible. Store the byte somewhere and then process it from the main loop. That way you are not holding off the ISR from processing the next byte. The ST scheduler is a good way to manage this.
I haven't used the ST scheduler before and a quick Google doesn't seem to come up with anything of note. Do you have more information?
Also, does this mean it's generally a good idea to begin attempting to receive immediately within the ISR, rather than waiting for the packet to be processes?
The scheduler is part of the stmcube distribution, there should be a ton of examples in there on how to use it. In short, you create "tasks" and you trigger them to run from the ISR. The task is run from the main loop the next time around.
I guess it's up to your application behavior. If you want to receive a continuous stream, then I would set up the next RX in the ISR. If you only want one byte at a time, then setup the RX from the task after you completed your processing. Just keep in mind that if you take too long to process, you could end up missing bytes. Typically you would just setup the RX after each byte in the ISR and use some sort of circular queue data structure to buffer the bytes until you process them. This is probably the most "streamlined" approach.
I think the Scheduler is now called Sequencer. You can find some info on it in AN5289 Section 4.4.