What is UART/USART — Serial Communication-Embedded C Training Institute in Hyderabad

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Tutorial 12 — Communication

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.

📡 6 USARTs Available📋 BRR/CR1/CR2/SR Registers🔄 Ring Buffer Implementation⚡ printf() Redirection
SECTION 1

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

USARTBusIRQ#Clock (168MHz)TX PinRX PinNotes
USART1APB23784 MHzPA9 (AF7)PA10 (AF7)ST-LINK virtual COM port
USART2APB13842 MHzPA2 (AF7)PA3 (AF7)Also PD5/PD6
USART3APB13942 MHzPB10 (AF7)PB11 (AF7)Also PD8/PD9
UART4APB15242 MHzPA0 (AF8)PA1 (AF8)No synchronous mode
UART5APB15342 MHzPC12 (AF8)PD2 (AF8)No synchronous mode
USART6APB27184 MHzPC6 (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).

Diagram: UART Frame Format
IDLE
(HIGH)
START
(LOW)
D0
LSB
D1
D2
D3
D4
D5
D6
D7
MSB
STOP
(HIGH)
IDLE
(HIGH)

Standard 8N1 frame: 8 data bits, No parity, 1 stop bit

SECTION 2

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

84 MHz (USART1/6 at 168MHz)
115,200
USART1_BRR = 0x02D9; // 115200 baud at 84MHz Mantissa=45, Fraction=9, Actual=115226 baud, Error=0.023%
/* 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 */
SECTION 3

USART_CR1 — Control Register 1

USART1_CR1 — Address: 0x4001100C
15OVER8
14—
13UE
12M
11—
10PCE
9PS
8—
7TXEIE
6TCIE
5RXNEIE
4IDLEIE
3TE
2RE
1—
0SBK
Bit and field descriptions
Bit / FieldDescription
15 OVER8Bit 15 — OVER8
13 UEBit 13 — UE
12 MBit 12 — M
10 PCEBit 10 — PCE
9 PSBit 9 — PS
7 TXEIEBit 7 — TXEIE
6 TCIEBit 6 — TCIE
5 RXNEIEBit 5 — RXNEIE
4 IDLEIEBit 4 — IDLEIE
3 TEBit 3 — TE
2 REBit 2 — RE
0 SBKBit 0 — SBK
BitNameDescription
0SBKSend Break. Write 1 to send a break character.
1RWUReceiver Wake-Up (mute mode).
2REReceiver Enable. Must set this to receive data.
3TETransmitter Enable. Must set this to transmit data.
4IDLEIEIDLE Interrupt Enable. Fires when line is idle.
5RXNEIERXNE Interrupt Enable. Fires when receive buffer has data.
6TCIETransmission Complete Interrupt Enable.
7TXEIETXE Interrupt Enable. Fires when TX buffer is empty (ready for next byte).
8PEIEPE Interrupt Enable (parity error).
9PSParity Selection. 0=even, 1=odd.
10PCEParity Control Enable. 1=enable parity generation/checking.
11WAKEWakeup method. 0=idle line, 1=address mark.
12MWord Length. 0=8 data bits, 1=9 data bits.
13UEUSART Enable. Master enable — set LAST after all configuration.
15OVER8Oversampling mode. 0=16× (default), 1=8× (higher max baud rate).
SECTION 4

USART_CR2 and USART_SR

USART_CR2 — Control Register 2

BitsNameDescription
[3:0]ADDAddress of USART node (for multi-device UART networks)
5LBDIELIN Break Detection Interrupt Enable
8LBCLLast Bit Clock Pulse (synchronous mode)
9CPHAClock Phase (synchronous mode)
10CPOLClock Polarity (synchronous mode)
11CLKENClock Enable (synchronous mode)
[13:12]STOPStop bits: 00=1 stop, 01=0.5, 10=2 stop, 11=1.5 stop
14LINENLIN 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.

USART1_SR — Address: 0x40011000 (offset 0x00)
9CTS
8LBD
7TXE
6TC
5RXNE
4IDLE
3ORE
2NF
1FE
0PE
Bit and field descriptions
Bit / FieldDescription
9 CTSBit 9 — CTS
8 LBDBit 8 — LBD
7 TXEBit 7 — TXE
6 TCBit 6 — TC
5 RXNEBit 5 — RXNE
4 IDLEBit 4 — IDLE
3 OREBit 3 — ORE
2 NFBit 2 — NF
1 FEBit 1 — FE
0 PEBit 0 — PE
BitNameSet WhenHow to Clear
0PEParity error in received dataRead SR then read DR
1FEFraming error (wrong stop bit)Read SR then read DR
2NFNoise flag detectedRead SR then read DR
3OREOverrun: new byte arrived before old was readRead SR then read DR
4IDLEIdle line detectedRead SR then read DR
5RXNEReceive data register not empty (byte received)Read DR (or write 0)
6TCTransmission complete (TX shift register empty)Read SR then write DR, or write 0
7TXETransmit data register empty (ready for new byte)Write DR
8LBDLIN break detectedWrite 0
9CTSCTS line changed state (if CTS flow control enabled)Write 0
SECTION 5

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) { }
}
SECTION 6

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 */
}
SECTION 7

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] */
}
Why disable TXEIE when buffer empty? TXE is set when the TX data register is empty — which is most of the time when idle. If TXEIE stays enabled, the ISR fires constantly even with nothing to send, wasting 100% of CPU. The pattern is: enable TXEIE only when you add data to TX buffer, and disable it from inside the ISR when the buffer runs empty.
SECTION 8

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *