Hello
Check out this sketch. The sketch is using an array to collect all relevant information like pin addresses, states and times. Inside the loop() a button debouncing, state change detection and led action will take place on this information.
/* BLOCK COMMENT
ATTENTION: This Sketch contains elements of C++.
https://www.learncpp.com/cpp-tutorial/
https://forum.arduino.cc/t/toggle-button-with-timed-on-off-help/927965
*/
#define ProjectName "Toggle button with timed on off help"
// HARDWARE SETTINGS
// YOU MAY NEED TO CHANGE THESE CONSTANTS TO YOUR HARDWARE AND NEEDS
constexpr byte ButtonPin {A0}; // portPin o---|button|---GND
constexpr byte Led1Pin {3}; // portPin o---|220|---|LED|---GND
constexpr byte Led2Pin {5}; // portPin o---|220|---|LED|---GND
#define OutPutTest
// CONSTANT DEFINITION
enum {Button_};
enum {Led1, Led2};
enum {One, Two};
constexpr byte Input_[] {ButtonPin};
constexpr byte Output_[] {Led1Pin, Led2Pin};
constexpr unsigned long OutPutTestTime {1000};
// VARIABLE DECLARATION AND DEFINITION
unsigned long currentTime;
struct TOOGLEBUTTON {
byte pin;
bool statusQuo;
byte led [sizeof(Output_)];
unsigned long stamp;
unsigned long duration;
} toogleButton {Input_[Button_], false, {Output_[Led1], Output_[Led2]}, 0, 20};
// -------------------------------------------------------------------
void setup() {
Serial.begin(9600);
Serial.println(F("."));
Serial.print(F("File : ")), Serial.println(__FILE__);
Serial.print(F("Date : ")), Serial.println(__DATE__);
Serial.print(F("Project: ")), Serial.println(ProjectName);
pinMode (LED_BUILTIN, OUTPUT); // used as heartbeat indicator
// https://www.learncpp.com/cpp-tutorial/for-each-loops/
for (auto Input : Input_) pinMode(Input, INPUT_PULLUP);
for (auto Output : Output_) pinMode(Output, OUTPUT);
#ifdef OutPutTest
// check outputs
for (auto Output : Output_) digitalWrite(Output, HIGH), delay(OutPutTestTime);
for (auto Output : Output_) digitalWrite(Output, LOW), delay(OutPutTestTime);
#endif
digitalWrite(toogleButton.led[Led1], HIGH);
}
void loop () {
currentTime = millis();
digitalWrite(LED_BUILTIN, (currentTime / 500) % 2);
// debounce button
if (currentTime - toogleButton.stamp >= toogleButton.duration) {
toogleButton.stamp = currentTime;
// check state change
bool stateNew = !digitalRead(toogleButton.pin);
if (toogleButton.statusQuo != stateNew) {
toogleButton.statusQuo = stateNew;
// take action on change
if (stateNew) {
digitalWrite(toogleButton.led[One], !digitalRead(toogleButton.led[One]));
digitalWrite(toogleButton.led[Two], !digitalRead(toogleButton.led[Two]));
}
}
}
}
Have a nice day and enjoy coding in C++.