5

I use the Pin 7 to get the status of a push button. I put 10Kohm R on the - .

The status is unstable because arduino says thet I push it but it is not true...

int button = 7;
...
// var for reading pushbutton value
int buttonState = 0;
...
buttonState = digitalRead(button);
  if(buttonState == HIGH)
  {
    myFunction();
  }

EDIT :

ARDUINO PIN 7 <---> R 10Kohm <--> [switch] <---> VCC

user2973
  • 1,391
  • 8
  • 12
clement
  • 217
  • 1
  • 3
  • 10

2 Answers2

10

At the moment, your resistor isn't doing anything useful. When your switch is open, the pin is still 'floating', which means it's ending up with random stray readings from nearby electromagnetic fields.

You basically need two connections coming from your Arduino pin. One goes through a resistor straight to ground. The other goes through your switch straight to +5V.

In that case, the resistor is acting as a pull-down, because it holds your pin at Ground whenever the switch is open. You could swap over the ground and +5V, and it the resistor would function as a pull-up instead.

This question deals with the same kind of issue:

Peter Bloomfield
  • 10,982
  • 9
  • 48
  • 87
8

Note that you can also activate the internal pull-up resistor on the pin by first making it an input, then setting it to HIGH.

pinMode(pin, INPUT);
digitalWrite(pin, HIGH);

EDIT:

Based on info from Craig (in the comments below) it's simpler to use the new pinMode INPUT_PULLUP:

pinMode(pin, INPUT_PULLUP);

Then wire the switch directly to ground.

This is the simplest way to wire a pushbutton to an arduino (no resistor needed) but do you need an extra line of code.

Also, the pin will read as HIGH when not pressed, and LOW when pressed (which might seem counter-intuitive)

Duncan C
  • 5,752
  • 3
  • 19
  • 30