We have learned in before tutorials how to blink an LED with Arduino automatically.  That program will run equally long as there is power for the Arduino. Let'due south become a flake further and try to control the LED with a button. We utilise a pushbutton to control the Blinking. In other words, we volition make a uncomplicated programme that allows you to control the LED by pushing a button.

Unfortunately, many of the guides never go beyond the very basic first sketch. In this guide, I hope to help new users take the adjacent step. The process for switching whatsoever digital device on and off is quite the same.

We are going to use polling techniques for reading the switches/pushbuttons. This means that in the instance sketches below, we constantly check the pivot state with digitalRead(). But when we look at the pivot, practise we know if the state has changed. It is like checking if the window is open up every infinitesimal.

The switch pivot is connected to a 10K resistor, GND, and push button switch in the example codes below. This means that the pin is existence pulled LOW. The other side of the switch is connected to VCC (in the example of an Arduino Uno 5V), and so when the switch is closed, the VCC overpowers the 10K resistor and connects the switch pivot to 5V, making information technology HIGH.

It is unremarkably is not wise to connect an Arduino Pin directly to 5V. Nosotros can do this here since the Arduino digital pins are fix for INPUT with the function pinMode(). This ways a resistor in front of the pivot allows u.s. to connect the pin directly to the 5V.

In that location are a couple of examples that we will examine.

The first example is a elementary button printing. In this example, the LED volition come up on when the button is pressed. When the button is released, the LED goes off.

The 2d example is a toggle switch. Here you will learn about button states. This means that you can press the push to plough the LED on and press the push button a second fourth dimension to turn the LED off.

The third case shows how you can reliable detect if the pushbutton/switch is pressed/closed with the debounce method.

Case i, Simple button press

the starting time example is very simple. When the pushbutton is open up (unpressed), there is no connection between the two legs of the pushbutton, so the pin is connected to the footing (through the pull-down resistor), and we read a LOW. When the push button is closed (pressed), it makes a connection betwixt its two legs, connecting the pivot to 5 volts so that nosotros read a High.

Materials you will need

Component Number
Arduino Uno Rev3 1x
Jumper Wires 7x
Breadboard 400 points 1x
220Ω resistor 1x
10KΩ resistor 1x
Tactile push button 1x

Arduinoplatform is a participant in several affiliate programs. This means that I will earn a commission if y'all buy a product from the affiliated websites by clicking on the links provided in a higher place.

BreadBoard Layout

Led Button Debounce

Case ane, Code

          /*  * Elementary on/off button sketch  * If the push is pressed the led volition turn on  * if the push is unpressed the led will turn off */  // the number of the pushbutton pin const int buttonPin = ii; // the number of the LED pin      const int ledPin =  10;        void setup() {   // initialize the LED pin as an output:   pinMode(ledPin, OUTPUT);   // initialize the pushbutton pin as an input:   pinMode(buttonPin, INPUT); }  void loop() {   // check if the pushbutton is pressed.    if (digitalRead(buttonPin) == High) {     // turn LED on:     digitalWrite(ledPin, HIGH);   } else {     // plow LED off:     digitalWrite(ledPin, LOW);   } }        

Example one, Code Explanation

When declaring the Arduino Pins that we want to utilise, it is wise to proper name them. You can also simply utilize the relevant number. Using blank numbers works fine merely tin lead to readability issues in the code, especially in large sketches or code that takes a while to develop. Y'all may remember it is clear that pin ten is the LED, but at some betoken, y'all are likely to forget. To make the code amend readable (or easier to follow), information technology is better to use variables with meaningful names instead of the actual PIN numbers. In the following instance, buttonPin and ledPin are declared. From the variable names, it is obvious where the pins are used for.

          // the number of the pushbutton pin const int buttonPin = ii; // the number of the LED pivot      const int ledPin =  10;                  

