Arduino sprintf()Arduino sprintf

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. 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.

Arduino Sprintf() function Syntax

Just like the Arduino print() function, which accept the various data types and able to print it. There is C programming language under the standard C functions. Which is also included in Arduino Core. So you can use this. The common syntax of the Arduino sprintf() function is very similar to the stardard c sprintf() function which is as follows.

int sprintf(char *str, const char *format, ...)
Code language: JavaScript (javascript)

Here 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.

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)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.