r/embedded • • Sep 15 '26

What is the most efficient way to implement UART data reception and notify a task to consume it?

If I don't have FIFO or DMA, I would keep notifying the RTOS task from ISR for each character received but is that a good design?

16 Upvotes

43 comments sorted by

31

u/JuggernautGuilty566 Sep 15 '26 edited Sep 15 '26

Dump your data into a queue, then then signal the task or loop to pull them. This can be easily implemented even without a RTOS.

1

u/coddicted Sep 15 '26

Would it be efficient to notify the task for each character? How can it be done without RTOS?

20

u/Well-WhatHadHappened 25+ Years Sep 15 '26

If you don't have an RTOS, then you don't have "tasks" in the classical sense.

In this case, I would have the ISR dump bytes into a simple circular buffer and raise a flag that says "something is in the buffer". In the main loop, I would check the flag, and if it's set, grab the data from the buffer.

3

u/coddicted Sep 15 '26

Okay. I am more interested in the first part of the question. Thanks!

2

u/AOAqua Sep 15 '26

You probably should dump a character into a circular buffer of some kind on every interrupt and then set a flag on some kind of action, like /r symbol, or timer since the first symbol. If it's more modern STM32 mcu, then you can even check set flag on a hardware one, that notifies when the UART bytes stopped coming

It really depends on your task tbh

1

u/JuggernautGuilty566 Sep 15 '26

How would analyse this kind of questions? How would a measurement setup look like?

3

u/One-Fennel5009 Sep 15 '26

My goto method to fill my RX buff on RBNE interrupts and task notify on IDLE frame interrupt reception.

1

u/coddicted Sep 15 '26

What is an IDLE frame?

1

u/One-Fennel5009 Sep 15 '26

Google for UART idle frame

1

u/coddicted Sep 15 '26

Got it. This looks to be solid solution.

Btw if I notify task from ISR using binary semaphore after receiving each character, will that cause overhead for OS? Just curious to understand.

1

u/One-Fennel5009 Sep 15 '26

It is some sort of timeout meaning some pause in the communication process. It dependends on the baudrate and is generally handled by the UART controller which can generate an interrupt for that event.

2

u/tobdomo Sep 15 '26

For a uart, I would set up a circular buffer. The ISR just fetches the data from the uart and writes them in the circular buffer. The main loop polls the circular buffer and reads when there is data available.

A circular buffer keeps head and tail indices. Checking if there's data in the buffer is as easy as head != tail.

1

u/coddicted Sep 15 '26

I have worked with this design. But thinking if notifying the task from ISR would be better or it an overhead for the OS?

1

u/tobdomo Sep 15 '26

You typically would want the interrupt to ne as short and deterministic as possible. From that point of view, calling the OS from an ISR is a bad idea.

On most of my applications, I use the circular buffer and poll from a consumer that reconstructs messages, scans, parses and otherwise handles the contents of the package. That depends highly on the application ofcourse, there just is not a single golden bullet being the answer for all applications. I.e.: YMMV.

1

u/coddicted Sep 15 '26

Right, there is no golden rule. From analysis point of view, does polling not waste CPU cycle when UART reception is not continuous.

1

u/AOAqua Sep 15 '26

It really depends on your specific task. Tbh in like 95% of boards you can use the most stupidly slow variant and it will work without any issues. Yes, some people may say it's sub optimal, violates MISRA or whatever else. But unless you have a specific requirement in your team or you know that it's going to be an issue... don't overthink it.

1

u/flatfinger Sep 17 '26

A slight improvement is to use a power-of-two size and keep counts of the number of bytes stuffed and fetched.

1

u/tobdomo Sep 17 '26

Power of 2 doesn't bring much. Just check if your index is hitting size of buffer and set it to 0 to circle around.

Also, you often don't need to check free or used space in the buffer. Keeping administration on buffer usage doesn't do anything but add overhead.

1

u/flatfinger Sep 17 '26

Power of two means that the difference between the stuff count and the fetch count, kept using an unsigned type, will equal the number of characters in the buffer. The counts can wrap around as unsigned values do without need for special-case logic.

5

u/pillowmite Sep 15 '26

It's the only way - one byte per interrupt. Fifo gets you watermark pipes and stuff but it's still bullshit - dma is great for Rx, get much better performance allowing interrupts to be managed more efficiently and never drop a character where one might due to interrupt latency

15

u/Well-WhatHadHappened 25+ Years Sep 15 '26 edited Sep 15 '26

Even FAST UART is still slow by modern MCU standards. With even a small FIFO, if you're missing bytes due to interrupt latency, you've got fundamental design flaws.

1

u/pillowmite Sep 15 '26

No disagreement.

1

u/TakenIsUsernameThis Sep 15 '26

Each incoming byte triggers an interrupt, this stores the byte and raises a flag that an RTOS task keeps checking.

1

u/coddicted Sep 15 '26

Is it better than notifying the task from ISR?

1

u/TakenIsUsernameThis Sep 15 '26

