I just purchased an arduino kit, and it's been fun to play with.
One of the basic input is using a push button.
In the tutorial, we connect it in between 5V and a digital input, but we also add a 10K ohm resistor between that digital input and ground.
I'd like to know why do we need that resistor?
Poor tutorial. Assumes people don't get the concept of reading a low to start an action, so resistor is used to hold the pin low until the pin is shorted tothe +5 supply - many cases of miswiring result in +5 being shorted to Gnd instead.
Use the internal pullup resistor that is available on all pins, and connect the pin to Gnd to show it is active instead:
pinMode(pinX, INPUT_PULLUP); // input mode with internal pullup resistor enabled.
// wire button to connect pin to Gnd when pressed.
if (digitalRead(pinX) == LOW){
// button is pressed, do something
}
// option:
else {
// button is not pressed, do something else, or ignore
}
You need the resistor because an input on the Arduino that is not connected to anything can "float", and end up at almost any voltage - and randomly read either HIGH or LOW. The resistor "pulls down" the pin to ground to keep it in the LOW state until you push the button to set it at a HIGH state.
A CMOS input is fully isolated from the rest of the chip by a layer of silicon dioxide
which is an extremely good insulator. That layer is the gate oxide of the first FETs
(field-effect transistor) in the input circuitry. Only the voltage on the pin affects the
rest of the chip, there is negligible current flowing (pico amps at most at room temperature).
Thus pins set as inputs pick up any stray signal going, influence of nearby signals,
static charges on nearby insulators, etc etc. Unless you connect them somehow to a
known voltage.
A pull-up or pull-down resistor defines the voltage of the pin (but won't prevent it
responding to the switch shorting it to Vcc (or ground or whatever).