0
0
Embedded Cprogramming~7 mins

Printf debugging over UART in Embedded C

Choose your learning style9 modes available
Introduction

Printf debugging over UART helps you see what your embedded program is doing by sending messages to a computer. It is like talking to your program to understand its actions.

You want to check if a sensor value is read correctly in your embedded device.
You need to find out why your program is stuck or not working as expected.
You want to monitor variables or program flow without a screen.
You want to log events or errors during device operation.
You are developing firmware and want quick feedback from your device.
Syntax
Embedded C
int printf(const char *format, ...);

// To send printf output over UART, you usually:
// 1. Initialize UART hardware.
// 2. Redirect printf output to UART transmit function.
// 3. Use printf as usual to send messages.

UART must be set up before using printf for debugging.

Redirecting printf output depends on your microcontroller and compiler.

Examples
This example shows how to redirect printf output to UART by implementing the _write function.
Embedded C
// Example UART initialization (pseudo code)
UART_Init(9600); // Set baud rate to 9600

// Redirect printf output to UART
int _write(int file, char *ptr, int len) {
    for (int i = 0; i < len; i++) {
        UART_SendChar(ptr[i]);
    }
    return len;
}
Prints the temperature value over UART so you can see it on your computer terminal.
Embedded C
printf("Temperature: %d C\n", temperature);
Sample Program

This program simulates sending printf messages over UART by redirecting output to UART_SendChar. It prints a start message and a sensor value.

Embedded C
#include <stdio.h>
#include <stdint.h>

// Mock UART send function
void UART_SendChar(char c) {
    // In real hardware, this sends a char over UART
    // Here we just print to standard output for simulation
    putchar(c);
}

// Redirect printf output to UART
int _write(int file, char *ptr, int len) {
    for (int i = 0; i < len; i++) {
        UART_SendChar(ptr[i]);
    }
    return len;
}

int main() {
    int sensor_value = 42;
    printf("Starting UART debug...\n");
    printf("Sensor value is %d\n", sensor_value);
    return 0;
}
OutputSuccess
Important Notes

Make sure UART baud rate matches your terminal program settings.

Some compilers require different functions to redirect printf output.

Using printf debugging can slow down your program, so remove it in final code.

Summary

Printf debugging over UART lets you see messages from your embedded device.

You must initialize UART and redirect printf output to UART transmit.

This method helps find bugs and monitor program behavior without a screen.