About The Project
In this project, we will learn how to interface an Arduino Uno board with a button switch and an LED. The LED will turn ON when the button switch is pressed and will remain ON even after the button is released.
Button
A button switch works by allowing or interrupting the flow of electricity in a circuit.
- Open State (Not Pressed):
- When the button is not pressed, the circuit is open, meaning no current flows through it.
- Closed State (Pressed):
- When the button is pressed, it closes the circuit, allowing current to flow through.
Circuit Wiring
Program Code
// button – LED
// www.matthewtechub.com
int buttonPin = 8;
int ledPin=6;
int buttonState;
void setup()
{
// initialize the pushbutton pin as an pull-up input
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the state of the switch/button:
buttonState = digitalRead(buttonPin);
if (buttonState==0)
digitalWrite(ledPin,HIGH);
}
- When the button is not pressed, the button pin reads HIGH due to the internal pull-up resistor.
- When the button is pressed, the button pin reads LOW, and the LED is turned on.
- The LED stays on even after the button is released.
Code Explanation
int buttonPin = 8;
int ledPin=6;
int buttonState;
- buttonPin = 8: The button is connected to digital pin 8.
- ledPin = 6: The LED is connected to digital pin 6.
- buttonState: Stores the current state of the button (HIGH or LOW).
void setup()
{
// initialize the pushbutton pin as an pull-up input
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
- pinMode(buttonPin, INPUT_PULLUP): Configures the button pin as an input with an internal pull-up resistor, which keeps the pin HIGH when the button is not pressed and LOW when pressed.
- pinMode(ledPin, OUTPUT): Configures the LED pin as an output.
void loop() {
// read the state of the switch/button:
buttonState = digitalRead(buttonPin);
if (buttonState==0)
digitalWrite(ledPin,HIGH);
}
buttonState = digitalRead(buttonPin): Reads the current state of the button.
- if (buttonState == 0): Checks if the button is pressed (button state is LOW).
- digitalWrite(ledPin, HIGH): Turns on the LED by setting the LED pin HIGH when the button is pressed.
Try Yourself
Modify the program code if you want the LED to turn off after releasing the button.
Just try…