Please, help me understand what is wrong with my program. I am experimenting with LEDs again (sounds like something a mum would tell a kid not to do, doesn't is).
I want my program to cycle through some pre-programmed blinking patterns at the press of a button. Button 1 cycles one way and button 2 cycles the other way. I only have 2 patterns, but I plan to make more when the problems will be fixed. The cycling routine is OK, I've already debugged it on the serial monitor. The two patterns are fine, each one on it's own. But, when I put everything together, the LEDs don't blink the way they are supposed to do: they will only blink right the first time I press a button.
This is the sketch. I have a feeling this has something to do with my crude debouncing implementation, but I don't know exactly what is happening.
#define RED 9
#define GREEN 8
#define YELLOW 10
#define BUT1 7
#define BUT2 6
byte leds[3] = {RED, GREEN, YELLOW};
void setup()
{
for (byte n = 0; n <= 3; n++)
{
pinMode(leds[n], OUTPUT);
digitalWrite(leds[n], 1);
}
pinMode(BUT1, INPUT_PULLUP);
pinMode(BUT2, INPUT_PULLUP);
}
const byte number_of_programs = 2; // <- update me
void loop()
{
switch ( poll_buttons() )
{
case 1:
program1();
break;
case 2:
program2();
break;
} // end switch
} //end loop
byte poll_buttons()
{
static unsigned int counter = 0;
if (digitalRead(BUT1) == LOW)
{
delay(10);
if (digitalRead(BUT1) == HIGH)
{
counter = counter == number_of_programs ? 1 : counter + 1;
}
} // end BUT1
if (digitalRead(BUT2) == LOW)
{
delay(10);
if (digitalRead(BUT2) == HIGH)
{
counter = counter < 1 ? number_of_programs : counter - 1;
}
} // end BUT 2
return counter;
} // end function
void blink_red(unsigned int period)
{
static boolean on_or_off = 1;
static unsigned long elapsed;
if ( (millis() - elapsed) > period )
{
elapsed = millis();
on_or_off = !on_or_off;
} // end if
digitalWrite(RED, on_or_off);
}
void blink_green(unsigned int period)
{
static boolean on_or_off = 1;
static unsigned long elapsed;
if ( (millis() - elapsed) > period )
{
elapsed = millis();
on_or_off = !on_or_off;
} //end if
digitalWrite(GREEN, on_or_off);
}
void blink_yellow(unsigned int period)
{
static boolean on_or_off = 1;
static unsigned long elapsed;
if ( (millis() - elapsed) > period )
{
elapsed = millis();
on_or_off = !on_or_off;
}
digitalWrite(YELLOW, on_or_off);
}
// OK, let's define some blinking programs
void program1()
{
blink_red(200);
blink_yellow(250);
blink_green(300);
}
void program2()
{
blink_red(350);
blink_yellow(350);
blink_green(350);
}