Sub topic 9
Floating Inputs and `INPUT_PULLUP`
Assume you know the Arduino IDE and the setup() and loop() functions. You should also know that voltage is a difference in electrical potential and that a digital pin reads a logic level.
A digital input should be connected to a definite voltage. It reads HIGH when its voltage is near the board's supply voltage and LOW when its voltage is near ground, or GND. A floating input is a pin that is not connected firmly to either level. It can pick up electrical noise and change between HIGH and LOW unpredictably.
A push button often creates this problem. When the button is open, the input wire has no defined voltage. When it is pressed, it may connect to GND. A resistor can hold the input at a known level while the button is open. This resistor is called a pull-up or pull-down resistor.
The Uno has an internal pull-up resistor on its digital pins. Enable it by using INPUT_PULLUP with pinMode():
const int buttonPin = 2;
const int ledPin = LED_BUILTIN;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
bool pressed = (digitalRead(buttonPin) == LOW);
digitalWrite(ledPin, pressed ? HIGH : LOW);
}Wire one terminal of the button to digital pin 2 and the other terminal to GND. The internal resistor pulls pin 2 toward HIGH when the button is released. Pressing the button connects the pin to GND, so the reading becomes LOW.
This arrangement reverses the usual meaning of the reading:
| Button state | Pin voltage | `digitalRead(buttonPin)` |
|---|---|---|
| Released | Pulled toward 5 V | `HIGH` |
| Pressed | Connected to GND | `LOW` |
The expression digitalRead(buttonPin) == LOW handles this inversion and produces true when the button is pressed.
Common errors
- Using
INPUTwithout an external resistor leaves the input floating when the button is open. - Testing for
HIGHas “pressed” reverses the behavior of an active-low button. - Connecting a button between 5 V and GND without a resistor creates a short circuit when pressed.
- Assuming every board's internal pull-up has the same resistance. The exact value varies, but it is suitable for simple buttons and slow signals.
- Treating rapid changes during a press as multiple intentional presses. Mechanical contacts can bounce. A later project may need software debouncing or a capacitor.
Exercise
A button is connected between pin 4 and GND, and pin 4 is configured with INPUT_PULLUP. What value should the program test for when the button is pressed?
Show answer
Test for LOW. Pressing the button connects the pin to GND, overriding the internal pull-up.