How To Use A Push Button With Arduino


arduino pushbutton


In last tutorial I shared a quick introduction to Arduino Uno. We also learnt how to program the microcontroller to blink a LED. In this article I will show you how to use a Pushbutton to control the LED. It will be very useful for future projects. So without wasting any more time, lets begin.


Requirement:


Once you have everything we need, we can connect it all and make a circuit. But before that, lets first see how a push button works.

How A Push Button Works:

To understand the working refer to the diagram. Usually push buttons have 4 pins marked as 1,2,3 & 4. The pins in vertical line are connected together. The circuit is completed when button is pressed and pins 1,3 and 2,4 are shorted. 
Pushbutton


Circuit:

The circuit is simple. Just connect the LED to pin no. 10. Make sure to use a 220ohm resistor or you might damage the LED. The button is not so hard either. Just connect one terminal of the button to pin no. 2 and ground via 220ohm resistor. Connect the other terminal to 3.3v. Refer the diagram below for better understanding.

pushbutton switch


The circuit when assembled on a breadboard should look like following: 


Coding:

Now that we have made a circuit, we can write a code to use it. The first code is very simple.

#define LED 10 //Declared pin 10 as LED
#define btn 2  //Declared pin 2 as btn
int btn_state = 0;  //Declared a variable btn_state and set it as 0

void setup()
{
   pinMode(LED, OUTPUT);  //Sets pin 10 (LED) as OUTPUT
   pinMode(btn, INPUT);  //Sets pin 2 (btn) as INPUT
 }

 void loop()
 {
    btn_state = digitalRead(btn); //Reads the input of pin 2 and save it in btn_state
    if(btn_state == HIGH)  //If the button is pressed
    {
        digitalWrite(LED, HIGH); //Turn on the LED
     }
     else
     {
        digitalWrite(LED, LOW); //Else turn off LED
      }
   }

This first code is simple, when the button is pressed LED turns on and remains on until  the button is pressed. You can see how it works in the GIF bellow.


This works very well but sometimes we need a different arrangement. Lets say we want to toggle LED on and off using the same switch. For that we will have to make some changes to the code. 

To use the pushbutton as a toggle switch we need to remember the switch state. For saving the state we will use flags. 

Flags are variables that save the state of a pin (High/low or integers).
Lets take a look at the code:


#define LED 10 //Declared pin 10 as LED
#define btn 2 //Declared pin 2 as btn

int btn_state = 0; //Declared variable to store state (Low by default)

int flag = 0; //Declared variable flag to store switch state


void setup() 

{
  pinMode(LED, OUTPUT); //Set LED as output
  pinMode(btn, INPUT); //Set btn as input
  digitalWrite(LED, LOW); //Sets LED LOW by default
}

void loop() 

{
  btn_state = digitalRead(btn); //Store btn state (HIGH/LOW)in variable

  if(btn_state == HIGH)//If btn is pressed

  {
    if(flag == 0) //Check if flag is 0
    {
      digitalWrite(LED, HIGH); //Turn LED on
      flag = 1; //Set flag to 1
    }
    else if(flag == 1) //If flag is 1
    {
      digitalWrite(LED, LOW); //Turn LED off
      flag = 0; //Set flag to 0
    }
  }
}

After uploading the above code, you will notice that the LED is off by default. Now press the button once and the LED should turn on. It will remain on until the button is pressed again. 



Now you will notice some error. The circuit is not working as it is supposed to. The button press is registered multiple times or isn't registered at all. This is because of button bouncing.

What Is Switch Bouncing?

Switch bouncing is a real world problem that we mostly ignore in theory. It is a common problem which at times can be very annoying. In switches a metal plate is pressed down to short contacts of the terminals. In theory when a button is pressed the contact should be made and switch should be closed. But what happens is when we press the button, before fully closing the metal plate bounces between the terminals in microseconds. This is not noticeable to humans but this rapid vibration generates a quick pulse of on/off in the microcontroller giving error in the results.

To over come this problem we need to add a debouncing method in out code. In next code we will add a simple debouncing feature which will eliminate the errors and give us a cleaner result.

Refer to the code below:
#define LED 10
#define btn 2 

int btn_state = 0; 
int flag = 0; 

long lastDebounceTime = 0; // the last time the output pin was toggled 
long debounceDelay = 200; // the debounce time 

void setup() 

   pinMode(LED, OUTPUT); 
   pinMode(btn, INPUT); 
   digitalWrite(LED, LOW); 


