Give the Arduino a real-world input.
Until now the UNO has simply followed a repeating program. A tactile pushbutton lets the circuit react to you. We will use Arduino’s internal pull-up resistor so the wiring stays simple and reliable.
Keep your LED circuit
Leave the LED from Lesson 1 on pin 8. Add one tactile button across the breadboard centre trench.
- One side of button → digital pin 2
- Opposite side → GND rail
- No external pull-down resistor required
Wire the button
Place the common four-leg tactile switch across the breadboard centre gap. Two legs on one side are already connected internally, and the other pair are connected internally. Pressing the button joins the two sides.
Button controls LED
const int ledPin = 8;
const int buttonPin = 2;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}The logic table
| Button | Pin 2 reads | LED |
|---|---|---|
| Not pressed | HIGH | OFF |
| Pressed | LOW | ON |
Reading this table before reading the code is a useful habit. It separates what you want the hardware to do from the syntax used to make it happen.
Experiments
- Reverse the LED behaviour so it is normally on and turns off while the button is pressed.
- Add a 200 ms delay inside the pressed condition. What changes?
- Move the button from pin 2 to pin 4 and update only the pin variable.
Challenge
Make the LED blink only while the button is being held. You already know every instruction needed: digitalRead(), if, digitalWrite() and delay().