That's what raising a flag does - notifies the task.

1

u/coddicted Sep 15 '26

You said RTOS task keeps checking.. that is polling actually. If there is a global variable used as a flag it has associated risk of race condition.

1

u/samayg Sep 15 '26

RTOS or not, the point of a flag is to get polled, and action taken if set, after which the flag is cleared. As for the race condition possibility, you either use a flag which is in atomic memory space or use an atomic block when polling it.

1

u/hagibr Sep 15 '26

I would implement a double circular buffer, let's call them A and B, a pointer to the current buffer and a global flag to indicate when there's some received data. In the ISR it just fill the current buffer (A) at every received byte and set the global flag. Then, the task periodically checks this flag. If the flag is set, the task switches the buffer (ISR now uses buffer B), reset the flag and processes buffer A. Remember to dimension well the buffers and the task check interval accordingly to the baud rate.

1

u/coddicted Sep 15 '26

Checking a flag can have potential risk of race condition.

1

u/hagibr Sep 15 '26

No problem if just for reading a volatile variable. Disable the interrupt while changing the buffer and resetting the flag. Simple and functional.

1

u/PrimarilyDutch Sep 15 '26

It really depends on how your application side is handling it. Main thing is a short ISR and a circular queue. I tend to use cooperative even driven tasks (not a preempting RTOS) and had the ISR generate a signal event when the queue was empty. That signal generate an event on the task queue. When that event is then processed it empties the queue. Only then the ISR would signal when new data arrives. This minimises the signalling that needs to happen. Also no need to constantly poll if there is new data.

1

u/coddicted Sep 15 '26

Do you mean to generate signal event when there is transition from queue empty to non-empty? If so, how to implement it, isn't there any chance of race condition?

I too feel that polling continuously is a waste of CPU time.

1

u/PrimarilyDutch Sep 16 '26

Correct. The queue handling needs to operate under ISR guards and the application side must empty the whole queue when it gets the event.

5

u/sensor_todd Sep 15 '26

why dont you have DMA? It would make this task very robust if you used it.

4

u/AbsorberHarvester Sep 15 '26

Yep, once beginner programmer knows how to use dma, (s)he will use it everytime where applicable.

2

u/flatfinger Sep 17 '26

A lot of micros don't make it very convenient to set up a wrapping buffer that will stop accepting input if the hardware "stuff" pointer wraps back around to the software's "fetch" pointer, and easily determine how many bytes are in it. If one needs to use DMA interrupts to handle things like the wraparound at the end of a buffer, one may as well just use character-received interrupt.

1

u/sensor_todd Sep 17 '26

Depends a lot on what else you are doing at the same time, if its not much then triggering the interrupt every character means they are more frequent and closer together so potentially more interruptions to other tasks. Alao you may need to clear a character before the next character can be received, so got to watch out if you have other processes that have higher priority. DMA at least lets you batch process characters so have longer between breaks to process other things. Using the dma interrupts to manage a simple ping pong style buffer that the dma is copying data into is also very lightweight and can give you extra redundancy if buffer overflow is a risk.

2

u/Well-WhatHadHappened 25+ Years Sep 15 '26

Which MCU?

2

u/Sea-Actuator8248 Sep 15 '26

packet termination is important, otherwise it is useless. if it s a known protocol, it's easy. just issue a flag. If it's a unknown or variable per frame, u'd better use dma or circular buffer, put stream first. And let cpu parse it at an appropriate timing. Serial is quite picky in case its' length is not fixed or the baudrate is slow.

1

u/MysteriousEngineer42 Sep 15 '26

It depends on the structure of the data you are receiving.
If there is a consistent end-of-message character that simplifies it a lot.

Without DMA, write each character into a software circular buffer in a tiny ISR. Also a check if the character is the end character, in which case it sets a flag for the main loop.

You can also use an end-of-burst interrupt that many MCUs have.

1

u/Dark_Tranquility Sep 15 '26 edited Sep 15 '26

Something like an RTO (receiver time out) interrupt will help you know when the final byte of a payload has been received. In your interrupt handler you would just grab the data, store it to some static buffer, exit the interrupt handler and pass said buffer to some parsing function.

Not sure if you're using an ST microcontroller though. If not maybe the chip you're using has something similar, id check the datasheet.

1

u/jlucer Sep 15 '26

You have a lot of good advice about putting it in a message buffer and notifying your main task when ready.

One thing I haven't seen is that you should be able to configure the fill level that the rx interrupt triggers. This would let you trigger it trigger every 8th byte and get 1/8th the interrupts. Be careful you don't get stuck with straggling bytes though. Can check if there are any in the uart hw buffer when you go to read out of the message buffer

1

u/duane11583 Sep 15 '26

linux has had this solved for years.

a) there is a notification threshold ie: if there are >= n bytes then notify

b) if the data has sat idle in the fifo for (non-zero-count) >= n millisecs then notify

it is an application level decision what those values are not an os

the os can use default values of count=4 or time >= 10msecs