// check multiple buttons and toggle LEDs
enum { Off = HIGH, On = LOW };
byte PinsLed [] = { A0, A1, 6 };
#define N_LED sizeof(PinsLed)
byte PinsBut [] = { 7, 8 };
#define N_BUT sizeof(PinsBut)
byte butState [N_BUT];
const unsigned long MsecPeriod = 500;
unsigned long msecLed [N_LED];
bool active [N_LED];
char s [90];
// -----------------------------------------------------------------------------
void
loop ()
{
unsigned long msec = millis ();
for (unsigned n = 0; n < N_LED; n++) {
if (active [n] && msec - msecLed [n] >= MsecPeriod) {
active [n] = false;
digitalWrite (PinsLed [n], Off);
sprintf (s, " %d expired", n);
Serial.println (s);
}
}
for (unsigned n = 0; n < N_BUT; n++) {
byte but = digitalRead (PinsBut [n]);
if (butState [n] != but) {
butState [n] = but;
delay (200); // debounce
if (LOW == but) {
msecLed [n] = msec; // only used if acitve
active [n] = true;
sprintf (s, " %d active", n);
Serial.println (s);
}
}
active [2] = (active [0] && active [1]);
if (active [2]) {
active [0] = active [1] = false;
digitalWrite (PinsLed [2], On);
sprintf (s, " %d on", 2);
Serial.println (s);
}
else if (active [1]) {
digitalWrite (PinsLed [1], On);
sprintf (s, " %d on", 1);
Serial.println (s);
}
else if (active [0]) {
digitalWrite (PinsLed [0], On);
sprintf (s, " %d on", 0);
Serial.println (s);
}
}
}
// -----------------------------------------------------------------------------
void
setup ()
{
Serial.begin (9600);
for (unsigned n = 0; n < sizeof(PinsBut); n++) {
pinMode (PinsBut [n], INPUT_PULLUP);
butState [n] = digitalRead (PinsBut [n]);
}
for (unsigned n = 0; n < sizeof(PinsLed); n++) {
digitalWrite (PinsLed [n], Off);
pinMode (PinsLed [n], OUTPUT);
}
}