GSwA : Using a Pushbutton to Control the LED

I'm reading the book Getting Started with Arduino (Make:PROJECTS). I think most people here are familiar with this book.

I constructed the circuit as can be seen on page 43, typed the code and... it works. When I push the button, the led turns on, when I release the button the led goes off.

I do understand the code, but the circuit is not being explained. Why do I need to connect the Gnd to PIN7, to make this work, if there is no voltage applied to PIN7 it should be LOW or shouldn't?

If I disconnect all wires the led turns on just by coming near it with my fingers (not actually touching anything).

So I changed the code to turn off the led when PIN7 is HIGH and turn on the led when PIN7 is LOW. This works as expected when all wires are connected. I push the button the led turns off, I release the button the led turns on again.

Now the really strange thing, I disconnect all wires as I did before and would expect to turn off the led just by coming near it with my fingers... It stays on, just dims a little bit and starts flickering when I move my fingers away a little further.

Does anybody know what's going on and why it's behaving the way it does? ::) It's probably very logic but I need to understand it to be able to design my own connection layouts.

Please share the code as we do not all have the book :) In the last case when the button is disconnected the pin fluctuates between LOW and HIGH as it is not connected to 0V or 5V. The arduino therefor swithes the LED with the same rythm.

Please read the tutorial about the pins and their behavior http://arduino.cc/en/Tutorial/DigitalPins may explain quite a lot.

Thnx Rob, that link actually answered my question ;D

In the book they use a pulldown resistor (resistor to ground) to get PIN7 to LOW and then a button to connect PIN7 to the 5V to get it to HIGH.

Now when the button is pressed it turns the LED on with the following code:

  // check whether the input is HIGH (button pressed)
  if (val == HIGH) { 
    digitalWrite(LED, HIGH); // turn LED ON
  } else {
    digitalWrite(LED, LOW);
  }
}

With the link Rob gave me I added the line to 'void setup':

digitalWrite(BUTTON, HIGH);

(that's the internal PULLUP resistor, instead of the external pulldown resistor)

Next I removed all connections and just connected the button between PIN7 and GND. Changed the code to turn on the led if the input is LOW or else turn off the led.

So now I can turn the led by pressing the button with only the button connected to the board. :)