Switch Case Help

I wrote a code that will make something go up or down depending on what key you hit. ( 'u' for up and 'd' for down) I am incredibly new to programming of any kind and can't get it to work properly. When I hit 'd' it goes down, but when I hit 'u' it only stops it from going up or down, it doesn't make it go up at all. Any suggestions? Note: this is only part of my code

if (Serial.available() > 0){ int variableCondition = Serial.read();

switch (variableCondition) { case 'u': digitalWrite(up_pin, HIGH); digitalWrite(down_pin,LOW); break; case 'd': digitalWrite(up_pin,LOW); digitalWrite(down_pin,HIGH); break; default: return;

Hmm, there doesn’t seem to be any glaring problems with your switch case code. Have you checked the wiring and the physical component(s) controled by the pin you labeled as “up_pin” to make sure they aren’t causing the problem?

I will look at the wiring. Thank you!

Try this

 if (Serial.available() > 0){
  int variableCondition = Serial.read();

    switch (variableCondition)
    {
    case 'u':
    digitalWrite(up_pin, HIGH); 
    digitalWrite(down_pin,LOW);
 variableCondition = 'o'; // clear out the variable
    break;
    case 'd':
    digitalWrite(up_pin,LOW); 
    digitalWrite(down_pin,HIGH);
variableCondition = 'o'; // clear out the variable
    break;
    } // end switch case
} // end if available

I don't know what these do, if anything: default: return;

Replace your entire original code snippet with this:

digitalWrite(up_pin, HIGH); 
digitalWrite(down_pin,LOW);

If whatever it is doesn't go up now, it looks like you have a wiring issue.

I don't know what these do, if anything: default: return;

the default branch in a switch statement is executed if non of the named options match, so in this case for all characters other than 'u' and 'd' .

It is good practice to explicitly add it to a switch statement, to make the 'non matching branch' explicit. Often error handling is added in the default branch while the commands are named cases.

Another often seen pattern is to handle the bulk of data in the default and the special cases in the named options

char name[24];
int idx = 0;
bool ready = false;

while (Serial.Available() > 0 && !ready)
{
  int c = Serial.Read();
  switch(c)
  {
    case '\n': 
      ready = true;  // return ==> end of name
      break;    
  case '*':   // * to reset name ,
      idx = 0;
      break;
   default:
     name[idx++] = c;
     break;
   }
   name[idx] = 0; // allways add an end char
   if (idx == 23) break; // prevent overflow.
}