0
0
Power-electronicsHow-ToBeginner · 3 min read

How to Send Data Using UART in Embedded C: Simple Guide

To send data using UART in embedded C, you write the data byte to the UART data register after ensuring the transmit buffer is ready. This usually involves checking a status flag and then writing your byte to a register like UDR or TXREG depending on your microcontroller.
📐

Syntax

The basic syntax to send a byte over UART involves waiting for the transmit buffer to be empty, then writing the byte to the UART data register.

  • Wait for transmit buffer empty flag: This ensures the UART is ready to send new data.
  • Write data byte: Place the byte in the UART data register to start transmission.
c
while (!(UART_STATUS_REGISTER & TRANSMIT_BUFFER_EMPTY_FLAG)) {
    // wait until buffer is empty
}
UART_DATA_REGISTER = data_byte;
💻

Example

This example shows how to send a single character 'A' using UART on a generic microcontroller. It waits for the transmit buffer to be ready, then sends the character.

c
#include <stdint.h>
#include <stdbool.h>

// Mock registers for example
volatile uint8_t UART_STATUS_REGISTER = 0x02; // Bit 1 = TX buffer empty
volatile uint8_t UART_DATA_REGISTER;

#define TRANSMIT_BUFFER_EMPTY_FLAG 0x02

void uart_send_byte(uint8_t data_byte) {
    // Wait until transmit buffer is empty
    while (!(UART_STATUS_REGISTER & TRANSMIT_BUFFER_EMPTY_FLAG)) {
        // busy wait
    }
    // Write data to UART data register
    UART_DATA_REGISTER = data_byte;
}

int main() {
    uart_send_byte('A');
    return 0;
}
⚠️

Common Pitfalls

Common mistakes when sending data via UART include:

  • Not waiting for the transmit buffer to be empty before writing data, causing data loss.
  • Forgetting to initialize UART hardware and baud rate before sending.
  • Writing to the wrong register or using incorrect flags for your specific microcontroller.

Always consult your microcontroller's datasheet for exact register names and flags.

c
/* Wrong way: Writing data without checking buffer status */
UART_DATA_REGISTER = data_byte; // May overwrite ongoing transmission

/* Right way: Wait for buffer empty before writing */
while (!(UART_STATUS_REGISTER & TRANSMIT_BUFFER_EMPTY_FLAG)) {
    // wait
}
UART_DATA_REGISTER = data_byte;
📊

Quick Reference

StepDescription
Initialize UARTSet baud rate, frame format, enable transmitter
Check transmit bufferWait until transmit buffer empty flag is set
Send dataWrite byte to UART data register
RepeatSend next byte after buffer is ready

Key Takeaways

Always wait for the UART transmit buffer to be empty before sending data.
Write your data byte to the UART data register to start transmission.
Initialize UART settings like baud rate and frame format before sending data.
Check your microcontroller datasheet for exact register names and flags.
Avoid writing data too fast without checking buffer status to prevent data loss.