// Momentary switch latching
// https://forum.arduino.cc/t/momentary-switch-latching/1419213
const int button1Pin = A5; // Pin where the momentary switch is connected
const int button2Pin = A3; // Pin where the momentary switch is connected
const int led1Pin = 9; // Pin where the ouput is connected
const int led2Pin = 10; // Pin where the ouput is connected
int button1State = 0; // Variable for reading the button status
int lastButton1State = 0; // Variable for storing the last button state
int led1State = LOW; // Variable for storing the LED state
int button2State = 0; // Variable for reading the button status
int lastButton2State = 0; // Variable for storing the last button state
int led2State = LOW; // Variable for storing the LED state
void setup() {
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
// initialise variables
lastButton1State = digitalRead(button1Pin);
lastButton2State = digitalRead(button2Pin);
}
void loop() {
button1State = digitalRead(button1Pin);
if (button1State != lastButton1State) {
lastButton1State = button1State;
if (button1State == HIGH) {
led1State = !led1State;
digitalWrite(led1Pin, led1State);
}
delay(50); // Debounce delay
}
button2State = digitalRead(button2Pin);
if (button2State != lastButton2State) {
lastButton2State = button2State;
if (button2State == HIGH) {
led2State = !led2State;
digitalWrite(led2Pin, led2State);
}
delay(50); // Debounce delay
}
}Btn1
Btn2
Led1
Led2