Toggle the state of led by using the change in the state of the switch.

Hello friends

I am new to this platform and recently started learning Arduino. I want to toggle the led state if the state of the switch changes. I use this method because I want to control the led with some other inputs along with it so pls help me.

const int buttonPin = 2;
const int ledPin = 13;

int buttonState = 0;
int lastButtonState = 0;

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:

void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
digitalWrite(ledPin, !digitalRead(ledPin));
lastButtonState = buttonState;


StateChangeDetection.ino (663 Bytes)

Doesn't it work?

do you want to check that when the button state changes that it is LOW?

otherwise pressing the button toggles the LED and releasing the button toggles it again