So you want to toggle the loads? (I.e. one press = on, second press = off.)
Then you need to debounce the pushbuttons, and remember the previous states in order to detect the falling edges:
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 isFalling() // read the button state check if the button has been pressed, debounce the button as well
{
bool falling = false;
bool state = digitalRead(pin); // read the button's state
int8_t stateChange = state - previousState; // calculate the state change since last time
if (stateChange == fallingEdge) { // 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
falling = true; // the button is pressed
}
}
if (stateChange == risingEdge) { // if the button is released or bounces
previousBounceTime = millis(); // remember when this happened
}
previousState = state; // remember the current state
return falling; // return true if the button was pressed and didn't bounce
};
private:
uint8_t pin;
bool previousState = HIGH;
unsigned long previousBounceTime = 0;
const unsigned long debounceTime = 25;
const int8_t risingEdge = HIGH - LOW;
const int8_t fallingEdge = LOW - HIGH;
};
const uint8_t ledPin_A = 2;
const uint8_t ledPin_B = 3;
const uint8_t ledPin_C = 4;
PushButton button_A = { 9 };
PushButton button_B = { 10 };
PushButton button_C = { 11 };
void setup() {
pinMode(ledPin_A, OUTPUT);
pinMode(ledPin_B, OUTPUT);
pinMode(ledPin_C, OUTPUT);
}
void loop() {
static bool ledState_A = false;
static bool ledState_B = false;
static bool ledState_C = false;
if (button_A.isFalling()) {
ledState_A = !ledState_A; // Toggle the LED state
digitalWrite(ledPin_A, ledState_A); // Write the state to the pin
}
if (button_B.isFalling()) {
ledState_B = !ledState_B;
digitalWrite(ledPin_B, ledState_B);
}
if (button_C.isFalling()) {
ledState_C = !ledState_C;
digitalWrite(ledPin_C, ledState_C);
}
}
Pieter