I found an old example code on this forum to learn from, it is supposed to read the string from the serial monitor input until it hits a "X". e.g type "testX" into serial monitor.
It then prints the string it received (test), and then it prints the first 3 charchters of the string (tes).
It works fine the first time, but the second time i try it prints out the string, but then it only prints out the first charchter of the string.
The string is reset in the code, so i'm not sure why it doesn't work.
Serial monitor output from inputting "testX" twice:
serial delimit test 1.0
test
First three characters are: tes
test
First three characters are:
t
this is the code:
//zoomkat 3-5-12 simple delimited 'X' string
//from serial port input (via serial monitor)
//and print result out serial port
String String1;
void setup() {
Serial.begin(9600);
Serial.println("serial delimit test 1.0"); // so I can keep track of what is loaded
}
void loop() {
//expect a string like 123467890X
if (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == 'X') {
//do stuff
Serial.println(String1); //prints captured string to serial port out
String1 = String1.substring(0, 3); //get the first three characters
Serial.print("First three characters are: ");
Serial.println(String1);
String1=""; //clears variable for new input
}
else {
String1 += c; //makes the string readString
}
}
}
note - the string was originally called "readString", but i changed it to "String1" because "readString" came up orange in the code and i thought that was the problem. Even when the string is called readString the same problem occurs.