Consider this simple approach to make a light work in 3 different modes: on, off and blink:
attachInterrupt(buttonVector, switchMode, FALLING);
void loop() {
switch(mode) {
case 0: turnOff(); break;
case 1: turnOn(); break;
case 2: blinkOnce(); break;
}
}
now if switchMode is something like this:
unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = 0;
void switchMode()
{
interrupt_time = millis();
// debounce measures
if (interrupt_time - last_interrupt_time > 200)
{
mode = (mode + 1) % 3;
}
last_interrupt_time = interrupt_time;
}
then once the button is pressed, the mode is changed and if we were in the blink mode (mode == 2) we'll wait until the blink is done (let's say that's 2 seconds) and only then the mode is actually switched to the "off" mode. Now, can I stop whatever was in the process of current loop, break it and get the "off" instantly?
PS Of'course there can be some workarounds, like
void switchMode()
{
interrupt_time = millis();
// debounce measures
if (interrupt_time - last_interrupt_time > 200)
{
mode = (mode + 1) % 3;
if(mode == 0)
turnOff();
if(mode == 1)
turnOn();
}
last_interrupt_time = interrupt_time;
}
but is there something more elegant and general? (note that if there's 4 modes: on, off, blink, blink_slowly, than this won't work)