// this code works fine and calculates the total time each LED is on
const uint8_t b1 {4}; // Button
const uint8_t b2 {22}; // Button
const uint8_t b3 {15}; // Button
const uint8_t b4 {16}; // 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 r4 {23}; // 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
bool isOn; // flag to track if the LED is currently on
public:
Indicator(uint8_t buttonPin, uint8_t relayPin) : buttonPin{buttonPin}, relayPin{relayPin}, onTime{0}, totalTime{0}, isOn{false}
{}
void begin() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(relayPin, OUTPUT);
}
void update() {
uint8_t buttonState = digitalRead(buttonPin);
if (buttonState == LOW && !isOn) {
digitalWrite(relayPin, HIGH);
onTime = millis(); // record the time the LED was turned on
isOn = true;
} else if (buttonState == HIGH && isOn) {
digitalWrite(relayPin, LOW);
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");
isOn = false;
}
}
};
//create 4 indicators (each with one button and one relay/LED)
Indicator indicator[] {
{b1, r1},
{b2, r2},
{b3, r3},
{b4, r4},
};
void setup() {
Serial.begin(115200);
while (!Serial); // wait for the serial monitor to open
for (auto &i : indicator) i.begin();
}
void loop() {
for (auto &i : indicator) {
i.update();
}
}