Now the long story. The Arduino IDE 1.0.1 forward has added a very convenient argument to the pinMode() function for using switches. Instead of just setting a switch pin to pinMode(switchPin, INPUT) you can use pinMode(switchPin, INPUT_PULLUP). This uses the Arduino's internal resistors to pull a switch pin HIGH by default so you don't get fluctuating readings on your switch. The switch is really easy to wire this way, just wire from the input pin to the switch, then to ground. When you want to read whether the switch is pressed, use the condition if(digitalRead(switchPin==LOW)).
Image source: arduino.cc |
Without the use of the INPUT_PULLUP argument a switch has to be wired with a pull-up or pull-down configuration, which is a bit more complicated. This Ladyada tutorial covers the wiring of pull-up and pull-down resistors very nicely. The image below uses a pull-up resistor, in which the switch is connected on one side to its input pin with a 100 ohm resistor and to Vin with a 10K ohm resistor, and then to ground on its other side, pulling it high by default.
Image source: ladyada.net |