I have sketch to blink 2 LEDs(red and yellow) a number of times given by a user.
Depending on the program loop is run an even or odd number of times
red or yellow LED is supposed to blink.
Maximum 4 loops should be run before new prompt for number of blinks
My sketch is as follows:
int rLed = 10; // pin for red LED
int gLed = 9; // pin for yellow LED
int pLed; // current selected LED
bool evenRun = true; // flag to see if loop is run even or odd times
int loopRuns = 0; // loop counter
int numBlinks = 2; // number of LED blinks
void setup() {
Serial.begin(9600);
getNumBlinks();
pinMode(rLed, OUTPUT);
pinMode(gLed, OUTPUT);
}
void getNumBlinks() {
Serial.println("Set number of blinks");
while(Serial.available()==0) { // Wait for User to Input Data
}
numBlinks = Serial.parseInt();
}
void blinkLed(){
for (int i = 1; i <= numBlinks; i = ++i) {
digitalWrite(pLed, HIGH);
delay(250);
digitalWrite(pLed, LOW);
delay(250);
}
}
void selectLED() {
if (evenRun)
pLed = rLed;
if (!evenRun)
pLed = gLed;
}
void loop() {
selectLED();
blinkLed();
evenRun = !evenRun;
Serial.print("loopRuns1:");
Serial.println(loopRuns);
delay(250);
if (loopRuns == 4) {
Serial.println("4 loop runs");
loopRuns = 0;
Serial.print("loopRuns2:");
Serial.println(loopRuns);
Serial.println("Prompt for number of blinks");
getNumBlinks();
}
loopRuns = ++loopRuns;
}
The output I get is:
Set number of blinks
loopRuns1:0
loopRuns1:1
loopRuns1:2
loopRuns1:3
loopRuns1:4
4 loop runs
loopRuns2:0
Prompt for number of blinks
Set number of blinks PROGRAM DOESN'T WAIT FOR USER INPUT
loopRuns1:1
loopRuns1:2
loopRuns1:3
loopRuns1:4
4 loop runs
loopRuns2:0
Prompt for number of blinks
Set number of blinks
When function getNumBlinks is called the second time it doesn't stop
for user input.
Why???