Hello Friends !
We are bringing to you the Tutorial 3 for How to Interface Switches with Arduino?
Push buttons or switches connect two points in a circuit when you press them. This example turns on one LED when the button pressed once, and off when pressed twice.
In this tutorial you will also learn how to use ‘flag’ variable to control an event.
So, let’s get started!
Requirements:
- Arduino Uno
- Breadboard
- LED
- 220 Ohm & 10K Ohm resistor
- Push Button
Step1:
Open Arduino IDE. Then create a New Project
Step2:
Code:
const int buttonPin = 4;
const int ledPin = 3;
int buttonState = 0;
int flag=0;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop(){
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
if ( flag == 0){
digitalWrite(ledPin, HIGH);
flag=1;
}
else if ( flag == 1){
digitalWrite(ledPin, LOW);
flag=0;
}
}
delay(200);
}
Step3:
If you are using Arduino UNO board, then the 13th pin of the board has an inbuilt LED. Now if you upload the program to the board, the LED will be turning ON/OFF with 1 second delay.
You can use a 220 Ohm Resistor with LED.
Connections : 

Thank you!
In case of any questions or queries, feel free to post below.
Subscribe to our YouTube Channel and check out other tutorials of DIY projects.