Hi, I am writing a code to detect the input from serial communication. If the arduino detected "abc123" , LED will ON, else LED OFF. My problem is the LED on just for a while when receiving "abc123". After that, it turns off while waiting for the next serial input. Below is my code:
Check out my tutorial Arduino Software Solutions which as various ways to read from Serial using Strings and SafeStrings.
Lets assume you are terminating the input with a \n. This sketch will read a line (see the tutorial for other example sketches)
// readStringUntil_nonBlocking.ino
// Reads chars into a String until newline '\n'
// https://www.forward.com.au/pfod/ArduinoProgramming/SoftwareSolutions/index.html
// Pros: Simple. Non-Blocking
// Cons: Does not return until the until_c char is found. i.e. no timeout or length limit
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, see Taming Arduino Strings
// https://www.forward.com.au/pfod/ArduinoProgramming/ArduinoStrings/index.html
}
// 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 = ""; // clear after processing for next line
}
}
Then you can edit the loop to add your check and turn the Led ON
if (readStringUntil(input, '\n')) { // read until find newline
Serial.print(F(" got a line of input '")); Serial.print(input); Serial.println("'");
input.trim();
if (input == "abc123") {
digitalWrite(13,HIGH);
} else{
digitalWrite(13,LOW);
}
input = ""; // clear after processing for next line
}
That will keep the line ON until the next line is read in.
You do not say when the LED should turn Off.