Serial.print and printf, Solved! in Arduino IDE and ESP

Serial.print and printf, Solved! in Arduino IDE and ESP. You’d like to be able to print values from inside strings, similar to printf. Since the Arduino IDE understands serial.print, you won’t be able to type anything for Arduino Uno, Arduino Mega or Arduino Nano etc like the statement below:

Serial.printf("You Entered %d hours", n);

However, there is a trick you can use, which is similar to many languages support it, such as php. See the code below.

Serial.print and printf, Solved! in Arduino

You simply need to specify a string, which can be blank or empty, and then begin printing using serial.println starting with the string variable, followed by a + sign to Concatenate with a constant string under double-course (” “), followed by another + sign, followed by the variable name, which can be int or float type, and so on.

int x = 36;
float y = 1.02;
String str;
void setup() {
  Serial.begin(9600);
  Serial.println(str + "Int: " + x + ", Float: " + y);
  delay(1000);
}

void loop() {

}

OUTPUT

Serial.print and printf, Solved
Serial.print and printf, Solved

Serial.printf in ESP8266

Serial.printf does not work with the Arduino boards like Uno, Mega, or Nano boards, but it does with the ESP8266 or NodeMCU boards. See the code below

int x = 36;
float y = 1.2;
void setup() {
  Serial.begin(115200);
  Serial.printf("Int is: %d and Float is %f \n", x, y);
  Serial.printf("Int is: %d and Float is %.2f \n", x, y);
  delay(1000);
}

void loop() {

}

Where,

Serial.printf("Int is: %d and Float is %.2f \n", x, y);

%.2f restrict a float number to just two digits after the decimal point in Arduino IDE.

OUTPUT

printf in nodemcu esp8266 or esp32
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments