how to print text and variable's values in the same line with Serial.println in Arduino
Asked Answered
B

5

18

I've this code:

 Serial.print("x:");
 Serial.print(x);
 Serial.print(" y: ");
 Serial.println(y);

and works fine. There's an example of the output:

x:41 y: 31

but I wonder if there's a way to write the four sentences in one with something like:

Serial.println("x:"+x+" y:"+y);

that returns an error:

invalid operands of types 'const char*' and 'const char [4]' to binary 'operator+'

Any idea?. Thanks in advance.

Blagoveshchensk answered 16/8, 2016 at 19:54 Comment(1)
I found the solution: Serial.println(String("x:") + x + String("y:") + y);Blagoveshchensk
C
6

String concatenation can be very useful when you need to display a combination of values and the descriptions of those values into one String to display via serial communication.

 int sValor = analogRead(A5); 
 String StrUno = "Valor Sensor N°5: ";
 String StrDos = StrUno + sValor ;
 Serial.println(StrDos);  

We can concatenate multiple values, forming a string with all the data and then send it. This can also be used with LCD dislpay.

Compliant answered 16/8, 2016 at 20:22 Comment(0)
W
35

There is a quicker way: Just convert your output directly to a String:

Serial.println((String)"x:"+x+" y:"+y);
Wingspread answered 10/10, 2018 at 21:29 Comment(0)
C
6

String concatenation can be very useful when you need to display a combination of values and the descriptions of those values into one String to display via serial communication.

 int sValor = analogRead(A5); 
 String StrUno = "Valor Sensor N°5: ";
 String StrDos = StrUno + sValor ;
 Serial.println(StrDos);  

We can concatenate multiple values, forming a string with all the data and then send it. This can also be used with LCD dislpay.

Compliant answered 16/8, 2016 at 20:22 Comment(0)
G
4

In PlatformIO for arduino works good (example):

Serial.println("R: " + String(variableR) + ", G: " + String(variableG) + ", B: " + String(variableB));
Gaynellegayner answered 1/8, 2022 at 7:14 Comment(0)
C
2

Either way, there needs to be an explicit conversion from int to String like seen in Guest's post - worked for me in the following way:

String(intVariable)

In the post of user3923880 this is missing and the code does not work in my Arduino IDE (Version 1.8.13). What worked for me, for example:

String outString = stringVar1 + '\t' + String(time) + '\n'; 
Serial.print(outString);

With \t being a tab delimiter and \n a line break.

Cornish answered 4/6, 2021 at 14:28 Comment(0)
R
0

Another possibility is this:

char buffer[40];
sprintf(buffer, "The %d burritos are %s degrees F", numBurritos, tempStr);
Serial.println(buffer);
Resonator answered 12/11, 2021 at 12:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.