Push button with LED
Introduction
In this guide, you will learn to combine a with a making a circuit that turns on the LED when the button is pressed down.
Before continuing this guide it is recommended that you have read- or have basic knowledge about and .
Supplies
- board
- Wires
- 220 Ohm
- (generic)
Circuit
Code
// Push button with LED
// constants will not change value
const int buttonPin = 2; // a pin is assigned to the button
const int LEDPin = 4; // a pin is assigned to the LED
// variables will change
// a variable is assigned to read the status of the button
int buttonState = 0;
// a variable is assigned to set the status of the LED
int LEDState = 0;
void setup() {
// initialize the pushbutton as an input
pinMode(buttonPin, INPUT);
// initialize the LED as an output
pinMode(LEDPin, OUTPUT);
}
void loop() {
// read state of button value. If the read is 'HIGH' the
// button is being pushed. If not the value will be 'LOW'
buttonState = digitalRead(buttonPin);
// check if the button is pressed.
if (buttonState == HIGH) {
// turns on the LED if button is pressed
digitalWrite(LEDPin, HIGH);
} else {
// turns off LED if button is not pressed
digitalWrite(LEDPin, LOW);
}
// adds 1/20 second delay to the program
delay(50);
}
Challenges
Now that you have completed this guide on how to combine a LED with a push button, you can try to change your button circuit to light up one of three different LED’s at a time, every time you press the button. Only one LED should light up at a time. That way you cycle through all three colours with three button presses.