/*
Interlocking Monoflop
https://forum.arduino.cc/t/delay-turning-led-off-after-button-press/1105635/
2023-03-23 by noiasca
to be deleted: 2023-06
*/
void release(); // only a prototype - just the signature of a function implemented later in the code
// a class for one LED one button
class Monoflop {
const uint8_t buttonPin; // the input GPIO, active LOW
const uint8_t ledPin; // the output GPIO, active
const uint8_t relayPin; // the output for relay
uint32_t previousMillis = 0; // time management
bool state = false; // active or inactive
public:
Monoflop(uint8_t buttonPin, uint8_t ledPin, uint8_t relayPin) : buttonPin{buttonPin}, ledPin{ledPin}, relayPin{relayPin}
{}
void begin() { // to be called in setup()
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(relayPin, OUTPUT);
}
void off() { // handles switching off
digitalWrite(ledPin, LOW);
digitalWrite(relayPin, LOW);
state = false;
}
void update(uint32_t currentMillis = millis()) { // to be called in loop()
uint8_t buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
release();
previousMillis = currentMillis;
digitalWrite(ledPin, HIGH);
digitalWrite(relayPin, HIGH);
state = true;
}
if (state && currentMillis-previousMillis > 1000) {
off();
}
}
};
//create 3 instances (each with one button and one led/LED)
Monoflop monoflop[] {
{A0, 12, 9}, // buttonPin, ledPin, relayPin
{A1, 11, 8},
{A2, 10, 7},
{A3, 255, 255},
};
void release(){ // release all outputs
for (auto &i : monoflop) i.off();
}
void setup() {
for (auto &i : monoflop) i.begin();
}
void loop() {
for (auto &i : monoflop) i.update();
}