Controlling an LED with a Button
Combine digital input and digital output into one real interactive sketch — the button-and-LED circuit that ties Lessons 5-9 together.
You'll need: everything from Lesson ard-05 (button on pin 2), plus a separate LED and resistor on pin 8.
This lesson doesn't introduce anything new on its own — it's a deliberate checkpoint, combining the digital input pattern from Lesson ard-05 with a separate digital output, so you can confirm both work together in a single sketch before moving on to analog and PWM outputs.
void setup() {
pinMode(2, INPUT);
pinMode(8, OUTPUT);
}
void loop() {
int buttonState = digitalRead(2);
if (buttonState == HIGH) {
digitalWrite(8, HIGH);
} else {
digitalWrite(8, LOW);
}
}
This introduces one new piece of syntax: the if...else statement. Rather than feeding the button's value directly into digitalWrite() as Lesson ard-05 did, this version explicitly checks the condition and decides what to do — functionally identical here, but this if...else shape is what you'll reach for once the "what to do" part becomes more than just mirroring one value, like triggering a whole sequence of actions instead of a single output.
If the LED doesn't respond to the button, work through Lesson 20's troubleshooting checklist against this specific sketch: confirm the button's wiring first (Lesson ard-05), then the LED's wiring separately (Lesson cb-02), before suspecting the code itself.