How can i concatenate integers as a single string?
int out1, out2, out3 = 0;
out1 = digitalRead(r1);
out2 = digitalRead(r2);
out3 = digitalRead(r3);
I tried like so, between others, with no luck.
Serial.write(out1 + "" + out2 + "" + out3);
For example the expected result when all outputs are HIGH
should be 111
, while when only the r3
output is HIGH
it should be 001
All i want, is reporting to the sender of the serial command, the pins state
3 Answers 3
If you're just outputting to serial you don't need to concatenate - just print each bit separately, such as:
Serial.print(out1);
Serial.print(",");
Serial.print(out2);
Serial.print(",");
Serial.println(out3);
You should avoid using String as it's not good on devices with small amounts of memory like Arduinos. Instead if you really need to concatenate numbers you should use a C string and maybe snprintf
to format the numbers into it:
char out[30];
snprintf(out, 30, "%d,%d,%d", out1, out2, out3);
I second Majenko's points about just printing the bits separately if
possible, and avoiding String
objects.
However, if you do need to build such a string (not String object, just
plain C string), you don't need sprintf()
, which is quite a big
function: you can build the string character by character. For example:
char out[4]; // 3 + 1 char for the termination character
out[0] = out1==HIGH ? '1' : '0';
out[1] = out2==HIGH ? '1' : '0';
out[2] = out3==HIGH ? '1' : '0';
out[3] = '0円'; // add NUL termination
Serial.println(out);
This is using the ternary operator, which here means "if out1
is
HIGH
, then use the character '1'
, otherwise use '0'
".
Now, it just happens that in Arduino HIGH
means 1 and LOW
means 0.
And single digit numbers can be converted into character by just adding
the numeric code of character "0", which is 48 but can written as '0'
in C++. Thus you can write:
out[0] = out1 + '0'; // convert number to character
And you can put all together as:
char out[4]; // 3 + 1 char for the termination character
out[0] = digitalRead(r1) + '0';
out[1] = digitalRead(r2) + '0';
out[2] = digitalRead(r3) + '0';
out[3] = '0円'; // add NUL termination
Serial.println(out);
Serial.write(b) prints one byte not a string. Use print() to print strings and numbers.
Serial.print(digitalRead(r1));
Serial.print(digitalRead(r2));
Serial.println(digitalRead(r3));
1
s and0
s, you could also convert it to a three digit number, and print thatSerial.write(out1*100 + out2*10 + out3);
Serial.println()
.Serial.println(out1*100 + out2*10 + out3);
(thanks @EdgarBonet)