Skip to main content
2 of 2
comment added to code
Remi
  • 159
  • 1
  • 10

The usage will depend of the data type of your variables.

If they are int, it would be %d or %i If they are string, it would be %s

Wrapper for printf

You can change the limit based on your requirements

#include <stdarg.h>
void p(char *fmt, ... ){
    char buf[128]; // resulting string limited to 128 chars
    va_list args;
    va_start (args, fmt );
    vsnprintf(buf, 128, fmt, args);
    va_end (args);
    Serial.print(buf); // Output result to Serial
}

Source: https://playground.arduino.cc/Main/Printf

Usage examples:

p("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3); // strings
p("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3); // numbers

ESP8266

Its built-in in Serial class of the framework. No need for additional library or function.

// strings
Serial.printf("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3);
// numbers
Serial.printf("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3);

More details about formatting tips on the printf format reference page : http://www.cplusplus.com/reference/cstdio/printf/

\n is the escape sequence for the line feed.

Escape sequences are used to represent certain special characters within string literals and character literals.

Source: http://en.cppreference.com/w/cpp/language/escape

[EDIT]

  • As @Juraj mentioned, it's not available on most of the AVR modules. So I added ESP8266 mention and a printf wrapper for common AVR modules
Remi
  • 159
  • 1
  • 10