I've set up a series of LEDs in a line, and set up the code that will light these LEDs in sequence in 'knight-rider' style. I've tested the code that runs the loop, and it works perfectly.
Now to take it a step further, my goal in this code is to be able to turn on/off the LED loop using the serial monitor. When I enter '1' into the serial monitor, the LED loop should begin and continue until I enter '0' into the serial monitor to turn the loop off.
The problem I am having with this code; when I enter '1' into the serial monitor, the knight-rider LED loops only once and then stops. I haven't been able to figure out how to keep the loop running continuously until it receives a '0' to turn it off. Any suggestions would be greatly appreciated.
int timer = 100; // The higher the number, the slower the timing.
int incomingByte = 0; // variable to read incoming serial instruction
void setup() {
for (int thisPin = 2; thisPin < 6; thisPin++) {
pinMode(thisPin, OUTPUT);
}
Serial.begin(9600);
}
void loop() {
// check the serial port for incoming data
if (Serial.available() > 0) {
incomingByte = Serial.read();
}
// if it receives an 'on', then begin the LED knight-rider loop
if (incomingByte == '1'){
// loop from the lowest pin to the highest:
for (int thisPin = 2; thisPin < 6; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = 5; thisPin >= 2; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
}
if (incomingByte == '0'){ //if it receives a '0', turn off the system - do nothing
}
}