class PushButton
{
public:
PushButton(uint8_t pin) // Constructor (executes when a PushButton object is created)
: pin(pin) { // remember the push button pin
pinMode(pin, INPUT_PULLUP); // enable the internal pull-up resistor
};
bool isPressed() // read the button state check if the button has been pressed, debounce the button as well
{
bool pressed = false;
bool state = digitalRead(pin); // read the button's state
int8_t stateChange = state - previousState; // calculate the state change since last time
if (stateChange == falling) { // If the button is pressed (went from high to low)
if (millis() - previousBounceTime > debounceTime) { // check if the time since the last bounce is higher than the threshold
pressed = true; // the button is pressed
}
}
if (stateChange == rising) { // if the button is released or bounces
previousBounceTime = millis(); // remember when this happened
}
previousState = state; // remember the current state
return pressed; // return true if the button was pressed and didn't bounce
};
private:
uint8_t pin;
bool previousState = HIGH;
unsigned long previousBounceTime = 0;
const static unsigned long debounceTime = 25;
const static int8_t rising = HIGH - LOW;
const static int8_t falling = LOW - HIGH;
};
PushButton incrementButton = { 10 };
PushButton decrementButton = { 9 };
const uint8_t ledPins[] = { 2, 3, 4, 5, 6, 7, 8};
const uint8_t nb_leds = sizeof(ledPins) / sizeof(ledPins[0]);
void setup() {
for (uint8_t i = 0; i < nb_leds; i++)
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins [0], HIGH);
}
void loop() {
static uint8_t selection = 0;
if (incrementButton.isPressed()) {
digitalWrite (ledPins[selection], LOW);
selection++;
if (selection == nb_leds)
selection = 0;
digitalWrite (ledPins[selection], HIGH);
}
if (decrementButton.isPressed()) {
digitalWrite (ledPins[selection], LOW);
if (selection == 0)
selection = nb_leds;
selection--;
digitalWrite (ledPins[selection], HIGH);
}
}
Connect two push buttons between pins 9 and 10 and ground (no resistors required, because the internal resistors will be used.
Connect 7 LEDs + current limiting resistors to pins 2-8.
Try to understand what's happening before blindly copying the code I posted. If you don't understand something, just ask.
Pieter