My Windows computer is sending out a string of two chars. The first is the command number, and the second is a char marker. The Arduino sketch reads in the string, uses a switch statement to determine which command number it is and then compares the second char in the string to the defined marker (an exclamation mark). If true, it acknowledges the marker by returning a plus sign char to the sending computer.
A straightforward comparison of the second char in the read-in string to the marker did not work. I used a Serial.println statement to display the singled out second char, but it displays as an empty string.
I got the code to work by using the indexOf function to check for the marker, but I would like to know if I did something wrong when checking for it directly. Thank you for your help, and time. Code follows. Saga
void setup() {
//Set up serial monitor
Serial.begin(115200);
//Wait till serial connection is established.
while (!Serial) {}
}
//Currently tx process only sends 1!.
if (Serial.available()) {
//I've got something, read it in into a string variable
String inData = Serial.readString();
//Displays as "1!"
Serial.println(inData); //Show raw data in Serial Monitor
//Available commands:
// 1 - Check presence. Use ! char as marker.
switch (inData.substring(0, 1).toInt()) {
case 1:
//Displays as "Mark: *"
Serial.println("Mark: " + inData.substring(1, 1) + " *"); //Show only marker
// Check the mark to see if this is the correct device.
if (inData.indexOf("!") > 0) {
//if (inData.substring(1, 1) == "!") {
//The above commented IF statement does not work.
//Send confirmation char to host to let it know that this is the
//correct device.
Serial.print("+");
}
break;
}
}
This displays Mark: * in the serial monitor. It does not see the ! char. I believe that the char is there because the indexOf function works as expected. It is odd that doing a inData.substring(1, 1) == "!" does not work, but is consistent with the display of it in the second Serial.println. Regards, Saga
This would be a lot easier without the String. If you had just two characters in an array then you could switch on the first and compare with the second pretty easy.
Agreed, I wanted the string for future expansion. I know that I'll be sending over longer strings. If I see that a char array works better, I'll go that route. Thanks for the input. Saga
The start-index is inclusive, and the end-index is exclusive; both base-zero. If there are three characters, then (0, 3) is everything. When the two indices are the same, it is always nothing, an empty string.
Thanks! I believed that the first number was the starting index and the next number was the number of chars to get. I changed as you mentioned and it worked.