#include <Bounce2.h>
const int BUTTON_COUNT = 4;
const int16_t DEBOUNCE_DELAY = 50;
const uint8_t buttonPins[BUTTON_COUNT] = {2, 4, 6, 8};
const uint8_t ledPins[BUTTON_COUNT] = {3, 5, 7, 9};
Bounce buttons[BUTTON_COUNT];
uint8_t ledStates[BUTTON_COUNT];
void setup() {
for (int i = 0; i < BUTTON_COUNT; i++) {
buttons[i].attach(buttonPins[i], INPUT);
buttons[i].interval(DEBOUNCE_DELAY);
pinMode(ledPins[i], OUTPUT);
ledStates[i] = LOW;
digitalWrite(ledPins[i], ledStates[i]);
}
}
void loop() {
// Update the debouncers.
for (int i = 0; i < BUTTON_COUNT; i++)
buttons[i].update();
// When the first button is pressed:
if (buttons[0].rose()) {
// Light up the first LED.
digitalWrite(ledPins[0], HIGH);
// and turn off all the others.
for (int i = 1; i < BUTTON_COUNT; i++) {
ledStates[i] = LOW;
digitalWrite(ledPins[i], ledStates[i]);
}
}
// When the first button is released:
if (buttons[0].fell()) {
// turn off the first LED.
digitalWrite(ledPins[0], LOW);
}
// When any other button is pressed:
for (int i = 1; i < BUTTON_COUNT; i++) if (buttons[i].rose()) {
// Toggle its state.
ledStates[i] = !ledStates[i];
digitalWrite(ledPins[i], ledStates[i]);
}
}
Edit: In order for the first button to only turn off LEDs 1 and 2, the lines
// and turn off all the others.
for (int i = 1; i < BUTTON_COUNT; i++) {
ledStates[i] = LOW;
digitalWrite(ledPins[i], ledStates[i]);
}
should be replaced by:
// and turn off LEDs 1 and 2.
for (int i = 1; i <= 2; i++) {
ledStates[i] = LOW;
digitalWrite(ledPins[i], ledStates[i]);
}