Hi all,
I'm new to Arduino and I have a pushbutton (KD2-22) which is an on (on) button with a built in LED. I'm trying to activate the LED when I press the button once and deactivate the LED when I press the button again.
Here's some code I found which should help with the bouncing I also found:
* Created by ArduinoGetStarted.com
* This example code is in the public domain
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-library
* This example reads the state of a button with debounce and print it to Serial Monitor.
*/
#include <ezButton.h>
const int LED = 3;
ezButton button(2); // create ezButton object that attach to pin 7;
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(9600);
button.setDebounceTime(50); // set debounce time to 50 milliseconds
}
void loop() {
button.loop(); // MUST call the loop() function first
if(button.isPressed())
Serial.println("The button is pressed");
digitalWrite(LED, HIGH);
if(button.isReleased())
Serial.println("The button is released");
digitalWrite(LED, LOW);
}
My problem is the LED is always on when I upload the code. It seems like the button is registered in pressed state from the beginning. When I press the button the serial monitor writes "Released" so it's opposite from my own logic. Maybe this code doesn't work with this particular switch.
Any help or guidance would be greatly appreciated. Thanks