const int buttonPin = 18; // The pin the button is connected to
int buttonState = LOW; // The current state of the button
int lastButtonState = LOW; // The previous state of the button
bool switchState = false; // The state of the switch
void setup() {
Serial.begin(115200); // Initialize serial communication at 115200 baud rate
pinMode(buttonPin, INPUT); // Set the button pin as an input
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the state of the button
// Check if the button was pressed
if (buttonState == HIGH && lastButtonState == LOW) {
switchState = !switchState; // Toggle the switch state
if (switchState) {
Serial.println("switch on...");
} else {
Serial.println("switch off...");
}
}
lastButtonState = buttonState; // Save the current state as the last state
delay(50); // Debounce delay
}