Switch Case

hi, just getting my head around switch and case,

variable = 0;

void loop () {

A

switch (variable) {
case 1: B break;
case 2: C break;
default: D break;
)

E
}

soooo... the procedure is running and the code runs as;

A E A E A E A E (until the variable is reached, then B or C)
[switch is ignored until the variables are matched]
or
A D E A D E A D E (until the variable is reached, then B or C)
default switch is included in the loop until a variable is reached]
or
A D D D D D ( until the variable is reached, then B or C) then E
[switch locks the default until the variable breaks it out]

or other? :astonished:

In that snippet of code, the order would be A, D, E, A, D, E,.... The variable in the switch statement has the value 0 so the default case code would be executed.

If you increment variable, then the order would be A, B, E, A, B, E,...

Increment again to get A, C, E, A, C, E,...

Increment again to once again get A, D, E, A, D, E,...

so what's the question?

if you understand if then better, switch in if form is like this

if(variable == b) {

} else if(variable == c) {

} else {
  // D     default
}

No, A is always called as is E However you have used the default statement which matches every value other there than the ones on the switch labels So in your case you get d if it not 1 or 2.

Mark

ok, makes sense. so if i drop the default switch, then i get A E A E A E unless the variable is brought into play.

unless the variable is brought into play.

The variable is always "in play". The sequence will be A, E, A, E,... unless variable gets a new value that is 1 or 2.

ok, so this isn't running as smoothly as i'd like!

i've sacked off A and E and i'm running the whole thing inside a switch.

i have 4 modes;

1 - fade in leds upwards
2 - fade in leds downwards
3 - fade out all leds
4 - all leds stay off

int switchbutton = 0;

switch (whichbutton) {

    case 1:    // bottom step
// ACCENT LIGHTING
// UP LIGHTING
// LANDING LIGHTING
whichbutton = 3;
break;

    case 2:    // top step
// ACCENT LIGHTING
// DOWN LIGHTING
whichbutton = 3;
break;
  
    case 3:   // all off   
// STEPS OFF
// LANDING OFF
// ACCENT OFF
whichbutton = 0;
break;

   default: // all off
// ALL LEDS OFF
break;
  } end of switch

so the running system is; 2 buttons (which button) trigger case 1 (whichbutton = 1) , or case 2 (whichbutton = 2) respectively, and then following case 1, or case2, whichbutton is set to 3 (whichbutton = 3) at the end of case3 whichbutton is set to 0, and defaults to all off.

what i seem to get is when which button is set to 3 inside the switch routine, it takes a couple of runs to realise and then jump to case 3, when in case 3 it takes a few runs and then it jumps to case 0, all off.

it works, its just not hardy!

oo, my apologies, after a slight restructuring of the order of the dammed {}}{}{ it all seems to be working as it should be!

thanks for reading!