Switch Case LED | ON, OFF & BLINK

Why does my code not work and how can i make it work?

const int ledPIN = 12;
char data;

void setup() {
  Serial.begin(9600);
  pinMode(ledPIN , OUTPUT);
}
 
void loop(){
  data = Serial.read();
  switch (data)
  {
    case '0': // LED OFF
      digitalWrite(ledPIN, LOW);
    break;
    case '1': //LED ON
      digitalWrite(ledPIN, HIGH);
    break;
    case '2': // LED BLINK
      digitalWrite(ledPIN , HIGH);
      delay(200);
      digitalWrite(ledPIN, LOW);
      delay(200);
    break;   
  }
}

but i also have tried this...

const int ledPIN = 12;
char data;

void setup() {
  Serial.begin(9600);
  pinMode(ledPIN , OUTPUT);
}
 
void loop(){
  data = Serial.read();
  switch (data)
  {
    case '0': // LED OFF
      digitalWrite(ledPIN, LOW);
    break;
    case '1': //LED ON
      digitalWrite(ledPIN, HIGH);
    break;
    case '2': // LED BLINK
    do
    {
      digitalWrite(ledPIN , HIGH);
      delay(200);
      digitalWrite(ledPIN, LOW);
      delay(200);
    }while(data == '2')
    break;   
  }
}

We have to guess what it does?

aarg:
We have to guess what it does?

LED changes depending on what you write to serial, 0 is for it to be OFF, 1 is for it be ON, and 2 is for BLINK

CodingCarnage:
LED changes depending on what you write to serial, 0 is for it to be OFF, 1 is for it be ON, and 2 is for BLINK

That is only what you think it should do. What does it do now?

aarg:
How does that differ from what you want it to do?

I cant get the LED to stay Blinking when it's on option 2 (Blink)... that's what i want to do but i cant get it to work

Your case statement is executed each time through loop() and you get a new character each time. So it's only the value '2' for one pass. You have to set some kind of flag (boolean variable) to enable the blink.

I can see more problems coming, but let's have you deal with that first.

aarg:
Your case statement is executed each time through loop() and you get a new character each time. So it's only the value '2' for one pass. You have to set some kind of flag (boolean variable) to enable the blink.

I can see more problems coming, but let's have you deal with that first.

You gave me an idea thanks dude :slight_smile: it works fine now

const int ledPIN = 12;
char data;
int option;

void setup() {
  Serial.begin(9600);
  pinMode(ledPIN , OUTPUT);
}
 
void loop(){
  data = Serial.read();
  if(data == '0')
  {
    option = 0;
  }else if(data == '1')
  {
    option = 1;
  }else if(data == '2')
  {
    option = 2;
  }
  switch (option)
  {
    case 0: // LED OFF
      digitalWrite(ledPIN, LOW);
    break;
    case 1: //LED ON
      digitalWrite(ledPIN, HIGH);
    break;
    case 2: // LED BLINK
      digitalWrite(ledPIN , HIGH);
      delay(200);
      digitalWrite(ledPIN, LOW);
      delay(200);
    break;   
  }
}

holdingpattern:
Add this in front of the read:

if(Serial.available())

And ofc set line ending to none.

Thanks for the tip :wink: