C++ functions print•println•printf•sprintf for Arduino ESP32 ESP8266. Combine•format → serial port

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

We use the serial monitor to debug the Arduino code, but there are many other things you can do. We will discover in this article the main methods to print(send) character strings on the serial port. print and println to send plain text. The printf function to convert, format and combine several variables in the same character string. sprintf and snprintf to store the results in a variable.

 

Quick access to functions

print or println  printf   options printf   sprintf write

How to open the serial port in the Arduino code?

Before being able to send messages on the serial port, it is necessary to initialize the communication with the command Serial.begin(speed). This method takes the baud rate of the serial port as a parameter.

By default, it is set at 9600 baud .

You can choose one of these speeds 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.

Most current development boards support the speed of 115200 baud without any problem.

Serial.begin(115200);

Print text on the serial port with print or println

The print() function is the base function. It allows to send(print) a character or a character string without any particular formatting.

Characters are sent to the serial port one after the other.

ExampleResult on serial monitor
Serial.print("A");
Serial.print("B");
Serial.print("C");
ABC

To return the cursor to the line (as on a word processor), there are several solutions:

  • Use the println() method
  • Add \n to the end of the published string
  • Combine the two

ExampleResult obtained on the serial monitor
Serial.print("A demo"); 
Serial.print("with");
Serial.println("a carriage return");
A demo with 
a new line
Equivalent
Serial.print("A half with \ n"); 
Serial.print("a carriage return");
A demo with 
a new line

How to combine multiple variables with print or println

As in most other languages ​​(Javascript, PHP ..), C ++ allows combining strings using the + operator . The data must first be converted into a string using the String() function.

Here is an example which combines in the same character string an integer variable, a float variable (decimal number) and a boolean.

int INT_VAR = 32;
float FLOAT_VAR = 32.23;
bool BOOL_VAR = true;
Serial.println("A string that combines an integer " + String(INT_VAR) + ", un decimal " + String(FLOAT_VAR) + " and a boolean" + String(BOOL_VAR));

Combine and format multiple variables into a string with printf

The printf() method allows both to format one or more data and then combine them into a single string before sending it to the serial port.

To do this, all you have to do is specify the position in the string using the % character .

Serial.printf("atmospheric pressure is %u hPa", pressure);

The % specifier  argument will then be replaced with the corresponding formatted value.

To format the output string as desired, it is possible to add additional options. The options are detailed in the following paragraphs.

%[flags][width][.precision][length]specifier

Here is an example that formats a decimal number with a single significant digit. The rounding is automatic.

%.1f

You can combine as many variables as you want. You just have to pass the variables in the same order as in the output string.

arduino begin printf function

Specify available

To be able to combine variables of different natures in the output string, you must indicate to the printf command the type of each data

Warning, choose the specifier which corresponds to the type of variable declared in the Arduino code.

SpecifierArduino data typeDescriptionExample
d or  iInt

Byte

World

Long (better to use unsigned Int)

Signed decimal integer392
uUnsigned decimal integer7235
oUnsigned octal610
xunsigned long

unsigned int

Unsigned hexadecimal integer (lowercase)7fa
XUnsigned hexadecimal integer (uppercase)7FA
f or Ffloat

double

Lowercase decimal floating point392.65
eLowercase exponent scientific notation3.9265e + 2
EScientific notation exponent in uppercase3.9265E + 2
gUse the shorter representation: % e  or  % f392.65
GUse the shorter representation: % E  or  % F392.65
ccharCharactera
schar []String of charactersexample
nNothing is printed
%%  followed by another % character   will write a single  %%

Flag option

The flag allows you to add characters before the value:

  • Force the addition of a sign (+ or -)
  • Insert space
  • Fill with zeros
  • Fill with 0x for hexadecimal numbers

flagDescription
-Left-justify within the given field width. By default, the justification is to the right of the value (see the width option )
+Forces the result to precede the result with a plus or minus sign (  +  or  -  ) even for positive numbers. By default, only negative numbers are preceded by the sign  -
(space)If no sign must be written, a space is inserted before the value
#Used with the ox  or  X specifiers ,  the value is preceded by  0  ,  0x  or  0X  respectively for nonzero values.
Used with  aAeEfF , g  or  G, the output string must contain a decimal point even if no number follows. By default, if no number follows, no decimal point is written
0Left-padded number with zeros ( 0 ) instead of spaces when padding is specified (see width option )

Option width

Specifies (or not) the number of characters to print

withDescription
(number)Minimum number of characters to print. If the value to be printed is less than this number, the result is completed by empty spaces. The value is not truncated even if the result is larger
*The  width  is not specified in the formatting string  , but as an additional integer value argument preceding the argument to be formatted

Precision option

Allows you to define the precision of the decimal numbers (the number of significant digits to print) or the maximum number of characters if it is a string.

.precisionDescription
.number
  • For d, i, o, u, x, X, the precision specifies the minimum number of digits to write. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0
  • For a, A, E, E, f and F, this is the number of digits to print after the decimal point (by default, this is 6)
  • For g and G, this is the maximum number of significant digits to print
  • For s, this is the maximum number of characters to print. By default, all characters are printed until the trailing null character is encountered
.*The  precision  is not specified in the format string   , but as an additional integer value argument preceding the argument to be formatted.

Conversion options taken from this article.

Store the result of a string formatted with sprintf or snprintf in a variable

The sprintf() method allows you to store the result of the conversion in a variable of type char[] .

Only restriction, it is not possible to convert several variables with a single command.

