// https://wokwi.com/projects/408924267717447681
// https://forum.arduino.cc/t/making-a-led-switch-but-its-a-bit-more-complex/1300283
const byte buttonPin = 2;
const byte toggleLED0 = 12;
const byte toggleLED1 = 11;
# define PRESST LOW
void setup() {
Serial.begin(115200);
Serial.println("Ready.\n");
pinMode(buttonPin, INPUT_PULLUP);
pinMode(toggleLED0, OUTPUT);
pinMode(toggleLED1, OUTPUT);
}
bool prevousButton; // true means button is pressed. down. shorted.
void loop() {
bool thisButton = digitalRead(buttonPin) == PRESST; // true if switch is closed
// detect state change?
if (thisButton != prevousButton) {
// yes the button is different to last time, set flags
bool leadingEdge = thisButton && !prevousButton; // button is down and wasn't, became pressed
bool trailingEdge = !thisButton && prevousButton; // button is up and wasn't, became released
// record for state change detection
prevousButton = thisButton;
// just toggle. one on the leading edge
if (leadingEdge)
digitalWrite(toggleLED0, digitalRead(toggleLED0) == HIGH ? LOW : HIGH);
// and ther other one on the troaling edge
if (trailingEdge)
digitalWrite(toggleLED1, digitalRead(toggleLED1) == HIGH ? LOW : HIGH);
delay(50); // poor man's debounce. only when the state change is done
}
}