And i wanted to add more functions to this comparison.
When i enter 123 to the serial port, i get 123 printed on the serial communication screen.
But when i compare the result to 123, it says not equal.
Please help to see where did i do wrong.
String input_string = "";
bool string_complete = false;
void setup()
{
Serial.begin(9600);
input_string.reserve(200);
}
void loop()
{
if (string_complete)
{
Serial.println(input_string);
if(input_string == "123") //When 123 is entered, this do not return true.
{
Serial.println("Number 123 detected");
}
else
{
Serial.println("Number 123 not detected");
}
input_string = ""; //reset string value
string_complete = false; //reset
}
}
void serialEvent()
{
while(Serial.available())
{
char input_char = (char)Serial.read(); //read each byte and add them to string.
input_string += input_char;
if(input_char == '\n')
{
string_complete = true;
}
}
}
Kind regards
Dongfang
serialEvent does not really buy you anything, it is only run once per loop() at the end of the loop.
You could try this code instead
String input;
void setup() {
Serial.begin(9600);
for (int i = 10; i > 0; i--) {
Serial.print(' '); Serial.print(i);
delay(500);
}
Serial.println();
Serial.println(F("readStringUntil_nonBlocking.ino"));
input.reserve(80); // expected line size
}
// read Serial until until_c char found, returns true when found else false
// non-blocking, until_c is returned as last char in String, updates input String with chars read
bool readStringUntil(String& input, char until_c) {
while (Serial.available()) {
char c = Serial.read();
input += c;
if (c == until_c) {
return true;
}
}
return false;
}
void loop() {
if (readStringUntil(input, '\n')) { // read until find newline
Serial.print(F(" got a line of input '")); Serial.print(input); Serial.println("'");
input.trim(); // remove \n and space
if (input = "...") {
// do stuff
}
input = ""; // clear after processing for next line
}
}