Sub topic 2
Fixing it with an external pull-down resistor
This chapter assumes you know the basic sketch structure (setup and loop), Ohm's law, breadboard wiring, and how to drive an LED with digitalWrite.
A floating input is a pin connected to nothing. It reads HIGH or LOW at random. A resistor that ties the pin to a known voltage fixes this. A pull-down resistor ties the pin to GND, so the pin reads LOW when the button is open.
Wiring a pull-down
Connect the button between the pin and 5V. Connect a 10 kΩ resistor between the pin and GND. When the button is open, the resistor holds the pin at 0 V. When the button closes, the pin connects to 5 V. The button's current overpowers the weak pull-down, so the pin reads HIGH.
const int buttonPin = 2;
const int ledPin = 13;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (digitalRead(buttonPin) == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}Fixing it with an external pull-up resistor
A pull-up resistor works the opposite way. It ties the pin to 5V, and the button connects the pin to GND. The pin reads HIGH when the button is open and LOW when it is pressed. Use a 10 kΩ resistor here too.
Using the internal pull-up with INPUT_PULLUP
The microcontroller on the Uno has built-in pull-up resistors, rated at about 20 to 50 kΩ. Calling pinMode(pin, INPUT_PULLUP) enables one. The button then needs only one wire to the pin and one to GND.
const int buttonPin = 2;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int level = digitalRead(buttonPin);
if (level == LOW) {
Serial.println("pressed");
} else {
Serial.println("released");
}
delay(200);
}Reading inverted logic: pressed is LOW
With INPUT_PULLUP, a press pulls the pin to GND, so the logic is inverted. Pressed reads LOW, and released reads HIGH. Compare against LOW in your code, not HIGH. Name the constants in your sketch if that helps you keep track.
Exercise
Exercise
In the pull-down circuit, what does the pin read when the button is open?
Show answer
LOW. The 10 kΩ resistor ties the pin to GND, so the pin sits at 0 V.