How to use printf with Arduino's streams without an intermediary buffer? The following seems unnecessary:

char buf[256];
sprintf(buf, ...);

Is there a way to connect HardwareSerial or SoftwareSerial to a libc stream or is there a custom implementation of printf that does this?

1 Answer 1


Sure - here's a Hello, World program that uses printf(). Everything that mentions "uart" is what connects printf() to your output stream. uart_putchar() does the actual outputting to ... someplace. That's what you'd modify to direct the C standard output to a different device - SofwareSerial, for instance:

// Hello, World program using printf()

#include <Arduino.h>

static FILE uartout = { 0 };   // FILE struct
static int uart_putchar(char c, FILE *stream);

void setup() {
   // For printf: fills in the UART file descriptor with pointer to putchar func.
   fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
   stdout = &uartout;

   printf("Hello, World!\n");

void loop( void ){
   printf("Elapsed time: %ld\n", millis());

// uart_putchar - char output function for printf
static int uart_putchar (char c, FILE *stream)
   if( c == '\n' )
   Serial.write(c) ;
   return 0 ;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.