Void setup(): We need to set the push button variable to an input mode and set the LED to an output mode. This tells the Arduino Lath to use pivot 2 every bit an input and pin x every bit an output.

          void setup() {   // initialize the LED pin equally an output:   pinMode(ledPin, OUTPUT);   // initialize the pushbutton pin as an input:   pinMode(buttonPin, INPUT); }        

Copy

In the void loop () part, we will command the LED by using an If statement and the command digtalRead(). The if argument in the sketch volition check whether Pin 2, the buttonPin, is sending a Loftier value. We use a comparison operator "==" to cheque if the Pin is set up HIGH since the excursion is closed when the switch is pressed.

          if (digitalRead(buttonPin) == Loftier) {     // turn LED on:     digitalWrite(ledPin, Loftier);   }        

If that condition is non met, the loop goes to the Else Statement, where the LED is turned off.

          else {     // plough LED off:     digitalWrite(ledPin, Low);   }        

You should be able to encounter that the sketch is constantly checking the switch and turning the LED on or off accordingly. This ways non only is the switch pin being constantly checked but the LED is constantly beingness turned on and off. For this brusk simple sketch, this is fine and works well but may run across issues when used in larger more than circuitous sketches.

If you want to let the LED stay on we need to determine the state of the button. To exercise this, nosotros will use the button equally a switch and determine the last land it was in.

Although we cannot get away from continuously checking the push button switch pivot (this is what polling is) we can stop setting the LED pin every time and only set information technology if the state of the button switch has changed.

Example 2, Toggle Switch

In the previous tutorial, we already learned how to turn a LED on with a button. The problem arises that if the button is unpressed, the LED turns off. If you would like to keep the LED on afterward the button is pressed, we need to remember the state of the button. Nosotros can use the boolean role for this. We volition use and modify the code we already fabricated in the outset example.

What if we do not want to concord the push button switched closed to proceed the LED on. What if we want to press one time to plow on the LED and printing over again to plow it off. To do this, we need to know when the button switch is pressed but was not pressed before (we have already washed this in the previous example), and nosotros also demand to know the status of the LED; is information technology on or is information technology off? Nosotros can continue track of the LED status by adding a new variable LEDstatus. LEDstatus will be LOW for off and Loftier for on.

For remembering the button land, we can declare a variable called SwitchState, where nosotros remember the old and the new country of the button/switch.

Instance 2, Lawmaking

          /*  * "Toggle Switch State"  * This sketch uses a switch to turn a LED on or off.  * The LED keeps on untill the switch is pressed again. */  // declaring pins for LED and the switch int pinLed = ten; int pinSwitch = 2;  // declaring boolean variables to hold //the new and one-time switch states boolean oldSwitchState = LOW; boolean newSwitchState = Low; boolean LEDstatus = LOW;  void setup() {   pinMode(pinLed, OUTPUT);   digitalWrite(pinLed, Depression);   pinMode(pinSwitch, INPUT); } void loop() {   // read the status from the switchpin   newSwitchState = digitalRead(pinSwitch);   //if the switch is pressed or unpressed    //compare with the previous land   if ( newSwitchState != oldSwitchState )   {     // has the button switch been airtight?     if ( newSwitchState == Loftier )     {       //cheque if what the condition is of the LED.       if ( LEDstatus == Depression ) {         digitalWrite(pinLed, High);         LEDstatus = HIGH;       }       // if the LED is on and the switch is pressed once again       else                    {         digitalWrite(pinLed, LOW);         LEDstatus = LOW;       }     }     // save the state of the switch so It can be compared     oldSwitchState = newSwitchState;   } }                  

Example 2, Code Caption

The first part of the sketch is the same as the starting time case. Here nosotros declare the variables that hold the LED pin and the pin for the switch input.

          // declaring pins for LED and the switch int pinLed = x; int pinSwitch = 2;        

As you can meet, three variables hold the electric current and new state of the button. Boolean variables hold/think the state of the object, in our example, the button. If the program is run for the outset time, both states should be LOW. We tin can now transform the button into a switch.

          // declaring boolean variables to hold //the new and old switch states boolean oldSwitchState = LOW; boolean newSwitchState = LOW; boolean LEDstatus = LOW;        

In comparison to example 1 we are turning the LED off at the get-go of the sketch.

          void setup() {   pinMode(pinLed, OUTPUT);   digitalWrite(pinLed, Low);   pinMode(pinSwitch, INPUT); }        

In the void loop() part of the sketch, the first thing to do is read the pin connected to the switch/button. If it'southward pressed, the value will be High. When the switch is non pressed, the value will be LOW.

          // read the condition from the switchpin   newSwitchState = digitalRead(pinSwitch);        

The next footstep is to check whether the push button has been pressed or released before. In other words, did the country of the switch inverse? The comparing operator != is used to meet if the new land of the switch is not the same as the old state of the button/switch.

          if ( newSwitchState != oldSwitchState )   {        

Next, we check whether the switch is pressed and execute the code that belongs to it.

          // has the button switch been airtight?     if ( newSwitchState == High )     {        

If the switch is pressed, we bank check whether the LED is on or off. If the LED is off (LEDstatus memorize the condition), the pin is set HIGH, which turns on the LED. Furthermore, the Boolean variable LEDstatus is fix HIGH to let the program know that the LED is on.

          //check if what the status is of the LED.       if ( LEDstatus == Low ) {         digitalWrite(pinLed, HIGH);         LEDstatus = High;       }        

If the condition is not true that the LEDstatus is LOW while you have pressed the switch/button, the LED volition exist turned off. Remember that the testing conditions if the LED is on are inside the if role that is just executed when the status of the pinSwitch is HIGH.

          // if the LED is on and the switch is pressed over again       else                    {         digitalWrite(pinLed, Low);         LEDstatus = Low;       }     }        

At the end of the sketch, we save the status of the switch into the oldSwitchState . This is important since we arrived at the stop of the sketch and we demand to know the old state of the switch for the next fourth dimension in the loop().

          // save the state of the switch so It tin be compared     oldSwitchState = newSwitchState;   }        

With many kinds of switches, you practice not get clean airtight contact. Y'all become a very curt transition menstruation where the switch very speedily closes, opens, closes, opens, and closes before settling downwards and condign closed. The contacts bounce a bit before becoming fully closed.

This will exist the third example that we will examine—namely, a toggle switch with debouncing.

Case 3, Debounce Switch

We tin can finetune the in a higher place lawmaking with the debounce method. The debounce method checks to meet if it gets the same reading from the switch later a slight delay that needs to be long enough for the switch contacts to stop bouncing. You may require longer intervals for "bouncier" switches (some switches can crave as much as l ms or more). The function works by repeatedly checking the country of the switch for as many milliseconds as divers in the debounce time. If the button remains stable for this fourth dimension, the state of the switch volition be returned (true if pressed and simulated if not). If the switch state changes inside the debounce period, the counter is reset so that the checks start over until the switch country does not change within the debounce time. This debounce() role will piece of work for any number of switches, but you must ensure that the pins used are in input way.

A potential disadvantage of this method is that the sketch is blocked for the time that you lot set the debounce. This means that the sketch is waiting for the debounce function the be completed until it can do something else in the sketch.

Instance 3, Code

          /*    Debounce sketch which puts on a LED    a switch connected to pin two lights the LED on pivot 13    debounce logic prevents misreading of the switch country */ // the number of the input pin const int inputPin = two; //the number of the output pin const int ledPin = x; // milliseconds to wait until stable const int debounceDelay = 10;  // debounce returns truthful if the switch in //the given pin is airtight and stable boolean debounce(int pin)  {   boolean state;   boolean previousState;    // store switch country   previousState = digitalRead(pivot);   for (int counter = 0; counter < debounceDelay; counter++)   {     // wait for 1 millisecond     delay(1);     // read the electric current pin value     state = digitalRead(pivot);     // if the current value of the pin is differ     if ( state != previousState)     {       // reset the counter if the state changes       counter = 0;       // and save the current country       previousState = land;     }   }   // here when the switch state has been stable   return land; } void setup() {   pinMode(inputPin, INPUT);   pinMode(ledPin, OUTPUT); } void loop() {   // if debounce role is true   if (debounce(inputPin))   {     // send HIGH point to ledPin     digitalWrite(ledPin, High);   } }                  

Example iii, Code Explanation

To detect the state of the switch, we first demand to declare the variables that hold the pins. And a abiding integer for the delay that we volition use in our debounce function.

          // the number of the input pin const int inputPin = ii; //the number of the output pivot const int ledPin = x; // milliseconds to wait until stable const int debounceDelay = 10;        

The debounce function returns True if the switch is closed and stable. The Boolean office starts by defining some variables that will concord usa of the button/switch.

                      // debounce returns true if the switch in //the given pin is closed and stable boolean debounce(int pin)  {   boolean state;   boolean previousState;    // store switch country   previousState = digitalRead(pivot);        

In the for loop, we outset the counter with nix and increases it by 1 until information technology reached the number eleven. The for loop will so return the value of the state. The loop will echo itself 10 times, the value of debounceDelay. It volition start with a delay of 1 ms and then read the pin that is connected to the button/switch.

The if argument that follows checks whether the state of the button/switch is the same as the previousState when it entered the if statement. This is vital to know whether the button is pressed or not.

          for (int counter = 0; counter < debounceDelay; counter++)   {     // wait for 1 millisecond     filibuster(one);     // read the current pin value     land = digitalRead(pin);     // if the current value of the pivot is differ     if ( state != previousState)     {       // reset the counter if the state changes       counter = 0;       // and relieve the current land       previousState = state;     }   }   // here when the switch state has been stable   return country;        

Void loop (): another if statement is used to check if the function "debounce" returns a true value for the inputPin. If this is true, a HIGH signal is sent to the ledPin. When the button is pressed, the LED will now be turned on.

          void loop() {   // if debounce role is truthful   if (debounce(inputPin))   {     // ship High signal to ledPin     digitalWrite(ledPin, High);   } }        

Now we know how to reliably observe the switch, to command multiple LEDs with 1 switch.