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.

Salvador Rueda
  • 855
  • 2
  • 7
  • 15

5 Answers5

33

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

Serial.println((String)"x:"+x+" y:"+y);
Guest
  • 341
  • 3
  • 2
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.

user3923880
  • 74
  • 1
  • 6
3

In PlatformIO for arduino works good (example):

Serial.println("R: " + String(variableR) + ", G: " + String(variableG) + ", B: " + String(variableB));
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
JanB
  • 31
  • 2
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.

budist
  • 61
  • 6
0

Another possibility is this:

char buffer[40];
sprintf(buffer, "The %d burritos are %s degrees F", numBurritos, tempStr);
Serial.println(buffer);