void loop() 

   btn_state = digitalRead(btn); 
   
   //Filters out the noise by setting a time buffer
   if ( (millis() - lastDebounceTime) > debounceDelay) 
   { 
     if(btn_state == HIGH) 
     { 
       if(flag == 0) 
       { 
          digitalWrite(LED, HIGH); 
          flag = 1; 
          lastDebounceTime = millis(); //Sets current time
        } 
       else if(flag == 1) 
       { 
         digitalWrite(LED, LOW); 
         flag = 0; 
         lastDebounceTime = millis(); //Sets current time
        } 
      } 
    } 
}

In above code we have used a simple debounce method, to explain in simple terms what we do is use a delay (200ms) after the first contact of the plate. So when a button is pressed and first contact is made the code sets a 200ms timer until which all other contacts are ignored thus filtering out all noise.



After uploading the code you will notice a better result. The LED turns on and off with every button press. This debounce code can be used in any project where you have used push buttons or switches to eliminate errors.

That's all for this tutorial, hope you like it and understand the concepts. Now you can experiment with multiple LEDs and Buttons to get better at coding. 

If you like my tutorials and want more, feel free to leave a comment and follow for more updates. 

Introduction To Arduino Uno


Hello and welcome to my blog. Here I will be sharing my projects, tutorials and reviews so if you are interested make sure you subscribe to get updates. If you are familiar with the name "WolfxPac" then you have probably seen my posts on sites like Hackster.io and Instructables.com. I have been sharing tutorials on these sites for a while now and I decided to start my own blog. 

For first blog I wanted to post something simple, specially for beginners and what better than an introduction to arduino? So without any further ado, lets get right into it.


What Is Arduino?

Arduino is a microcontroller development board by Arduino.cc. It is based on Atmel's microcontroller series. There are different boards for different applications, most popular ones being Arduino Uno, Arduino Mega and Arduino Nano. If you want to learn more about these boards check out this Wiki page. This article is specifically based on one of the most versatile board by Arduino that is UNO.

Arduino Uno:

Arduino uno is a development board based on Atmega328 and comes with Arduino Boot-loader pre burnt. This board has 14GPIO out of which 6 are PWM enabled and  6 Analog pins. It has USB interface to burn the program onto the chip and can be powered through a DC power jack (9v-12v), Vin pin (6v-9v) or the USB itself.

The board can be used to control external devices through the GPIO pins. But it must be programmed first. An IDE (Integrated Development Environment) by Arduino is used for this purpose. The programming language used by arduino is based on C++, so if you have any experience with C or C++ then using Arduino will be a piece of cake.

Specifications:

  • Microcontroller: ATmega328
  • Operating Voltage: 5V
  • Input Voltage (recommended): 7v -12V
  • Input Voltage (limits): 6-20V
  • Digital I/O Pins: 14 (of which 6 provide PWM output)
  • Analog Input Pins: 6
  • DC Current per I/O Pin: 40 mA
  • DC Current for 3.3V Pin: 50 mA
  • Flash Memory: 32 KB of which 0.5 KB used by bootloader
  • SRAM: 2 KB (ATmega328)
  • EEPROM: 1 KB (ATmega328)
  • Clock Speed: 16 MHz

Pinout's:


Now that you are familiar with the board and know its pin outs, lets make a quick project to get you started.

Requirements:


After you have gathered everything and installed Arduino IDE we can move on to next step.

Circuit:

Make the connections according to the diagram below:

The positive terminal of LED is connected to pin 13 of arduino and negative terminal is connected to ground through a 220ohm resistor.


After the connections are made, we can upload the code to the arduino which will make the LED blink.

Coding:

  • First download and install the Arduino IDE and open it.
  • Connect the Arduino uno to your PC using USB cable.
  • Goto Tools >> Port and select the COM port to which the arduino is connected.

  • Now write the code given below:
#define LED 13 //define pin 13 as LED

void setup()
{
    pinMode(LED, OUTPUT); //sets pin 13 as output
    digitalWrite(LED, LOW); //turns LED off
}

void loop()
{
    digitalWrite(LED, HIGH); //turns LED on
    delay(2*1000); //waits for 2 sec
    digitalWrite(LED, LOW); //turns LED off
    delay(2*1000); //waits for 2 sec
}

Save the code and upload it to arduino using the arrow on top left corner.

Now you will see the LED blink, it will stay on for 2 seconds and then turn off for 2 seconds. Here is an example:



Final Note:

Now some trouble shooting, If you are getting any errors while uploading then you probably have a clone board. No need to panic, Arduino is an opensource platform so different manufacturers can copy and modify the design. So now all you have to do is install the proper drivers.

All the information about the drivers can usually provided by the seller but most common driver you might need is ch340g. Just download and install it , restart the IDE and you are ready to upload.

This article was aimed at beginners who are just getting started. In future posts we will learn about different devices and sensors that can be used with arduino to build awesome projects.