Simple button project will not work

Hey guys
Please bear with me because I am a total newbie at this stuff.
I am trying to do a very simple project in which a button types the letter w into the serial monitor when it is pressed.

My code:


#include <Keyboard.h>

const int buttonPin = 5;

int buttonState = 0;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  
  buttonState = digitalRead(buttonPin);


  if(buttonState == HIGH)
  {
       
Serial.println("w");
delay(1500);
  }

}

My project:

What happens is it seems that my hand is causing some kind of interference when it is roughly an inch away. Only then, when my hand is near, will the letter w be printed in the serial monitor. When I press the button, the w's stop printing.

I have done simple projects like this with a button before and this has never happened.

I might also add that when I put a LED after the button (using no code) the LED would correctly respond to the button being pressed. So this is not an issue with the button... I think.

Please help, I'm very confused. :grinning:

You should connect a resistor (10K is a good value) between pin 5 and GND, otherwise it reads random levels when the button is not pressed.

1 Like

Did you do initialize the pins as INPUT_PULLUP to actually enable the internal pull up resistor. Doing this will eliminate an external resistor. I would not recommend this in a real application but it should be fine for your test.

2 Likes

If so, the logic is wrong because it would send "w" when the button is not pressed. That's why I assumed that the button is connected to the 5V terminal.

Try this instead.

#include <Keyboard.h>

const int buttonPin = 5;

void setup() 
{
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() 
{  
  int buttonState = digitalRead(buttonPin);
  if(buttonState == LOW)
  {      
    Serial.println("w");
    delay(1500);
  }
}

As-is, your button input will be floating and reading the input will be indeterminate (even when it's not pressed, you could read either HIGH or LOW.

My change makes the input configuration INPUT_PULLUP ensures that when the button is not pressed, the input will be pulled up to V+ and read HIGH consistently, and LOW when pressed (connected to Ground) consistently.

Make sense?

1 Like

Thanks gilshultz! After adding _PULLUP I change HIGH after buttonState == to LOW and it works

1 Like

Thank you! just tried this right before you replied and it worked

1 Like

Is this INPUT_PULLUP specific to arduino leonardo? I do not remember this needing to be used when I used arduino uno (INPUT by itself worked fine)

No. It's there on UNO too. Perhaps the project you used before had an external pull-up or pull-down resistor. But the problem of floating inputs is common to all of electronics.

1 Like

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