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!

int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonApin, INPUT_PULLUP);
pinMode(buttonBpin, INPUT_PULLUP);
}
void loop()
{
if (digitalRead(buttonApin) == LOW and digitalRead(buttonBpin) == LOW)
{
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
}
else if (digitalRead(buttonApin) == LOW or digitalRead(buttonBpin) == LOW)
{
digitalWrite(ledPin, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
}
}Now your LED should flash when you hold down both buttons, stay of when you are holding down one button, and turn off if you let go of both buttons.
For an overview of several concepts used in these examples, check out the slideshow below.
Last updated
Was this helpful?