Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Button

Outline:
This lesson will teach you how to use a button to turn an LED on and off.

Materials
Uno Board x 1
USB cable x 1
Button x 1
Resistor (10k Ohm) x 1
Resistor (220 Ohm) x 1
Jumper wires (few pcs)
Breadboard x 1
Red LED x 1
Product Description

Buttons are a common component used to control electronic devices. They are
usually used as switches to connect or disconnect circuits.
For example, pressing any button on the phone, the backlight will light up
Note
In order to avoid electrical interference, a pull-down resistor is used. This
means a 1K–10KΩ resistor is connected between the button port and GND

Wiring Diagram

Code:
const int keyPin = 12; //the number of the key pin
const int ledPin = 13;//the number of the led pin
void setup()
{
pinMode(keyPin,INPUT);//initialize the key pin as input
pinMode(ledPin,OUTPUT);//initialize the led pin as output
}
void loop()
{
//read the state of the key value
//and check if the kye is pressed
//if it is,the state is HIGH
if(digitalRead(keyPin) ==HIGH )
{
digitalWrite(ledPin,HIGH);//turn on the led
}
else
{
digitalWrite(ledPin,LOW);//turn off the led
}
}

Results
1) The LED doesn't not light up when the button isn't pressed, as shown on the
picture like below:
2)After pressing, the LED lights up, as shown on the picture like below:

You might also like