Skip to main content
Arduino

Return to Revisions

3 of 3
replaced http://arduino.stackexchange.com/ with https://arduino.stackexchange.com/

Serial printf implementation

Based on this approach I wanted to implement a function for formatted printing data to the serial monitor. I tried the code below:

int PIN = 12;
void _printf(char *fmt, ...) {
 va_list va;
 va_start(va, fmt);
 char buf[vsnprintf(NULL, 0, fmt, va) + 1];
 sprintf(buf, fmt, va);
 Serial.println(buf);
 va_end(va);
}
void setup() {
 Serial.begin(9600);
 Serial.println("serial monitor has been set up");
 char buf0[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
 sprintf(buf0, "pin %i configured to output", PIN);
 Serial.println(buf0);
 _printf("pin %i configured to output", PIN);
 char buf1[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
 sprintf(buf1, "pin %i configured to output", PIN);
 Serial.println(buf1);
 _printf("pin %i configured to output", PIN);
 pinMode(PIN, OUTPUT);
 char buf2[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
 sprintf(buf2, "pin %i configured to output", PIN);
 Serial.println(buf2);
 _printf("pin %i configured to output", PIN);
 char buf3[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
 sprintf(buf3, "pin %i configured to output", PIN);
 Serial.println(buf3);
 _printf("pin %i configured to output", PIN);
}
void loop() { }

But it gives me some weird output:

serial monitor has been set up
pin 12 configured to output
pin 2263 configured to output
pin 12 configured to output
pin 2234 configured to output
pin 12 configured to output
pin 2205 configured to output
pin 12 configured to output
pin 2176 configured to output

What do 2263 and 2269 mean? Why does it happen only inside the function? What is my mistake and how can I fix it?

pt12lol
  • 101
  • 1
  • 3

AltStyle によって変換されたページ (->オリジナル) /