You need to maintain more state information to have 'case 3' work like a KITT-style back and forth LED scanner. I think you can do it with three state variables, j
for which pair of LEDs is active, backwardsScan
to say which way to go, and a timertimer4
to remember how long we've been working onwhere in the 91ms cycle we are with the active pair of LEDs.
Try something like this:
...
int backwardsScan = 0;
...
case 3: // KITT-like scanning back and forth 90us/1us
// j remembers which LED pair is active
// backwardsScan remembers which direction to scan
// timer4 handles the 90ms/1ms on-off cycle.
//
// reset output leds appropriately for (j,timer4):
for(int ii=0;ii<=5;ii++){
digitalWrite(ledArray[ii],( (ii==j) && (timer4 <90)));
}
// update KITT state based on (j,backwardsScan,timer4)
if(timer4 > 91){
j += backwardsScan? -1 : 1 ;
if (j > 5){
backwardsScan = 1;
j = 5;
}
if (j < 0) {
backwardsScan = 0;
j = 0;
}
timer4 = 0;
}
break;
The main trick with state machines is being able to fully determine the complete state from what you are keeping track of--It should be memoryless, in that the state variable(s) fully specify the state, and you don't need to remember the prior state. If you find you need to know more than one thing, you might need a vector or set of state variables. One could map the whole led-backwardsScan-timer4 state vector into a single state variable (timer4, modulo 182ms for example,) but that would be unnecessarily complicated. Recognizing all the variables required to fully specify the state is important.