// this code works fine and calculate total time of each led on
const uint8_t b1 {4}; // Button
const uint8_t b2 {22}; // Button
const uint8_t b3 {15}; // Button
const uint8_t r1 {21}; // Output relay
const uint8_t r2 {19}; // Output relay
const uint8_t r3 {18}; // Output relay
const uint8_t commonStatePin {5}; // 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
unsigned long onTime; // the time the LED was turned on
unsigned long totalTime; // the total time the LED was on
public:
static uint8_t lastActive; // the last pressed button
static constexpr uint8_t noPin = 255; // dummy value for "no button is pressed"
Indicator(uint8_t buttonPin, uint8_t relayPin) : buttonPin{buttonPin}, relayPin{relayPin}, onTime{0}, totalTime{0}
{}
void begin() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(relayPin, OUTPUT);
}
void update(){
uint8_t buttonState = digitalRead(buttonPin);
if (buttonState == LOW && lastActive == noPin) {
digitalWrite(relayPin, HIGH);
lastActive = buttonPin;
onTime = millis(); // record the time the LED was turned on
}
else if (buttonState == HIGH && lastActive == buttonPin) {
digitalWrite(relayPin, LOW);
lastActive = noPin;
totalTime += millis() - onTime; // add the time the LED was on to the total time
Serial.print("LED ");
Serial.print(relayPin);
Serial.print(" was on for ");
Serial.print(totalTime / 1000.0); // convert milliseconds to seconds
Serial.println(" seconds");
}
}
};
uint8_t Indicator::lastActive = Indicator::noPin; // initialize a static class member
//create 3 indicators (each with one button and one relay/LED)
Indicator indicator[] {
{b1, r1},
{b2, r2},
{b3, r3},
};
void setup() {
Serial.begin(9600);
while (!Serial); // wait for the serial monitor to open
for (auto &i : indicator) i.begin();
pinMode(commonStatePin, OUTPUT);
}
void loop() {
bool commonState = HIGH;
for (auto &i : indicator) {
i.update();
if (i.lastActive != Indicator::noPin) commonState = LOW; // if one button reports active, common Relay has to be switched off
}
digitalWrite(commonStatePin, commonState);
delay(2000);
}