Stream UART Bytes to a Task With FreeRTOS Stream Buffers
Move UART bytes from an interrupt to a task with a FreeRTOS stream buffer: trigger level, ISR send, blocking receive and the single-writer rule.

A UART delivers a continuous stream of bytes, and a queue of single bytes is a poor fit: each byte pays the full overhead of a queue item, and the receiving task wakes once per byte. A FreeRTOS stream buffer is built for exactly this case. It is a byte-oriented FIFO with one writer and one reader, it can be written from an interrupt, and it lets the reader sleep until a chosen number of bytes has accumulated. This post wires a UART receive interrupt to a task through a stream buffer, explains the trigger level and why it matters, shows how to read with a timeout to find the end of a burst and states the single-writer, single-reader rule that makes it safe without locks. It uses FreeRTOS Kernel V11.3.3 on a Cortex-M4F. The cornerstone guide on FreeRTOS queues, stream buffers and message buffers compares the types, and the earlier post on sending queue messages from an ISR shows the queue version of this handler.
What a stream buffer is
A stream buffer holds bytes, not items. You create one with a total size in bytes and a trigger level:
StreamBufferHandle_t xRxStream = xStreamBufferCreate(256, 1);The first argument is the capacity in bytes. The second is the trigger level: the number of bytes that must be in the buffer before a task blocked in a receive is woken. A trigger of 1 wakes the reader as soon as any byte arrives. A larger trigger makes the reader wait for a batch, which reduces wake-ups. The trigger level is clamped to at least 1.
The functions mirror the queue ones, with byte counts in place of items:
| Function | Purpose |
|---|---|
xStreamBufferSend | Write bytes from a task; may block for space |
xStreamBufferSendFromISR | Write bytes from an interrupt; never blocks |
xStreamBufferReceive | Read up to a maximum number of bytes; may block for data |
xStreamBufferReceiveFromISR | Read from an interrupt |
xStreamBufferBytesAvailable | How many bytes can be read now |
xStreamBufferSpacesAvailable | How many bytes can be written now |
xStreamBufferReset | Empty the buffer, when no task is blocked on it |
The single-writer, single-reader rule
A stream buffer is safe without a lock only when one task or interrupt writes and one task or interrupt reads. Two writers can interleave their bytes and corrupt the internal indices. If you need several writers, serialize them with a mutex, or give each its own buffer and merge in the reader. For a UART, the receive interrupt is the one writer and one task is the one reader, which fits.
The interrupt
Reading the data register in the interrupt and sending the byte to the buffer takes a few lines. As with queues, the FromISR call takes the woken-task flag and the handler ends with a yield:
#include "FreeRTOS.h"
#include "stream_buffer.h"
#include "stm32f4xx.h"
extern StreamBufferHandle_t xRxStream;
volatile uint32_t rx_dropped;
void USART2_IRQHandler(void)
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if (USART2->SR & USART_SR_RXNE)
{
uint8_t byte = (uint8_t) USART2->DR;
size_t sent = xStreamBufferSendFromISR(xRxStream, &byte, 1, &xHigherPriorityTaskWoken);
if (sent != 1)
{
rx_dropped++; /* buffer full: the reader is too slow */
}
}
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}xStreamBufferSendFromISR returns the number of bytes actually written. It writes what fits and never blocks, so check the return value. A value below the length you passed means the buffer was full, and the missing bytes are lost.
Setup mirrors the queue case. The interrupt priority must be at or below the kernel's maximum syscall priority, and the buffer must exist before the interrupt is enabled:
StreamBufferHandle_t xRxStream;
void uart_rx_init(void)
{
xRxStream = xStreamBufferCreate(256, 1);
configASSERT(xRxStream != NULL);
NVIC_SetPriority(USART2_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1);
NVIC_EnableIRQ(USART2_IRQn);
USART2->CR1 |= USART_CR1_RXNEIE;
}The reading task: lines from a stream
A common job is to collect bytes into lines. The task receives whatever is available, up to a maximum, and feeds a small parser:
#include <stdio.h>
#include <string.h>
#define LINE_MAX_LEN 80
static void vLineTask(void *pvParameters)
{
char line[LINE_MAX_LEN];
size_t used = 0;
uint8_t chunk[32];
(void) pvParameters;
for (;;)
{
size_t n = xStreamBufferReceive(xRxStream, chunk, sizeof chunk, portMAX_DELAY);
for (size_t i = 0; i < n; i++)
{
char c = (char) chunk[i];
if (c == '\n')
{
line[used] = '\0';
printf("line: %s\n", line);
used = 0;
}
else if (c != '\r' && used < LINE_MAX_LEN - 1)
{
line[used++] = c;
}
}
}
}xStreamBufferReceive returns the number of bytes copied, between 1 and the maximum you asked for, once the trigger level is met. If you send hello\n followed by ok\n from a terminal, the task prints:
line: hello
line: okThe read may deliver hel, then lo\n, or the whole message at once, depending on how bytes arrive. The parser is written for that, because a stream has no message boundaries. If you need boundaries preserved, a message buffer is the right type, covered in its own post.
Choosing the trigger level
With a trigger of 1, the task wakes for every byte at the default behavior, and at 115,200 baud that is about 11,500 wake-ups a second in the worst case, each one a context switch. Raise the trigger level, and the task sleeps until that many bytes have arrived. Raising it also raises the worst-case latency: a command of 5 bytes sits unread when the trigger is 8.
A timeout resolves the tension. Keep a trigger level above 1 for efficiency, and read with a finite timeout so the task wakes after a quiet period even without the full trigger:
size_t n = xStreamBufferReceive(xRxStream, chunk, sizeof chunk, pdMS_TO_TICKS(20));Here the call returns when the trigger level is reached or 20 ms pass, whichever comes first, with whatever bytes are present, and 0 if there are none. That gives batching during bursts and bounded latency at the end of one. You can also change the trigger at run time with xStreamBufferSetTriggerLevel.
Sizing the buffer
The buffer must hold the bytes that arrive while the task is not running. At a byte rate of R bytes per second and a worst-case task latency of L seconds, you need at least R x L bytes, plus a margin. At 115,200 baud with 10 bits per byte, that is 11,520 bytes a second. If the task can be delayed 20 ms by higher-priority work, the buffer needs at least 231 bytes, and 256 gives a small margin. The sizing post works through this with the queue case; the arithmetic is the same.
Add counters like rx_dropped and watch them in testing. A non-zero count means the buffer is too small or the task is too slow, and the numbers say which.
Pitfalls
Two writers. If a second interrupt, such as a DMA half-transfer handler, also writes to the buffer, you have two writers. Use one writer path.
Reading from a task and an ISR. The same applies to readers.
Forgetting the yield. Without portYIELD_FROM_ISR, the woken reader waits for the next tick.
Resetting while a task blocks. xStreamBufferReset fails if a task is blocked on the buffer, and returns pdFAIL.
Treating a stream as messages. Bytes of two commands merge, and a command may arrive split. Parse by a delimiter or a length prefix.
DMA instead of per-byte interrupts
At high baud rates, one interrupt per byte costs a lot. Use the UART's DMA in circular mode and have the idle-line or half-transfer interrupt send the new bytes in a block with one xStreamBufferSendFromISR call. The reader side does not change. That is the reason to choose a stream buffer: its interface is the same whether bytes arrive one at a time or in blocks.
The boundary
A stream buffer has no memory of message boundaries and supports exactly one writer and one reader. It also copies the bytes twice, once in and once out, which is cheap for a UART and wasteful for megabytes. For framed packets use a message buffer, and for several producers use a queue. And V11.1.0 added a stream batching buffer that blocks the reader until the trigger level is reached or the timeout ends, even when some data is already present, which suits readers that want whole batches only.


