Push-buttons and resistors - why and how?

I know that yo have to add a resistor when connecting a push-button to the Arduino, otherwise the output gets unstable and displays both LOW and HIGH randomly. But WHY is that? And how do I know what kind of resistor I need for the button?

Example:

You don't need to add a resistor if you use pinMode INPUT_PULLUP which does it for you. The reason one is needed is roughly because pins with nothing connected to them act like little aerials and pick up all sorts of random signals from the air.

If for some reason you do want to use an external resistor something like 10K either to 5V or to ground usually works.

Steve

Look at the symbol for a MOSFET, the gate is drawn a bit like a capacitor and isn't connected to anything. That's because in a real MOSFET it behaves like a very small capacitor and isn't connected to anything. In logic circuits 1 and 0 are defined as particular voltages, usually 0V or close to 0V for a 0 and whatever the supply voltage is, usually 3.3V or 5V, or close to the supply voltage for a 1. Not connected to anything is therefore neither a 0 or a 1. A push button that isn't pushed isn't connected to anything. An input that is connected to a push button that isn't pushed isn't connected to anything. The input is therefore not properly defined as 0 or 1. As the electronics in the chip can only see a 0 or a 1 it will see one of these, but which one depends on what random electrical crap is picked up by the pin. Adding a resistor makes sure that when the button isn't pressed the input is definitely connected to 0 or 1, whichever it is you want.

Might be worth mentioning though, that there’s a reason it’s a resistor not just a piece of wire. A wire would do as good job of connecting, better maybe, and be simpler…

Reason is that if the pin was connected to one side (either 0 or 5) with a wire, then connected to the other side (5 or 0) with a switch (which is just another piece of wire), there would be a dead short between the 0 and 5V.

So a resistor in the order of 10’s of k’s prevents a dead short, while at the same time being large enough to limit the current so there’s not a huge power drain whenever the switch is closed.

Imagine in this pic (from here) the resistor was a wire (a 0 Ohm resistor, for all intents and purposes) and you closed the switch…