[sourcecode language=”plain”]
const int buttonPin = 2; // The pin that the button is connected to
int buttonState = LOW; // The current state of the button
int lastButtonState = LOW; // The previous state of the button
unsigned long lastDebounceTime = 0; // The last time the button was debounced
unsigned long debounceDelay = 50; // The debounce time in millisecondsvoid setup() {
pinMode(buttonPin, INPUT_PULLUP); // Configure the button pin as an input with pullup resistor
Serial.begin(9600); // Initialize serial communication for debugging
}void loop() {
int reading = digitalRead(buttonPin); // Read the current state of the button
if (reading != lastButtonState) { // If the state has changed
lastDebounceTime = millis(); // Record the time of the state change
}
if ((millis() – lastDebounceTime) > debounceDelay) { // If the debounce delay has elapsed
if (reading != buttonState) { // If the state is still different from the last recorded state
buttonState = reading; // Update the current state of the button
if (buttonState == HIGH) { // If the button is pressed
Serial.println("Button pressed!");
// Insert your action here
}
}
}
lastButtonState = reading; // Record the current state as the last state for the next iteration
}
<pre>
[/sourcecode]
const int buttonPin = 2; // The pin that the butto…
12
Apr