Sub topic 1
Reading a button with digitalRead()
A pushbutton is the simplest input you can attach to a microcontroller. It is also where most beginners first see a sketch behave in ways the code does not seem to explain. This chapter covers what digitalRead() reports, what the pin is measuring, and what happens when you poll a button inside loop(). The later chapters in this tutorial build on this model.
Prerequisites
This chapter assumes you can already do the following:
- Write a basic Arduino sketch with
setup()andloop(). - Call
pinMode(),digitalRead()anddigitalWrite(). - Wire a pushbutton and an LED to a board on a breadboard.
- Read
ifstatements,boolvariables and integer types such asintandunsigned longin C++.
The examples use an Arduino Uno-class board (5 V logic, pin 2 for the button). On other boards the pin numbers or voltages may differ.
What digitalRead() actually reports
digitalRead(pin) returns one of two values, HIGH or LOW. The function returns an int. HIGH is defined as 1 and LOW as 0, so you can use the result directly as a number or a condition.
The pin does not know about buttons. The microcontroller compares the voltage on the pin with internal thresholds and reports the result. On a 5 V ATmega328P, as on the Uno, the datasheet defines these ranges:
| Voltage on the pin | Reading |
|---|---|
| Below about 1.5 V (0.3 × VCC) | `LOW` |
| Between about 1.5 V and 3.0 V | Undefined, may read either way |
| Above about 3.0 V (0.6 × VCC) | `HIGH` |
The undefined zone matters. A pin that sits at 2 V is not "half pressed." It can read HIGH on one pass and LOW on the next. Your wiring must always drive the pin firmly to one side.
Why a pin needs a defined level
A pushbutton is a switch that connects two terminals while pressed. If you wire one terminal to 5 V and the other to the input pin, the pin sees 5 V during a press. While the button is released, the pin is connected to nothing. This state is called floating.
A floating pin is a very high-impedance input. It picks up stray charge from your hand, nearby wires, and mains hum. Reading it gives a result that looks random and can change when you move your hand near the board. This is the most common first bug with buttons.
The fix is to give the pin a default level through a resistor. A resistor to ground is called a pull-down resistor, and a resistor to the supply is called a pull-up resistor. This chapter uses a pull-down resistor because it gives the intuitive result of HIGH when pressed. The next chapter replaces it with the board's internal pull-up, which is how you will wire most buttons.
Wiring with an external pull-down
Connect the parts like this:
- Connect one button terminal to the 5 V pin.
- Connect the opposite terminal to digital pin 2.
- Connect a 10 kΩ resistor from digital pin 2 to GND.
When the button is released, the resistor holds pin 2 near 0 V, so the reading is LOW. When the button is pressed, pin 2 connects directly to 5 V. Only about 0.5 mA flows through the resistor (5 V ÷ 10 kΩ), so the supply is not stressed. The pin reads HIGH.
The 10 kΩ value is a convention, not a requirement. It is small enough to hold the pin firmly at 0 V, yet large enough that a pressed button wastes very little current.
Your first button sketch
This sketch copies the button level straight to the built-in LED. Pin 2 is the input and has no internal resistor enabled, so INPUT is the correct mode here.
const uint8_t BUTTON_PIN = 2;
void setup() {
pinMode(BUTTON_PIN, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
int level = digitalRead(BUTTON_PIN);
digitalWrite(LED_BUILTIN, level);
}Hold the button and the LED lights. Release it and the LED goes out. digitalWrite() accepts the integer from digitalRead() directly, which works because HIGH and LOW are just 1 and 0.
Writing the test as an explicit comparison is clearer when the logic grows:
const uint8_t BUTTON_PIN = 2;
void setup() {
pinMode(BUTTON_PIN, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if (digitalRead(BUTTON_PIN) == HIGH) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
}Both versions behave the same. Use the explicit form when you later need to name the meaning, for example bool isPressed = (digitalRead(BUTTON_PIN) == HIGH);. That one line is the only place that knows which level means "pressed."
Polling: how fast loop() reads
Reading a pin on every pass through loop() is called polling. The Arduino core has no event system for plain pin reads. Your code asks, again and again, "what is the level now?"
Polling is fast. A single digitalRead() takes a few microseconds on an Uno (the core looks up the port and pin, turns off PWM on that pin if needed, then reads the register). The sketch above runs loop() on the order of hundreds of thousands of times per second.
The speed has two consequences:
- Your sketch notices a press almost instantly, which is what you want.
- Your sketch also notices every electrical twitch, and a human press lasts many thousands of loop passes. Anything inside the
ifthat runs "once per pass" will run thousands of times per press.
You can see the second effect by counting passes. This sketch counts how many loop passes occur while the button is held, and prints the total each time the count reaches a multiple of 10,000:
const uint8_t BUTTON_PIN = 2;
unsigned long passesWhilePressed = 0;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT);
}
void loop() {
if (digitalRead(BUTTON_PIN) == HIGH) {
passesWhilePressed++;
if (passesWhilePressed % 10000 == 0) {
Serial.println(passesWhilePressed);
}
}
}Open the Serial Monitor at 9600 baud and hold the button for one second. The count climbs quickly. The exact number depends on the board and the serial speed, but it is far larger than 1. If the code inside the if toggled an LED, the LED would flip thousands of times during a single press, and you could not predict its final state. The chapter "Reacting to a press once, not continuously" fixes this by detecting the change of level, not the level itself.
Level versus event
The distinction above is central to the rest of the tutorial, so it is worth stating plainly.
- A level is the present state of the pin:
HIGHorLOW.digitalRead()gives you a level. - An event is something that happens at one moment, such as "the button was just pressed." A pin never reports events. Your code must construct them by comparing the current level with the previous one.
Most button bugs come from using a level where you meant an event. "The LED is lit while the button is down" is a level behavior. "Each press toggles the LED" is an event behavior and needs memory of the previous reading.
Common errors at this stage
| Symptom | Likely cause | Fix |
|---|---|---|
| LED flickers or changes when you wave a hand near the wires | The pin is floating, with no pull-down or pull-up | Add the 10 kΩ resistor, or use `INPUT_PULLUP` (next chapter) |
| Button always reads `HIGH` | The resistor goes to 5 V instead of GND, or the button is wired across the wrong legs | Check that the resistor goes to GND. Check which button legs are connected internally |
| Button always reads `LOW` | The button's 5 V wire is not connected, or you used the wrong pin number | Re-check the wire from 5 V and the `BUTTON_PIN` constant |
| Reading never changes, no matter what | The pin is set with `pinMode(pin, OUTPUT)` by mistake, or a different pin is wired | Set the pin to `INPUT`. Confirm the pin number |
| Behavior is correct on an Uno but a 3.3 V board is damaged or unreliable | The board's pins are 3.3 V only, and you connected a 5 V supply | Connect the button to the board's own 3.3 V pin |
Pushbuttons with four legs are a frequent source of wiring mistakes. The legs on the same side are internally connected, so a button placed in the wrong orientation can be permanently closed. If the reading never changes, rotate the button 90° on the breadboard and test again.
What to remember for the next chapters
This chapter set up three facts that the rest of the tutorial uses:
digitalRead()reports a voltage level asHIGHorLOW, and only a firmly driven pin gives a trustworthy value.- Polling reads the pin on every pass of
loop(), so one press produces thousands of identical readings. - A level is not an event. Turning levels into events needs stored state.
The next chapter replaces the external resistor with INPUT_PULLUP, which saves a part but inverts the logic: pressed reads LOW. After that, the tutorial turns to the fact that real buttons do not produce a clean single transition.
Exercise
You wire a button between 5 V and pin 2 with a 10 kΩ resistor from pin 2 to GND, and call pinMode(2, INPUT). A sketch toggles an LED inside if (digitalRead(2) == HIGH) { ... }. Holding the button down gives an unpredictable LED state when you let go. Why does this happen, and what kind of fix does the sketch need?
Show answer
With polling, loop() runs thousands of times while the button is held, and each pass inside the if toggles the LED again. The final state depends on whether the number of passes was odd or even. The sketch is acting on the level (HIGH), not on the event (the button just went from LOW to HIGH). It needs to store the previous reading and act only when the current reading differs from it. That is state change detection.
Exercise
On a 5 V Uno, a pin sits at 2.2 V. What does digitalRead() return, and what does this tell you about wiring a button?
Show answer
The result is undefined. 2.2 V is between the low threshold (about 1.5 V) and the high threshold (about 3.0 V), so the pin may read HIGH or LOW and can change between calls. A button circuit must always drive the pin clearly to one side, for example with a pull-down or pull-up resistor, so the pin never rests in this zone.