Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
UART/USART — Serial Communication
Complete guide to STM32F407 USART. BRR baud-rate register, CR1/CR2/SR registers explained bit-by-bit. Polling, interrupt-driven, and ring-buffer implementations in bare-metal C.
UART/USART Architecture
UART (Universal Asynchronous Receiver-Transmitter) is the simplest serial protocol: no clock signal, just two wires (TX and RX), with both sides pre-configured to the same baud rate. STM32F407 has 6 USARTs (Universal Synchronous/Asynchronous Receiver-Transmitter) — the U stands for it also supporting a synchronous clock mode.
USART Instances on STM32F407
| USART | Bus | IRQ# | Clock (168MHz) | TX Pin | RX Pin | Notes |
|---|---|---|---|---|---|---|
| USART1 | APB2 | 37 | 84 MHz | PA9 (AF7) | PA10 (AF7) | ST-LINK virtual COM port |
| USART2 | APB1 | 38 | 42 MHz | PA2 (AF7) | PA3 (AF7) | Also PD5/PD6 |
| USART3 | APB1 | 39 | 42 MHz | PB10 (AF7) | PB11 (AF7) | Also PD8/PD9 |
| UART4 | APB1 | 52 | 42 MHz | PA0 (AF8) | PA1 (AF8) | No synchronous mode |
| UART5 | APB1 | 53 | 42 MHz | PC12 (AF8) | PD2 (AF8) | No synchronous mode |
| USART6 | APB2 | 71 | 84 MHz | PC6 (AF8) | PC7 (AF8) | Also PG14/PG9 |
UART Frame Format
A UART frame consists of a start bit, 8 (or 9) data bits, optional parity bit, and 1 or 2 stop bits. The idle line state is HIGH. A start bit is always LOW (marking the beginning of transmission).
(HIGH)
(LOW)
LSB
MSB
(HIGH)
(HIGH)
Standard 8N1 frame: 8 data bits, No parity, 1 stop bit
USART_BRR — Baud Rate Register
The BRR register determines the baud rate. It consists of two fields: the integer part (bits [15:4]) and the fractional part (bits [3:0]). The BRR value is calculated from the peripheral clock frequency and desired baud rate.
BRR Formula (OVER8=0, 16× oversampling — default):
BRR = f_PCLK / (16 × BaudRate)
Or for integer + fraction parts:
DIV_MANTISSA = (int)(f_PCLK / (16 × BaudRate))
DIV_FRACTION = round(((f_PCLK / (16 × BaudRate)) - DIV_MANTISSA) × 16)
BRR = (DIV_MANTISSA << 4) | DIV_FRACTION
Examples for USART1 (APB2 = 84 MHz):
9600 baud: BRR = 84,000,000 / (16×9600) = 546.875 → 0x0223 (error ~0%)
115200 baud: BRR = 84,000,000 / (16×115200) = 45.572 → 0x02D9 (error ~0.02%)
1,000,000 baud: BRR = 84,000,000 / 16,000,000 = 5.25 → 0x0054 (error ~0%)
Baud Rate Calculator
/* BRR calculation macro */
#define USART_BRR_VALUE(pclk, baud) ((pclk) / (baud))
/* For USART1 at 115200 baud (APB2 = 84MHz): */
USART1->BRR = 84000000UL / 115200; /* = 729 = 0x2D9 */
/* Manual layout: DIV_MANTISSA=45, DIV_FRACTION=9 */
/* BRR = (45 << 4) | 9 = 0x2D9 */
/* The hardware uses both parts for fractional divider */
/* Note: simple integer division works fine for most baud rates */
/* The fractional part reduces baud rate error for odd multiples */
USART_CR1 — Control Register 1
Bit and field descriptions
| Bit / Field | Description |
|---|---|
| 15 OVER8 | Bit 15 — OVER8 |
| 13 UE | Bit 13 — UE |
| 12 M | Bit 12 — M |
| 10 PCE | Bit 10 — PCE |
| 9 PS | Bit 9 — PS |
| 7 TXEIE | Bit 7 — TXEIE |
| 6 TCIE | Bit 6 — TCIE |
| 5 RXNEIE | Bit 5 — RXNEIE |
| 4 IDLEIE | Bit 4 — IDLEIE |
| 3 TE | Bit 3 — TE |
| 2 RE | Bit 2 — RE |
| 0 SBK | Bit 0 — SBK |
| Bit | Name | Description |
|---|---|---|
| 0 | SBK | Send Break. Write 1 to send a break character. |
| 1 | RWU | Receiver Wake-Up (mute mode). |
| 2 | RE | Receiver Enable. Must set this to receive data. |
| 3 | TE | Transmitter Enable. Must set this to transmit data. |
| 4 | IDLEIE | IDLE Interrupt Enable. Fires when line is idle. |
| 5 | RXNEIE | RXNE Interrupt Enable. Fires when receive buffer has data. |
| 6 | TCIE | Transmission Complete Interrupt Enable. |
| 7 | TXEIE | TXE Interrupt Enable. Fires when TX buffer is empty (ready for next byte). |
| 8 | PEIE | PE Interrupt Enable (parity error). |
| 9 | PS | Parity Selection. 0=even, 1=odd. |
| 10 | PCE | Parity Control Enable. 1=enable parity generation/checking. |
| 11 | WAKE | Wakeup method. 0=idle line, 1=address mark. |
| 12 | M | Word Length. 0=8 data bits, 1=9 data bits. |
| 13 | UE | USART Enable. Master enable — set LAST after all configuration. |
| 15 | OVER8 | Oversampling mode. 0=16× (default), 1=8× (higher max baud rate). |
USART_CR2 and USART_SR
USART_CR2 — Control Register 2
| Bits | Name | Description |
|---|---|---|
| [3:0] | ADD | Address of USART node (for multi-device UART networks) |
| 5 | LBDIE | LIN Break Detection Interrupt Enable |
| 8 | LBCL | Last Bit Clock Pulse (synchronous mode) |
| 9 | CPHA | Clock Phase (synchronous mode) |
| 10 | CPOL | Clock Polarity (synchronous mode) |
| 11 | CLKEN | Clock Enable (synchronous mode) |
| [13:12] | STOP | Stop bits: 00=1 stop, 01=0.5, 10=2 stop, 11=1.5 stop |
| 14 | LINEN | LIN mode enable |
USART_SR — Status Register
This is the most-read register during UART operation. You check flags here to know when to send/receive data.
Bit and field descriptions
| Bit / Field | Description |
|---|---|
| 9 CTS | Bit 9 — CTS |
| 8 LBD | Bit 8 — LBD |
| 7 TXE | Bit 7 — TXE |
| 6 TC | Bit 6 — TC |
| 5 RXNE | Bit 5 — RXNE |
| 4 IDLE | Bit 4 — IDLE |
| 3 ORE | Bit 3 — ORE |
| 2 NF | Bit 2 — NF |
| 1 FE | Bit 1 — FE |
| 0 PE | Bit 0 — PE |
| Bit | Name | Set When | How to Clear |
|---|---|---|---|
| 0 | PE | Parity error in received data | Read SR then read DR |
| 1 | FE | Framing error (wrong stop bit) | Read SR then read DR |
| 2 | NF | Noise flag detected | Read SR then read DR |
| 3 | ORE | Overrun: new byte arrived before old was read | Read SR then read DR |
| 4 | IDLE | Idle line detected | Read SR then read DR |
| 5 | RXNE | Receive data register not empty (byte received) | Read DR (or write 0) |
| 6 | TC | Transmission complete (TX shift register empty) | Read SR then write DR, or write 0 |
| 7 | TXE | Transmit data register empty (ready for new byte) | Write DR |
| 8 | LBD | LIN break detected | Write 0 |
| 9 | CTS | CTS line changed state (if CTS flow control enabled) | Write 0 |
USART Initialization — Complete Setup
/*
* USART1 initialization at 115200 8N1
* TX=PA9 (AF7), RX=PA10 (AF7)
* APB2 clock = 84 MHz at 168 MHz system clock
*/
#include <stdint.h>
/* Register definitions */
#define RCC_AHB1ENR (*((volatile uint32_t*)0x40023830))
#define RCC_APB2ENR (*((volatile uint32_t*)0x40023844))
#define GPIOA_MODER (*((volatile uint32_t*)0x40020000))
#define GPIOA_OSPEEDR (*((volatile uint32_t*)0x40020008))
#define GPIOA_AFRH (*((volatile uint32_t*)0x40020024))
#define USART1_BASE 0x40011000UL
#define USART1_SR (*((volatile uint32_t*)(USART1_BASE + 0x00)))
#define USART1_DR (*((volatile uint32_t*)(USART1_BASE + 0x04)))
#define USART1_BRR (*((volatile uint32_t*)(USART1_BASE + 0x08)))
#define USART1_CR1 (*((volatile uint32_t*)(USART1_BASE + 0x0C)))
#define USART1_CR2 (*((volatile uint32_t*)(USART1_BASE + 0x10)))
#define USART1_CR3 (*((volatile uint32_t*)(USART1_BASE + 0x14)))
void USART1_Init(uint32_t pclk, uint32_t baud) {
/* Step 1: Enable GPIO and USART clocks */
RCC_AHB1ENR |= (1 << 0); /* GPIOA clock */
RCC_APB2ENR |= (1 << 4); /* USART1 clock */
/* Step 2: PA9 (TX) and PA10 (RX) = AF mode (MODER = 10) */
GPIOA_MODER &= ~((3 << 18) | (3 << 20)); /* Clear PA9 and PA10 */
GPIOA_MODER |= (2 << 18) | (2 << 20); /* AF mode */
/* Step 3: High speed for UART pins (especially at high baud rates) */
GPIOA_OSPEEDR |= (3 << 18) | (3 << 20); /* Very high speed */
/* Step 4: Select AF7 (USART1) for PA9 and PA10 */
/* AFRH controls pins 8-15: PA9 = bits [7:4], PA10 = bits [11:8] */
GPIOA_AFRH &= ~((0xF << 4) | (0xF << 8));
GPIOA_AFRH |= (7 << 4) | (7 << 8); /* AF7 = USART1 */
/* Step 5: Configure USART — set BEFORE enabling UE */
USART1_CR1 = 0; /* Start fresh, UE=0 */
USART1_CR2 = 0; /* 1 stop bit, async mode */
USART1_CR3 = 0; /* No flow control, no DMA */
/* Step 6: Set baud rate */
USART1_BRR = pclk / baud; /* 84MHz / 115200 = 729 */
/* Step 7: Enable TX, RX, and the USART */
USART1_CR1 = (1 << 3) | /* TE = Transmitter Enable */
(1 << 2) | /* RE = Receiver Enable */
(1 << 13); /* UE = USART Enable (must be last) */
}
int main(void) {
SystemClock_Config(); /* 168 MHz */
USART1_Init(84000000UL, 115200);
while(1) { }
}
Polling Mode — Send and Receive
/* Send a single byte — poll until TXE */
void USART1_SendByte(uint8_t data) {
while (!(USART1_SR & (1 << 7))); /* Wait for TXE (TX buffer empty) */
USART1_DR = data; /* Writing DR clears TXE */
}
/* Wait until transmission fully complete (useful before sleep/DMA) */
void USART1_FlushTX(void) {
while (!(USART1_SR & (1 << 6))); /* Wait for TC (transmission complete) */
}
/* Send a null-terminated string */
void USART1_Print(const char* str) {
while (*str) {
USART1_SendByte((uint8_t)*str++);
}
}
/* Receive a byte — blocking */
uint8_t USART1_ReceiveByte(void) {
while (!(USART1_SR & (1 << 5))); /* Wait for RXNE (data available) */
return (uint8_t)(USART1_DR & 0xFF); /* Reading DR clears RXNE */
}
/* Receive with timeout — returns 0 on timeout */
uint8_t USART1_ReceiveByteTimeout(uint8_t* data, uint32_t timeout_ms) {
uint32_t start = g_ms_ticks;
while (!(USART1_SR & (1 << 5))) {
if ((g_ms_ticks - start) > timeout_ms) return 0; /* Timeout */
}
*data = (uint8_t)(USART1_DR & 0xFF);
return 1; /* Success */
}
Interrupt-Driven UART with Ring Buffer
Polling blocks your CPU while waiting. For real applications, use interrupt mode: the ISR receives each byte and puts it in a ring buffer. The main loop drains the buffer whenever convenient — no bytes lost, no CPU wasted polling.
/*
* UART ring buffer implementation
* RX is interrupt-driven (RXNEIE) — ISR fills buffer
* TX is also interrupt-driven (TXEIE) — ISR drains buffer
* Thread safety: buffer indices are volatile, accesses are atomic (8-bit index)
*/
#define RX_BUF_SIZE 256 /* Must be power of 2 for mask trick */
#define TX_BUF_SIZE 256
#define BUF_MASK (RX_BUF_SIZE - 1)
typedef struct {
volatile uint8_t buf[RX_BUF_SIZE];
volatile uint8_t head; /* Write position (ISR writes here) */
volatile uint8_t tail; /* Read position (main loop reads here) */
} RingBuf_t;
RingBuf_t rx_buf = {0};
RingBuf_t tx_buf = {0};
static inline uint8_t ring_empty(RingBuf_t* rb) { return rb->head == rb->tail; }
static inline uint8_t ring_full(RingBuf_t* rb) { return ((rb->head+1) & BUF_MASK) == rb->tail; }
static inline uint8_t ring_count(RingBuf_t* rb) { return (rb->head - rb->tail) & BUF_MASK; }
void USART1_IRQHandler(void) {
uint32_t sr = USART1_SR;
/* Handle receive (RXNE) */
if (sr & (1 << 5)) {
uint8_t byte = (uint8_t)(USART1_DR & 0xFF); /* Clears RXNE */
if (!ring_full(&rx_buf)) {
rx_buf.buf[rx_buf.head] = byte;
rx_buf.head = (rx_buf.head + 1) & BUF_MASK;
}
/* If full, byte is silently dropped — check overflow in app */
}
/* Handle overrun error — must clear by reading DR */
if (sr & (1 << 3)) { /* ORE */
(void)USART1_DR; /* Clears ORE (read SR already done above) */
}
/* Handle transmit (TXE) — send next byte from TX buffer */
if (sr & (1 << 7)) { /* TXE */
if (!ring_empty(&tx_buf)) {
USART1_DR = tx_buf.buf[tx_buf.tail];
tx_buf.tail = (tx_buf.tail + 1) & BUF_MASK;
} else {
/* Nothing to send — disable TXEIE to stop ISR storm */
USART1_CR1 &= ~(1 << 7); /* Disable TXEIE */
}
}
}
/* Queue a byte for transmission — returns 0 if TX buffer full */
uint8_t USART1_TxByte(uint8_t data) {
if (ring_full(&tx_buf)) return 0;
tx_buf.buf[tx_buf.head] = data;
tx_buf.head = (tx_buf.head + 1) & BUF_MASK;
USART1_CR1 |= (1 << 7); /* Enable TXEIE to start transmission */
return 1;
}
/* Read a received byte — returns 0 if RX buffer empty */
uint8_t USART1_RxByte(uint8_t* data) {
if (ring_empty(&rx_buf)) return 0;
*data = rx_buf.buf[rx_buf.tail];
rx_buf.tail = (rx_buf.tail + 1) & BUF_MASK;
return 1;
}
/* Enable interrupt-driven UART */
void USART1_EnableInterrupts(void) {
USART1_CR1 |= (1 << 5) | (1 << 8); /* RXNEIE + PEIE */
/* TXEIE is enabled on demand when there's data to send */
NVIC_IPR(37) = (3 << 4);
NVIC_ISER(1) |= (1UL << 5); /* IRQ 37 = bit 5 of ISER[1] */
}
Redirecting printf() to UART
/*
* Redirect printf() output to USART1
* Requires implementing _write() (GCC/newlib)
* Works with printf(), puts(), putchar() etc.
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
/* GCC newlib hook — called by printf() */
int _write(int file, char* ptr, int len) {
(void)file;
for (int i = 0; i < len; i++) {
USART1_SendByte((uint8_t)ptr[i]);
}
return len;
}
/* Now you can use: */
printf("Hello World!\r\n");
printf("ADC value: %d, Voltage: %.2f V\r\n", adc_val, adc_val * 3.3f / 4095.0f);
/* Note: printf with float requires linking with -u _printf_float */
/* Or use a lightweight sprintf alternative to save flash */
/* Simpler alternative — snprintf then print */
char buf[64];
snprintf(buf, sizeof(buf), "Tick: %lu\r\n", g_ms_ticks);
USART1_Print(buf);
Summary
USART_BRR
Baud rate = PCLK / BRR. For 115200 at 84MHz: BRR = 729.
USART_CR1
Key bits: TE(3), RE(2), UE(13), RXNEIE(5), TXEIE(7), M(12)=0 for 8-bit.
USART_SR
RXNE(5)=data ready, TXE(7)=can send, TC(6)=fully done, ORE(3)=overrun.
USART_DR
Write to transmit. Read to receive. Reading clears RXNE. Writing clears TXE.
Ring Buffer
ISR fills RX buffer. TXEIE enabled on demand. Disable TXEIE when TX buffer empty.
Init Order
Clock → GPIO AF → BRR → CR2/CR3 → CR1(TE+RE) → last: set UE bit.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments