Strange behavior in user input

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??? :confused:

What have you got the line ending set to in the Serial monitor ?

 numBlinks = Serial.parseInt();

Serial.parseInt() leaves any new line/carriage return characters in the serial input buffer and the next time around the code sees that data in the buffer and tries, unsuccessfully, to parse an integer from it.

As UKHeliBob suggests, you can set the monitor to no line endings and your program will wait for data.

Alternatively, you can use any monitor termination and pull and discard any trailing characters from the buffer with

 numBlinks = Serial.parseInt();
   while (Serial.available())
  {
    Serial.read();//throw away any terminating character
    delay(5);//see if there's another
  }

  for (int i = 1; i <= numBlinks; i = ++i) Crazy complicated.  for (int i = 0; i < numBlinks; i++)

Please remember to use code tags when posting code

Thanks for your help!!! :slight_smile: