i want the lights to on only when message comes but the last for loop runs continuously even i send the message the led state does not change and the for loop continues .if i give a if condition to the for loop it executes only once this is the code can anyone help me with this .thanks in advance
That for loop takes 8 seconds to run. During that time you are only running the code in this for loop and not any other code. None of the code in this for loop reads from your serial line, so it won’t respond to any serial commands.
You’re going to have to think of a way to blink your led 4 times without using the delay function or a single for loop to run all the blinks at once. You need a way to do this in a non-blocking fashion. See the Blink Without Delay example for some inspiration.
The way your code is written the code in each of the IF statements will repeat until a new character is received. It is only in the case of the last one that that is obvious.
It would be better to write the code without using delay(). See how to use millis() to manage timing in Several Things at a Time. That way it could respond immediately to a new character.
Below is a very simple example of capturing of input on the arduino serial port and evaluating what was received. For this type of comparison, no other bytes like cr or lf are assumed to be sent.
// zoomkat 8-6-10 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later
int ledPin = 13;
String readString;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("serial on/off test 0021"); // so I can keep track
}
void loop() {
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
if (readString.length() >0) {
Serial.println(readString);
if (readString == "on")
{
digitalWrite(ledPin, HIGH);
Serial.println("LED ON");
}
if (readString == "off")
{
digitalWrite(ledPin, LOW);
Serial.println("LED OFF");
}
readString="";
}
}