/*
Arduino Forum
Topics: Multi Button Programming
Category: Programming Questions
Link: https://forum.arduino.cc/t/multi-button-programming/1094488
*/
/*
Sketch: sketch.ino
Created: 25-Feb-2023
to be deleted: 2023-04
*/
/*
Author: noiasca
*/
const uint8_t b1 {A2}; // Button
const uint8_t b2 {A1}; // Button
const uint8_t b3 {A0}; // Button
const uint8_t r1 {12}; // Output relay
const uint8_t r2 {11}; // Output relay
const uint8_t r3 {10}; // Output relay
const uint8_t commonStatePin {9}; // Output relay
// a class for one LED one button
class Indicator {
const uint8_t buttonPin; // the input GPIO, active LOW
const uint8_t relayPin; // the output GPIO, active HIGH
public:
static constexpr uint8_t noPin = 255; // dummy value for "no button is pressed"
Indicator(uint8_t buttonPin, uint8_t relayPin) : buttonPin{buttonPin}, relayPin{relayPin}
{}
void begin() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(relayPin, OUTPUT);
}
uint8_t update(){
uint8_t lastActive = noPin;
uint8_t buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
digitalWrite(relayPin, HIGH);
lastActive = buttonPin;
}
else {
digitalWrite(relayPin, LOW);
lastActive = noPin;
}
return lastActive; // returns the button GPIO if it is pressed
}
};
//create 3 indicators (each with one button and one relay/LED)
Indicator indicator[] {
{b1, r1},
{b2, r2},
{b3, r3},
};
void setup() {
for (auto &i : indicator) i.begin();
pinMode(commonStatePin, OUTPUT);
}
void loop() {
bool commonState = HIGH;
for (auto &i : indicator) if (i.update() != Indicator::noPin) commonState = LOW; // if one button reports active, common Relay has to be switched off
digitalWrite(commonStatePin, commonState);
}