Electronics for Building Things · Lesson 5
Why a button needs a resistor, and the "floating pin" gremlin.
So far we've pushed current out to light an LED. Now we read the world in — the first half of any home-automation gadget (a button, a switch, a motion sensor). It seems like you should just wire a button to a pin… and that's exactly the trap this lesson defuses.
A microcontroller input pin reads voltage: near the supply voltage it reads HIGH, near
ground it reads LOW. The danger is in between. If a pin isn't firmly connected to
either, it's floating — and it'll drift, picking up electrical noise from the
air and reading randomly HIGH or LOW
(SparkFun: Pull-up Resistors).
A simple button is just a gap that closes when pressed. Wire one between a pin and 3.3V and you've only defined one state: pressed connects the pin to 3.3V (HIGH). Released leaves the pin connected to nothing — floating. Your code can't trust it.
A pull-up (or pull-down) resistor weakly ties the pin to a known voltage, so it has a definite state when the button isn't pressed.
+. Default reads HIGH; pressing
(button to GND) reads LOW. This "pressed = LOW" is called active-low and is
extremely common.GND. Default LOW; pressing
(button to +) reads HIGH.INPUT_PULLUP). Use them — wire the button between the pin and
GND, enable the internal pull-up, and you skip the external resistor entirely.
Mechanical buttons don't make clean contact — the metal physically bounces for a few milliseconds, so one press can register as several. The cure, called debouncing, is usually a few lines of code (ignore further changes for ~20–50 ms after a press) or a small capacitor. Just know the word — when a button "double-fires," bounce is the culprit.
Recall first.
See also: Glossary · Rules of thumb