3

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

char buf[256];
sprintf(buf, ...);
Serial.print(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?

asked May 2, 2016 at 21:04

1 Answer 1

6

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;
 Serial.begin(9600);
 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('\r');
 Serial.write(c) ;
 return 0 ;
}
answered May 2, 2016 at 21:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.