[SOLVED] Help with "Case" function in simple sketch

Hello Forum

I have this simple sketch:

const int etned = 2;      // the pin that the LED is attached to
const int etop = 3;
const int toned = 4;
const int toop = 5;
byte serialA;
void setup()
{
  // initialize the serial communication:
  Serial.begin(9600); //baud rate - make sure it matches that of the module you got:
  // initialize the ledPin as an output:
  pinMode(etned, OUTPUT);
  pinMode(etop, OUTPUT);
  pinMode(toned, OUTPUT);
  pinMode(toop, OUTPUT);
}

void loop() {

  if (Serial.available() > 0) {
    serialA = Serial.read();
    Serial.println(serialA);
  }


  switch (serialA) {
  case 1:
    digitalWrite(etned, HIGH);
    delay(1000);
    digitalWrite(etned, LOW);
    break;

  case 2:
    digitalWrite(toned, HIGH);
    delay(1000);
    digitalWrite(toned, LOW);
    break;

  default:
    break;
  }

}

When I run it, and sends the numbers 1 or 2 through a terminal, the cases are executed almost right, the pins are going high, but not low again, after the delay function. How can I make the pin go low after the delay? - right now they are just staying high.

I think there is a very simple solution to this, but I can't find it...

Thank you very much

best regards
JohannesTN

The are going low, but then going high again as soon as they go low, so you don't see it.

You have to ask yourself "What is in serialA on the pass through loop() AFTER the one where a number is entered, and what effect will that have on the switch()?"...

An easy fix is to add another delay after you write them low.

Sovereignty:
An easy fix is to add another delay after you write them low.

Assuming you want the LEDs blink. If not, just move the case statement inside the if statement.

I think I understand you, Majenko. But what is the easiest way to solve it then?

  • I though the "case" would stop right before the break, and remain there until called again...

Already tried that one, Sovereignty. It made the pin go, high low high low high low in a continuous loop.

Thank you

JohannesTN:
But what is the easiest way to solve it then?

See my post.

You need to have serialA return to a default state after the switch has run. Maybe something like "serialA = 0;" just after the end of the switch...

That works great, Majenko. Thank you very much.

Thank you to all of you! it is nice with so quick help :slight_smile: