LOOP INSIDE SWTCH AND CASE STATEMENT

Hi. I'm new to Arduino programming. I would like to make a program looks like below:

  1. if press S, red LED is blinking continuously witj green LED off.
  2. if press E, red LED goes off and green LED will blink continuously

I'm using switch and case statement. But what happened, my led is only blinking once, when the S or E is pressed.

My program is attached. Great help is needed and highly appreciated.

Thanks

int red = 2, green = 3 ;

void setup()
{
Serial.begin(9600);
pinMode(red, OUTPUT); // LED on pin 2 of UNO
pinMode(green, OUTPUT) ;
}

char input = 0;

void loop()
{

if (Serial.available() > 0)
{ // is a character available?
input = Serial.read();
}

switch (input)
{
case 'S':
redblink() ;
Serial.println("RED is BLINK");
break;

case 'E':
greenblink() ;
Serial.println("GREEN is BLINK");
break;

}

} // end: switch (rx_byte)

void redblink()
{
digitalWrite(red, HIGH) ;
delay(500) ;
digitalWrite(red, LOW) ;
delay(500) ;
}

void greenblink()
{
digitalWrite(green, HIGH) ;
delay(500) ;
digitalWrite(green, LOW) ;
delay(500) ;
}

switch.ino (794 Bytes)

But what happened, my led is only blinking once, when the S or E is pressed.

Set the serial monitor for no line endings. There is a pull down menu next to the baud rate setting at the lower right of the monitor window.

The new line/carriage return line endings are received after the 'S' or 'E'. The 'S' and 'E' are not the active input values when the line endings become the input.

Thanks a lot. It is working.

Extra credit.

delay() stops regular code execution for the delay interval.

You can replace delay() with a technique called Blink Without Delay BWD.

When using BWD, your sketch can run other code during the delay time.

Read Robin2’s discussion:

https://forum.arduino.cc/index.php?topic=223286.0

Thanks for the BWD info.

You may also want to throw away any unwanted characters (anything other than 'S' or 'E', or perhaps any control characters) so that the line ending doesn't matter.