very simple newbie question about reading a pin as high/low

Hi all,

I have uploaded the following sketch, but the behaviour isn't what i would expect. Pin7 has a non-latching push-to-make switch attached, with the other pin connected to ground.

;
int buttonstate = LOW;
void setup() {
** pinMode(13, OUTPUT);**
** pinMode(7, INPUT);**
}
void loop() {
buttonstate = digitalRead(7);

** if (buttonstate == LOW) {**
** digitalWrite(13, LOW);**
** }**
** else {**
** digitalWrite(13, HIGH);**
** }**

}

Now I would expect that once uploaded, the LED would be off, and when I shorted pin7 to ground, the LED would light up. But the behaviour is inverted - once uploaded, the LED is on, and shorting pin7 turns it off.

Can anyone give me any ideas as to why this doesn't work as I am expecting it to?

Thanks in advance!

The need is to understand how you are electrical wiring up a button switch and how you implement a required pull-down or pull-up resistor for the input pin.

Lefty

I had the same problem. I fixed it, but now I don't remember how, sorry. :~ I need to read more on pull-down and pull-up resistors.

achundee:

  if (buttonstate == LOW) {

digitalWrite(13, LOW);




Now I would expect that once uploaded, the LED would be off, and when I shorted pin7 to ground, the LED would light up.

Why would you expect that? Shorting to ground makes the pin low, so the LED will go off, as you told it to.

OK thanks for that Nick, makes sense. I have changed the code as follows:

;
int buttonstate = HIGH;
void setup() {
** pinMode(13, OUTPUT);**
** pinMode(7, INPUT);**
}
void loop() {
buttonstate = digitalRead(7);

** if (buttonstate == LOW) {**
** digitalWrite(13, HIGH);**
** }**
** else {**
** digitalWrite(13, LOW);**
** }**

}

Now when I start the sketch, pin 13 is HIGH, and when I push the button, the LED flickers slightly yet stays on. Any more ideas please folks?

Floating input.

Groove:
Floating input.

Thanks. So do I need to implement a pull-down resistor into the circuit?

When you ground the pin it is definitely zero. When you don't its value is undefined.

You need to change:

  pinMode(7, INPUT);

to:

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

That implements the internal pullup (not pulldown) resistor. Now both values are defined.

use the internal pull up

void setup() {
pinMode(13, OUTPUT);
pinMode(7, INPUT);
digitalWrite(7, HIGH);
}

Ninja'd by one minute!

thank you all very much for your comprehensive answers - hopefully they will see me right!

Cheers!

Just to explain a bit more, if you don't connect a pin to anything, it doesn't have any particular value. Basically it collects noise from nearby circuits, thus the flickering. You need to ensure it is either low (with an external pulldown) or high (with an internal or external pullup) and then take steps to change the value to the other one via your switch.

ok all working - thanks again people!