How to create a loop under a switch (arduino)?

I need help in creating a loop under a switch command in arduino IDE, I'm new to programming. 
void loop() {
  if (Serial.available() > 0) {
 
   incomingByte = Serial.read();
 
}

switch (incomingByte){

   case '1':
   digitalWrite(led1, LOW);
   digitalWrite(led2, HIGH);
delay(300);
   digitalWrite(led1, LOW);
   digital Write(led2, HIGH);
break;

    case'2':
   digitalWrite(led1, LOW);
   digitalWrite(led2, LOW);
break;

}
I need the LEDs to blink alternatively (now it just blinks once), and stop when '2' is entered.
I also tried
 
case '1':
   for(int i = 0; i < 5; i++)
{
   digitalWrite(led1, HIGH);
   digitalWrite(led2, LOW);
   delay(200);
   digitalWrite(led1, LOW);
   digitalWrite(led2, HIGH);
   delay(200);
}
break;

case'2':
   digitalWrite(led1, LOW);
   digitalWrite(led2, LOW);
break;

But the circuit does not stop at '2'.
Thanks

sort by: active | newest | oldest
mh76dk3 years ago

Something like this (untested code off-the-top-of-my-head, and i dont know arduino specifics) perhaps?:

int done = 0;

while (!done && Serial.available())

{

incommingByte = Serial.read();

/* put your switch statement here

in case:'2' just before the break; add: done = 1; */

}

mh76dk mh76dk3 years ago

And now i get the feeling i misunderstood you, my code will blink once when you press 1 and end the program (or rather, loop() might just restart in that case - im guessing thats arduinos "main loop") when you press 2. if you want it to run without blinking till you press 1, continue blinking till you press 2, then wait for a 1 again - let me know, thats a slight rewrite but not a biggie :-)

mh76dk mh76dk3 years ago

So i put together 2 examples that you might find useful and which i believe will do as you requested...(i am not sure if the loop() is effectively like my while(1), so you might not need that while-loop around it all, but it shouldnt hurt):

http://pastebin.com/zK5PYK3N

ThisIsSteve (author)  mh76dk3 years ago

Hey mh76dk,

Thanks for your examples, the first example did the job.

That is great! I was starting to think it was more confusing than helpful.

HarisP11 year ago

How to change "unlimited" time?