Help with pushbutton with built in LED

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 :slight_smile:

Where do you do: ? :thinking:

digitalWrite(LED, LOW);


Probably meant:

  if(button.isPressed())
{
    Serial.println("The button is pressed");
    digitalWrite(LED, HIGH);
}

BTW

1 Like

Thanks for responding so quickly! I have updated the code with the missing LED low statement. I will look at the diagram provided.

Because you didn't add curly braces, only the Serial.prinln() statement is executed conditionally.

Do not edit your previous posts as that destroys the flow of responses.

If you make changes, add those to a new post.


As told to you in post #2


  if(button.isPressed())
{
    Serial.println("The button is pressed");
    digitalWrite(LED, HIGH);
}

Noted - thanks.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.