Digital Inputs
Let's control our LEDs with some pushbuttons!
In this lesson, you will learn to use push buttons with digital inputs to turn an LED on and off. Pressing the button nearer the top of the breadboard will turn the LED on, pressing the other button will turn the LED off.
Parts:
1 - 5mm red LED
1 - 220 ohm resistor
1 - push switches
1 – Assorted Wires
1 - Breadboard
1 - Elego Uno R3
Wiring Diagram:

Code:
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 8; // the number of the pushbutton pin
const int ledPin = 12; // the number of the LED pin
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input pullup:
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (digitalRead(buttonPin) == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
If done right, your LED should turn on when you press the button and it should turn off when you let go of it.
After messing around with this one for a while, try the next one too!
For an overview of several concepts used in these examples, check out the slideshow below.
Last updated
Was this helpful?