sprintf function usage#

“The [3] burritos are [147.7] degrees F”

In this example, consider both the number of burritos and the temperature value as variables. Using Serial.print() you’d typically write five lines of code to print out that single line of text.

Serial.print("The ");
Serial.print(numBurritos);
Serial.print(" burritos are ");
Serial.print(tempStr);
Serial.println(" degrees F");

Let’s break each line down.

  • First, you’ll create in a character array to save the output string.

  • Then you use the sprintf() function to combine our text and variables into a string.

  • Finally, you’ll tell Serial.print() to display the formatted string.

char buffer[40];
sprintf(buffer, "The %d burritos are %s degrees F", numBurritos, tempStr);
Serial.println(buffer);
  • d or i – signed decimal integer

  • u – unsigned decimal integer

  • s – a string of characters

如何打印浮点数?#

float a=5.55,b=2.22;
char buff[20];
sprintf(buff,"%.2f,%.2f",a,b);
Serial.println(buff);

The code in visual c++ can run correctly, but in arduino IDE, it output garbage characters. What causing that?

arduino 本身是不会处理浮点数的,但可以先转换成 string (字符串) 形式

dtostrf()#

dtostrf() - turn your floats into strings - Programming Electronics Academy