how to control LED using Button switch with Arduino uno
In this tutorial,we will learn how to detect the state of a button,and then toggle the state of the LED based on the state of the button
1 x Arduino Uno
1 x USB Cable
1 x Button
1 x LED
1 x 10kΩ Resistor
1 x 220Ω Resistor
1 x Breadboard
1 x Several jumper wires
Principle of operation
Buttons are a common component used to control electronic devices. They are usually used as switches to connect or disconnect circuits. Although buttons come in a variety of sizes and shapes, the one used in this experiment will be a 12mm button.
The button we used is a normally open type one. The two contacts of a button are in the off state under the normal conditions; only when the button is pressed they are close
Each time you press the button, the Arduino will regard you have pressed the button many times due to the jitter of the button You should deal with the jitter of buttons before using. You can eliminate the jitter through software programming. Besides, you can use a capacitor to solve the issue. Take the software method for example. First, detect whether the level of button interface is low level or high level. If it is low level, 5~10ms delay is needed. Then detect whether the level of button interface is low or high. If the signal is low, you can infer that the button is pressed once. You can also use a 0.1uF capacitor to avoid the jitter of buttons.
//File name: Experiment 3
//Description: controlling an LED by a button.
//Author: Okudzeto osei prince
int ledpin=12; //definition digital 11 pins as pin to control the LED
int buttonpin=2; //Set the digital 2 to button interface
volatile int state = LOW; // Defined output status LED Interface
pinMode(ledpin,OUTPUT);//Set digital 11 port mode, the OUTPUT for the output
pinMode(buttonpin,INPUT); //Set digital 2 port mode, the INPUT for the input
if(digitalRead(buttonpin)==LOW) //Detection button interface to low
delay(10); //Delay 10ms for the elimination of key leading-edge jitter
if(digitalRead(buttonpin)==LOW) //Confirm button is pressed
while(digitalRead(buttonpin)==LOW);//Wait for key interfaces to high
delay(10); //delay 10ms for the elimination of key trailing-edge jitter
while(digitalRead(btnpin)==LOW);//Confirm button release
state = !state; //Negate operation, each time you run the program here, state the HGIH becomes LOW, or the state becomes the LOW HGIH.
digitalWrite(ledpin,state); //Output control status LED, ON or OFF
Compile the program and upload to Arduino Uno board Now, you can detect the status of an external button,and then toggle the state of LED on/off relying on the state of the button detected before.