Arduino sprintf()
function is used to format strings. This helps us to include many variables in one strings. You may face this problem very often when you need to display the strings to LCD or via Serial, which includes many variables.
Table of Contents
What is Sprintf()?
sprintf()
stands for “string print formatted”. It formats and stores a series of characters and values in a buffer. It is commonly used in C programming to format strings without printing them to the console.
Basic Syntax of Arduino sprintf() function
The Arduino sprintf()
function is a powerful tool for formatting strings dynamically. It allows you to combine text with variables of various data types, creating customized output. Let’s discuss the basic syntax of sprintf()
method which is generic Embedded C style which is why could be used in Arduino as well.
The sprintf()
function takes three parameters: a pointer to a character array (char *str
) where the formatted string will be stored, a format string (const char *format
) that specifies the structure of the output using text characters and format specifiers, and a variable number of additional arguments (...
) that provide the values to be formatted according to the format specifiers.
As you can see that, first of all you provide the string buffer which will be used to place the formatted string then you provide the format which you want to apply on the string buffer and then you applied the variables which you are using to format the string.
Example Usage of sprintf()
Let’s take a scenario where we are reading two kind of values from the DHT11 sensor. You may already know that the DHT11 is a humidity sensor which also provides the temperature readings. So now we have two variables. The traditional way to send this string over serial port is something like as follows.
float temp = 30.3, hum = 40.8;
Serial.print(temp);
Serial.print(',');
Serial.println(hum);
Code language: Arduino (arduino)
The above code will output the values something like this 30.3,40.8
. But if you have to display the values with c
and h
to indicate centigrade and Humidity indications you may add some extra Serial.print
statements like this.
float temp = 30.3, hum = 40.8;
Serial.print(temp);
Serial.print('c,');
Serial.print(hum);
Serial.println('h');
Code language: PHP (php)
You get the idea.
DHT11 Arduino sprintf() example usage
Now we will extend the DHT11 Arduino example with the sprintf() function to format a string with the temperature and humidity readings. So we assume that we already fetched the Temperature and humidity readings from the DHT11 sensor in Arduino just like the above-mentioned example and now we want to send these values to the serial port. But this time we are using the sprintf
function to format a string with the variables and then we transmit that string over the serial.print()
function. Here is the example Arduino sprintf() usage.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
char buffer[50]; //buf to store the final output here
void setup() {
Serial.begin(9600);
dht.begin();//init the dht sensor
}
void loop() {
float t = dht.readTemperature();//read tempreature
float h = dht.readHumidity();
// Check if the readings are valid
if (isnan(t) || isnan(h)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Convert the temperature to Fahrenheit
float f = dht.convertCtoF(t);
float hic = dht.computeHeatIndex(t, h, false);
float hif = dht.computeHeatIndex(f, h);
sprintf(buffer, "Temperature: %.1f C / %.1f F, Humidity: %.1f %%, Heat index: %.1f C / %.1f F", t, f, h, hic, hif);
Serial.println(buffer);
delay(2000);
}
Code language: Arduino (arduino)
Here you can see that first we read the values from the sensor then we used the string format specifier to tell that we are dealing with floating values. %f
indicates floating values while the %d
specifies that we are dealing with the integer values.
C String Format Specifiers
In the above-mentioned examples, we used the %.1f
format specifier. Here the f
word is used to indicate that we want to format a floating-point number into our string. The .
indicates how much decimal point we want after the values. So mentioning that 1
we are telling that we are looking for only 1 value after the decimal point. You can read more about the format specifiers from this link. Here is the complete list of them.
Specifier | Description |
---|---|
%d | Decimal integer |
%u | Unsigned decimal integer |
%x, %X | Hexadecimal integer (lowercase/uppercase) |
%o | Octal integer |
%f | Floating-point decimal |
%e, %E | Floating-point exponential format (lowercase/uppercase) |
%g, %G | Use %e or %f format, whichever is shorter (lowercase/uppercase) |
%c | Character |
%s | String |
%p | Pointer address |
%% | Literal % character |
Difference between sprintf and printf
The basic common different between these two is that, sprintf
is used to write it’s output to a string buffer while on the other hand, the printf
is used to output the value on the standard output device. Like for example, if we are writing code in pure C language then it will write on the stdout if it is screen or printer. Here is the c equaling example for the printf usage as well.
#include <stdio.h>
int main()
{
int x = 10;
char buffer[20];
sprintf(buffer, "x = %d", x); // store "x = 10" in buffer
printf(buffer); // print buffer on screen
printf("\n");
printf("x = %d", x); // print "x = 10" on screen
return 0;
}
Code language: C++ (cpp)
Return value of sprintf()
The sprintf
function return the number of bytes it writes to the string buffer excluding the null character. So, for example if the total string it writes contains the 5 numbers of characters and 1 null \0
character at the end, the sprintf function will return the number 5. Here is the example code to test this usecase with sprintf return value printed out.
void setup() {
Serial.begin(9600);
char buffer[20];
int n = sprintf(buffer, "Hello, %s!", "world");
// Output buffer string along with the value of n
Serial.print("buffer = ");
Serial.println(buffer);
Serial.print("n = ");
Serial.println(n);
}
void loop() {
}
Code language: Arduino (arduino)