How to Receive Data Using UART in Embedded C: Simple Guide
To receive data using
UART in embedded C, configure the UART peripheral, enable its receiver, and read incoming data from the UART data register when the receive flag is set. Typically, you check the receive interrupt flag or poll the status register, then read the received byte from the UART data register.Syntax
The basic steps to receive data via UART in embedded C are:
- Initialize UART with desired baud rate and settings.
- Wait for the receive flag to indicate data arrival.
- Read the received byte from the UART data register.
Example syntax for polling method:
c
while (!(UART_STATUS_REG & UART_RX_FLAG)) { // wait for data } uint8_t received_byte = UART_DATA_REG;
Example
This example shows how to initialize UART and receive one byte by polling the receive flag.
c
#include <stdint.h> #include <stdbool.h> // Mock registers for demonstration volatile uint8_t UART_STATUS_REG = 0; volatile uint8_t UART_DATA_REG = 0; #define UART_RX_FLAG 0x01 void UART_Init(void) { // Initialize UART registers (baud rate, frame format, enable RX) // This is hardware-specific and simplified here } uint8_t UART_ReceiveByte(void) { // Wait until data is received while (!(UART_STATUS_REG & UART_RX_FLAG)) { // wait } // Read and return received byte return UART_DATA_REG; } int main(void) { UART_Init(); // Simulate data arrival UART_DATA_REG = 'A'; UART_STATUS_REG |= UART_RX_FLAG; uint8_t data = UART_ReceiveByte(); // Clear flag after reading UART_STATUS_REG &= ~UART_RX_FLAG; // For demonstration, return received data as exit code return data; // Should return ASCII 65 ('A') }
Common Pitfalls
Common mistakes when receiving UART data include:
- Not enabling the UART receiver before reading data.
- Reading the data register before the receive flag is set, causing invalid data.
- Not clearing the receive flag after reading, leading to repeated reads of the same data.
- Ignoring hardware-specific initialization steps like baud rate and frame format.
Example of wrong and right approach:
c
// Wrong: Reading data without checking flag uint8_t data_wrong = UART_DATA_REG; // Right: Check flag before reading while (!(UART_STATUS_REG & UART_RX_FLAG)) {} uint8_t data_right = UART_DATA_REG; UART_STATUS_REG &= ~UART_RX_FLAG; // Clear flag
Quick Reference
| Step | Description |
|---|---|
| Initialize UART | Set baud rate, frame format, enable receiver |
| Wait for RX flag | Check UART status register for data arrival |
| Read data | Read byte from UART data register |
| Clear RX flag | Reset flag to receive next byte |
Key Takeaways
Always check the UART receive flag before reading data to avoid invalid reads.
Initialize UART properly with correct baud rate and enable receiver before use.
Clear the receive flag after reading to prepare for next data reception.
Polling is simple but interrupts can improve efficiency for UART data reception.