Go Down

Topic: [solved] Reading value from button pressed (Read 2240 times) previous topic - next topic

axelleap

Oct 29, 2016, 11:04 am Last Edit: Oct 30, 2016, 03:53 pm by axelleap
Hi,

I have an Arduino Lilypad USB and a Lilypad Button Board. I'm simply trying to read when the button is pressed or not, but that's not working.

I know a little about bouncing, i.e when I press the button and release, it will oscillate back to the High value.

But this does not seem to be a bouncing issue : when I run the following program and don't press the button at all any time, it reads Low and High values alternatively...

What's the problem thanks ?

NB. I have connected the S of the button board to 2 (I also tried A2, A3...) and - to -.

Code: [Select]

int buttonPin = 2;

int nbPressed = 0;

void setup()
{
  pinMode(buttonPin, INPUT);  
   pinMode(13, OUTPUT);

  // Initialize Serial, set the baud rate to 9600 bps.
  Serial.begin(9600);

  nbPressed = 0;  
}


void loop()
{
 digitalWrite(13, HIGH);
  int buttonValue = digitalRead(buttonPin);
  if (buttonValue == LOW) {
    Serial.print("Button is pressed ");
    nbPressed = nbPressed + 1;
    Serial.println(nbPressed);
  } else {
    Serial.println("Button is NOT pressed");
  }

  // Delay so that the text doesn't scroll too fast on the Serial Monitor.
  // Adjust to a larger number for a slower scroll.
  delay(1000);
  digitalWrite(13, LOW);
  delay(500);
}

uxomm

Short Answer:
Change the line
Code: [Select]
pinMode(buttonPin, INPUT);
to
Code: [Select]
pinMode(buttonPin, INPUT_PULLUP);


Background:
Digital inputs need to have defined voltage levels, they should be either "low" or "high".
In your case, if you press the button the level on the input pin will be low, because it is connected (through the button) to GND (you call it "minus").

BUT if the button is NOT pressed there is no defined level on the input pin (neither "high" nor "low") because the "cable" just is connected to "nothing". So your input pin will "float", it will give you "unexpected results", maybe "high" maybe "low".

To solve the problem of floating, an easy way is to use a (relatively) high value resistor to "pull" the input pin "high", while the button is not pressed. This resistor is called "pullup resistor".
As this is a very common problem many microcontrollers have internal pullup resistors that can be activated if needed.

The instruction pinMode(buttonPin, INPUT_PULLUP);
will activate the internal pullup resistor (see: Reference: Digital Pins)
 

 
Always decouple electronic circuitry.

axelleap

Thanks, that works just great, and I wouldn't have found without your answer!
Thanks so much, +reading the reference on digital pins.

Go Up