The sprintf() command requires initializing the output variable with a size at least equal to the length of the string. It is simply the number of characters in the output string.

char output_sprintf[6];
sprintf(output_sprintf, "%.1f°C", temp);
Serial.printf("Formatted value saved in the variable output %s \n", output_sprintf);

To combine several variables in the same string, you will need to use the snprintf() function which is written in a similar way

char output_snprintf[60];
snprintf(output_snprintf, sizeof(output_snprintf), "Température is %.1f°C, humidity is %.1f%% \n", temp, hum);
Serial.printf("output_snprintf = %s \n", output_snprintf);

Print the content of a byte buffer with write()

You may need to use an array of bytes. This array could for example contain the numeric code of each character of a String(character string).

To print an array of bytes to the serial port, the print(), println() functions do not work because they expect a variable of type char, char[] or String.

To print the contents of a buffer with the write() function , all you have to do is iterate through the latter using a for loop().

String stringtocopy = "Arduino"; 

// Measure string length
int buffer_size = stringtocopy.length();
Serial.printf("Buffer size: %u\n", buffer_size);

// Create a buffer having the same size as the string
byte buffer[buffer_size]; 

// Copy the contents of the string using the getBytes function 
// Attention, you must add 1 to the size of the string so as not to have a NULL character
stringtocopy.getBytes(buffer, buffer_size + 1); 
Serial.println("Print buffer with write function"); 

// Each cell of the buffer is printed one by one using a for loop
for (int i = 0; i < buffer_size; i++) { 
  Serial.write(buffer[i]); 
} 

Warning, you must add 1 to the length of the string at the level of the len parameter of the getBytes function , otherwise the last character will be null, for example: Arduin␀

Upload the Arduino code of the examples

Create a new sketch on the Arduino or PlatformIO IDE and upload the code to test all the examples presented previously.

#include <Arduino.h>

#define SERIAL_SPEED 115200

void setup() {
  Serial.begin(SERIAL_SPEED);
  
  Serial.println("\n=== print and println ====");
  Serial.print("A");
  Serial.print("B");
  Serial.print("C");

  Serial.println("\n=======");

  Serial.println("A demo with ");
  Serial.print("a line break");
  
  Serial.println("\n---- Or -----");

  Serial.print("A demo with \n");
  Serial.print("a line break");

  Serial.println("\n=== Concatenate with println ====");
  int INT_VAR = 32;
  float FLOAT_VAR = 32.23;
  bool BOOL_VAR = true;
  Serial.println("A string that combine an integer " + String(INT_VAR) + ", a decimal " + String(FLOAT_VAR) + " and a boolean " + String(BOOL_VAR));

  Serial.println("\n=== printf ====");
  unsigned int x = 0x999b989;
  byte b = 120;
  word w = 63450;
  unsigned int l = 2147483647; // long
  char c = 65; // A
  char s[] = "a string";
  float f = 99.57;
  double fdbl = 99.5769;
  Serial.printf("Hexa %x %X \n", x, x);
  Serial.printf("Byte %u \n", b);
  Serial.printf("World %u \n", w);
  Serial.printf("Long %u \n", l);
  Serial.printf("Char %c \n", c);
  Serial.printf("%s \n", s);
  Serial.printf("Variable float %f | %.2f \n", f, f);
  Serial.printf("Variable double %f | %.2f \n", fdbl, fdbl);

  Serial.println("\n=== FAKE BME280 ====");
  float temp = 18.68;
  float hum = 67.98;
  Serial.printf("Temperature is %.1f°C, humidity is %.1f%% \n", temp, hum);

  char output_sprintf[6];
  sprintf(output_sprintf, "%.1f°C", temp);
  Serial.printf("output_sprintf = %s \n", output_sprintf);
  
  char output_snprintf[60];
  snprintf(output_snprintf, sizeof(output_snprintf), "Temperature is %.1f°C, humidity is %.1f%% \n", temp, hum);
  Serial.printf("output_snprintf = %s \n", output_snprintf);

  Serial.println("\n=== write() buffer to Serial ====");
  String stringtocopy = "Arduino"; 
  int buffer_size = stringtocopy.length();
  Serial.printf("Buffer size: %u\n", buffer_size);
  byte buffer[buffer_size]; 
  stringtocopy.getBytes(buffer, buffer_size + 1); 
  Serial.println("Print buffer with write() function"); 
  for (int i = 0; i < buffer_size; i++) { 
    Serial.write(buffer[i]); 
  }
}

void loop() {
}

Open the serial monitor to view the operation of the functions

=== print and println ====
ABC
=======
A demo with 
a line break 
---- Ou -----
A demo with 
a line break
=== Concatenate with println ====
A string that combine integer 32, decimal 32.23 and a boolean 1

=== printf ====
Hexa 999b989 999B989 
Byte 120 
World 63450 
Long 2147483647 
Char A 
a string 
Variable float 99.570000 | 99.57 
Variable double 99.576900 | 99.58 

=== FAKE BME280 ====
Temperature is 18.7°C, humidity is 68.0% 

=== Write buffer to Serial ====
Buffer size: 7
Print buffer with write function
Arduino

Updates

22/10/2020 Publication of the article

Version française

Click to rate this post!
[Total: 0 Average: 0]

Are you having a problem with this topic?

Maybe someone has already found the solution, visit the forum before asking your question
Ask your question

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

Did you like this project ? Don't miss any more projects by subscribing to our weekly newsletter!

We will be happy to hear your thoughts

      Leave a Reply

      DIY Projects