Digital Input: Reading a Push Button
Read a physical button press into your sketch, using the pull-down wiring from Lesson cb-08 and a new function: digitalRead.
You'll need: a push-button, a 10kΩ resistor, jumper wires, a breadboard, and your Uno.
Wire the button exactly as the pull-down circuit from Lesson cb-08: one side of the button to 5V, a 10kΩ resistor from the same side down to GND, and connect that junction to digital pin 2. This guarantees pin 2 reads a clean LOW when the button is open and a clean HIGH when it's pressed — reading a switch with nothing else connected leaves the pin floating (Lesson cb-08 explains exactly why that's unreliable).
void setup() {
pinMode(2, INPUT);
pinMode(13, OUTPUT);
}
void loop() {
int buttonState = digitalRead(2);
digitalWrite(13, buttonState);
}
digitalRead(2) checks pin 2's current voltage and returns either HIGH or LOW, storing it in a variable named buttonState. Feeding that same value straight into digitalWrite(13, buttonState) means the onboard LED mirrors the button in real time — lit exactly while the button is held, dark otherwise.
This read-a-pin, act-on-the-value pattern — check an input, then do something based on what it says — is the shape behind nearly every interactive sketch from here on, however much more complex the "act on it" part eventually gets.