LED blink not looping

The first two if statements work when I type 1 or 2 in the serial monitor, but when I type 3 into the serial monitor the LED only turns on for 1 second, then just turns off . How can I get the last if statement to loop when I type 3?

If you want it to blink indefinitely you must take a different approach.

If you you are Ok with 2,3 or N blinks, you can use a for statement in the if(c==3)

And please post your code according to the forum instructions.

Please.

Always show us a good schematic of your proposed circuit.
Show us good images of your ‘actual’ wiring.
Give links to components.


In the Arduino IDE, use Ctrl T or CMD T to format your code then copy the complete sketch.
Use the < CODE / > icon from the ‘posting menu’ to attach the copied sketch.


When 3 is received, set a Flag variable.

When the Flag variable is set, a non-blocking TIMER toggles the LED every 1sec.

When 1 or 2 is received, reset the Flag variable.

Way to confuse a n00b with unnecessary stuff, guys.

@sloving when you drop into that if (c == 3) block, enclose the code in a while() statement. Note that it will loop forever.

while(true)
{
  digitalWrite(2, HIGH);
  delay(1000);
  digitalWrite(2, LOW);
  delay(1000);
}

It's left as an exercise to the student to understand how to stop it from looping forever, if that is desired. Also, this would be a great time to learn about the 'switch' statement.

The line that says int c = Serial.ParseInt();

Because it has the int there, that means you are creating an int type variable called c. Since it is created inside the loop function, it will only live as long as the loop function. At the end of the loop function it will be destroyed and when loop repeats a new one is created at that line.

Instead you can put:
int c;

Above loop and outside of it and just put:
c = Serial.ParseInt();

inside of loop.

In that way the variable is created as a "global" variable and lives forever outside of loop.

You could also change the line in loop to:
static int c = Serial.ParseInt();

where the static modifier tells the compiler that this variable should be created once and live forever instead of being re-created every time through the function.

You also need to move the if statements outside the test for Serial.available(). That way when the c variable keeps it's value of 3 the if statements can still run each pass of loop until you send a new value.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.