const int switchPin = 13; // Connect the switch to digital pin 2
const int ledPin = 17; // Connect the LED to digital pin 3
int switchState = 0; // variable to store the state of the switch
int lastSwitchState = 0; // variable to store the previous state of the switch
int ledState = LOW; // variable to store the state of the LED (initially off)
void setup() {
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Read the state of the switch
switchState = digitalRead(switchPin);
// Check if the switch state has changed
if (switchState != lastSwitchState) {
// If the new state is HIGH (pressed), toggle the LED
if (switchState == HIGH) {
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
// Save the current switch state for comparison in the next iteration
lastSwitchState = switchState;
// A small delay to debounce the switch (optional, depending on your switch)
delay(50);
}
}