You can add Strings together in a variety of ways. This is called concatenation and it results in the original String being longer by the length of the String or character array with which you concatenate it. The + operator allows you to combine a String with another String, with a constant character array, an ASCII representation of a constant or variable number, or a constant character.
// adding a constant integer to a string: stringThree = stringOne + 123; // adding a constant long interger to a string: stringThree = stringOne + 123456789; // adding a constant character to a string: stringThree = stringOne + 'A'; // adding a constant string to a string: stringThree = stringOne + "abc"; // adding two Strings together: stringThree = stringOne + stringTwo;
stringThree = stringOne + millis();
stringThree = stringOne + analogRead(A0);because analogRead() returns an integer. 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, on an LCD display, over an Ethernet connection, or anywhere that Strings are useful.
Caution: You should be careful about concatenating multiple variable types on the same line, as you may get unexpected results. For example:
int sensorValue = analogRead(A0); String stringOne = "Sensor value: "; String stringThree = stringOne + sensorValue; Serial.println(stringThree);
int sensorValue = analogRead(A0); String stringThree = "Sensor value: " + sensorValue; Serial.println(stringThree);
gives unpredictable results because stringThree never got an initial value before you started concatenating different data types.
Here's another example where improper initialization will cause errors:
Serial.println("I want " + analogRead(A0) + " donuts");
int sensorValue = analogRead(A0); String stringThree = "I want " + sensorValue; Serial.println(stringThree + " donuts");
For best results, initialize your Strings before you concatenate them.
Step 1: What You Need?
Don't have components? Don't worry. Just click the component's name.Step 2: Build Your Circuit.
Step 3: Upload The Code.
1. Select the Arduino board type: Select Tools >> Board >> Select your correct Arduino board used.
2. Find the port number by accessing device manager on Windows. See the section Port (COM&LPT) and look for an open port named "Arduino Uno (COMxx)". If you are using a different board, you will find a name accordingly. What matters is the xx in COMxx part. In my case, it's COM3. So my port number is 3.
Select the right port: Tools >> Port >> Select the port number.
3. You can find this code in the example of Arduino IDE.
Select File >> Examples >> 08. Strings >> StringAdditionOperator
Click press the "upload" button (see the button with right arrow mark).
Here's a working example of several different concatenation examples :
0 comments:
Post a Comment