Background
I'm trying to write a wrapper function for snrpintf()
on an embedded platform (Arduino) to have a shorthand for writing into a buffer then printing it over the Serial port.
Problem
As long as I write out the full code everything works, but this is rather verbose. So, I decided to write a function for it, which, alas, doesn't work.
It looks like the pointer doesn't get set properly, as the output is total rubbish.
Example
#include <Arduino.h>
#define AVR_PRINTF_BUFF_SIZE 127
void avrPrintf(const char *fmt, ...) {
char avr_printf_buffer[AVR_PRINTF_BUFF_SIZE] = {};
va_list args;
va_start(args, fmt);
snprintf(avr_printf_buffer, AVR_PRINTF_BUFF_SIZE, fmt, args);
va_end(args);
Serial.print(avr_printf_buffer);
}
void setup() {
Serial.begin(19200);
delay(1000);
Serial.println("Without a function:");
char buffer[AVR_PRINTF_BUFF_SIZE] = {};
snprintf(buffer, AVR_PRINTF_BUFF_SIZE, "%d.%02d.%02d %02d:%02d:%02d Weekday: %02d\r\n\n", 1985, 5, 15, 14, 0, 32, 3);
Serial.print(buffer);
Serial.println("From a function:");
avrPrintf("%d.%02d.%02d %02d:%02d:%02d Weekday: %02d\r\n", 1985, 5, 15, 14, 0, 32, 3);
}
void loop() {
;
}
OUTPUT
Without a function:
1985.05.15 14:00:32 Weekday: 03
From a function:
2139.12594.14643 12590:13618:13369 Weekday: 12590