0
0
Embedded Cprogramming~5 mins

Printf redirect to UART in Embedded C

Choose your learning style9 modes available
Introduction

We use printf to show messages. On embedded devices, we often send these messages through UART to see them on a computer.

You want to see debug messages from your microcontroller on your PC.
You need to send text data from your device to another device using UART.
You want to check sensor values or program status during development.
You want to log information without a screen or display.
You want to test communication between your embedded device and a terminal program.
Syntax
Embedded C
int fputc(int ch, FILE *f) {
    // send character ch to UART
    UART_SendChar((char)ch);
    return ch;
}

This function overrides the low-level output used by printf.

UART_SendChar is a placeholder for your UART transmit function.

Examples
Basic example redirecting printf output to UART character send function.
Embedded C
int fputc(int ch, FILE *f) {
    UART_SendChar((char)ch);
    return ch;
}
Waits until UART is ready before sending each character.
Embedded C
int fputc(int ch, FILE *f) {
    while(!UART_ReadyToSend());
    UART_SendChar((char)ch);
    return ch;
}
Adds carriage return before newline for proper terminal formatting.
Embedded C
int fputc(int ch, FILE *f) {
    if(ch == '\n') {
        UART_SendChar('\r');
    }
    UART_SendChar((char)ch);
    return ch;
}
Sample Program

This program redirects printf output to UART_SendChar, which here prints to the console. On a real device, UART_SendChar sends data over UART.

Embedded C
#include <stdio.h>

// Simulated UART send function
void UART_SendChar(char c) {
    // For demo, print to standard output
    putchar(c);
}

int fputc(int ch, FILE *f) {
    UART_SendChar((char)ch);
    return ch;
}

int main() {
    printf("Hello UART!\n");
    return 0;
}
OutputSuccess
Important Notes

Make sure your UART is initialized before using printf.

Redirecting printf this way helps debugging without extra hardware.

Remember to handle special characters like '\n' if your terminal needs it.

Summary

Redirect printf by overriding fputc to send characters via UART.

This lets you see printf output on a PC terminal through UART.

Useful for debugging and communication in embedded systems.