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 off after the button is released.
Program Code
C
// www.matthewtechub.com
//just read button state and switch on led
//while pressing on button
// pinMode ----- INPUT_PULLUP
int buttonPin = 8;
int ledPin = 6;
int buttonState;
void setup()
{
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);
else
digitalWrite(ledPin, LOW);
}
- 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 turns off 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);
else
digitalWrite(ledPin,LOW);
}
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.
- else
- digitalWrite(ledPin, LOW); Turns off the LED by setting the LED pin LOW when the button is released.
Try Yourself
Modify the program to toggle the LED each time the button is pressed.