An easy way to print multiple variables
The Serial.print() function is a nice way to print on the serial monitor but it is a bit frustrating to have to type something like :
Serial.print("Hello, I'm "); Serial.print(myName); Serial.print("and I'm "); Serial.print(myAge); Serial.println(" years old."); Serial.print("I live in "); Serial.print(myCountry); Serial.print(", my hobbies are :") Serial.print(myArduinoHobbies); //...
It could be a good idea to useSerial.print() once, don’t you agree? C/C++ programming – on computers – provides one way to do so : using the the printf() function along with the stream operators of printf(). This function is available in C and C++, and it is called this way :
printf("Hello, I'm %s and I'm %d years old.\nI live in %s , my hobbies are : %s", myName, myAge, myCountry, myArduinoHobbies);
Any %s operator will be replaced by the given string and any %d operator will be replaced by the given integer in the order they are given. The ‘\n’ indicates that the cursor must go to a new line (a kind of short Serial.println()).
The stream operator “<<” is C++ specific and may be quite confusing when met for the first time but a simple example is self explainatory :
std::cout << "Hello, I'm " << myName << " and I'm " << myAge << " years old.\nI live in " << myCountry << " , my hobbies are : " << myArduinoHobbies;
std::cout is the terminal, the output of a program which runs on a computer.
Sadly, since these functions directly print to a monitor only available on a computer, it is not possible to use them on an Arduino boards. Some workarounds have been presented on the Arduino playground here and here and of course, Arduinoos provides its own ! It is not the ultimate one but it does the job. PlainPRINT allows you to use the printf() way and the streaming way, as follows :
_printer.Printf("Hello, I'm %s and I'm %d years old.\nI live in %s , my hobbies are : %s", myName, myAge, myCountry, myArduinoHobbies);
and :
_printer << "Hello, I'm " << myName << " and I'm " << myAge << " years old.\nI live in " << myCountry << " , my hobbies are : " << myArduinoHobbies;
The %letter specifiers of Printf() are not as numerous as the ones available from the original function printf(). Here are the different specifiers :
SPECIFIER | INPUT TYPE | OUTPUT FORMAT |
---|---|---|
u | uint16_t | decimal |
ul | uint32_t | decimal |
d | int16_t | decimal |
l | int32_t | decimal |
f | float | decimal |
x | uint16_t | hexadecimal |
o | uint16_t | octal |
b | uint16_t | binary |
c | char | ASCII |
s | char* | ASCII string |
% | char | "%%" outputs "%" |
Using Printf() has an advantage over using the stream operator: you can print an integer value in hexadecimal, octal or binary. Moreover, you can specify the precision of a floating point number, here is an example :
_printer.print("Pi with few decimals %4f", 3.14159); /* output : 3.1416 */
This code shortening library is, as usual, available on request.