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. 

1 comment:

  1. This is a great tutorial thank you. I would have liked the next step to be to remove the delay and use millis to time the delay instead. Subscribed!

    ReplyDelete