Arduino — Button — LED
We are going to learn how to:
We will learn how to toggle LED each time button is pressed in Arduino — Button Toggles LED tutorial.
|1||×||Arduino UNO or Genuino UNO|
|1||×||USB 2.0 cable type A/B|
|1||×||220 ohm resistor|
About LED and Button
If you do not know about LED and button (pinout, how it works, how to program . ), learn about them in the following tutorials:
Image is developed using Fritzing. Click to enlarge image
Read the line-by-line explanation in comment lines of source code!
We are considering to make the video tutorials. If you think the video tutorials are essential, please subscribe to our YouTube channel to give us motivation for making the videos.
Button and LED on Commercial Products
Most electronic products have a reset button. Additionally, the button also keeps other functionalities in many products.
How to use Push button | Toggle Switch on-off | with Arduino
I am going to tell you how to use Arduino as a switch. In this, we will learn the simple Button Digital Input using Arduino. It is very easy. Then, apply it with coding to change into a toggle switch on-off.
Are you ready? Let’s get to learn.
Here is a step by step process.
The Arduino has Digital I/O PINs. Which “I/O” is Input and Output. We use the output of Arduino to display the LEDs.
So, we need to use the switches as digital input pins to get various electrical signals to control the operation of the circuit as well.
What is Digital?
Digital is a kind of electrical signal. Which has work of only two states are:
– HIGH or ON or “1”
– LOW or OFF or “0”
We bring this digital Go to the many benefits and high accuracy.
Switch on Arduino (Pull-up, Pull-Down)
What is digital Input?
Digital Pins of Arduino can read 2 status are “HIGH” and “LOW” depend on that Pin has current or not.
The Button switch to Input Pin of Arduino. We need to connect the resistor to exact status of the inputs. We use 2 form circuit
• Pull-Up: the Input will be connected with a resistor that call “Pull-UP Resistor” to a Vin we will have the status “HIGH” all the time, until you press button to LOW or ground, the Arduino will read “LOW” or we call “Active Low”
• Pull-Down: the Input will be connected with a resistor that call “Pull-Down Resistor” to a Ground we will have the status “LOW” all the time, until you press button to Vin or HIGH, the Arduino will read “HIGH” or we call “Active High”
We will see that 2 circuits have the operation reversed. Depending on what is selected.
Figure 1 Pull-up and Pull-Down Circuits
This resistor Pull-Up / Down Resistor used the 5K – 20K. We use 10K
Start to build the Button to control LED
We will use the Input Pin of Arduino to receive the button status, then control LED display on Output Pin 13. By using the Pull-Down to apply LED grow up when we press the button only.
Parts will you needs
- Normally open pushbutton
- one LED
- 10K resistor
- 470 ohms resistor
- jumper wires
Step 2 connect the parts as circuit Figure 2 The circuit connection
This circuit use Pull-Down by connect the Button to 5V power supply and 10K resistors to ground. And We use Digital PIN 3 as Input. Next, the Output is Digital PIN 13 connected to LED by 470 ? resistor to limit current.
Figure 3 Simple Button Digital Input using Arduino
Let’s test it
We type the code on IDE below
Figure 4 the Simple Button Digital Input code with delay
We test it as Video, first type code on IDE without “delay” command. And upload When we press the button LED will glow as we press. Then, we put the code delay. The LED will delay time turn ON about 10S.
Now we use the button or switch as a digital input. It is easy
Today we will as push button switch as toggle switch. When we press the button “on” it will store status “on” hold, although, we will release. Then, we press it again it will “off” and store status “off” as well.
How it works and building
We want to control LED ON-OFF by button (as toggle switch). So we use schematic as Figure 1
Figure 1 Schematic diagram of The Button becoming Toggle Switch using Arduino
Parts will you needs
- Arduino UNO R3
- Normally open pushbutton
- one LED
- 10K resistor
- 470 ohns resistor
- jumper wires
Then, we connect parts on breadboard and the arduino as Figure 2
Figure 2 circuits connection on breadboard
We code programming on Sketch – Arduino IDE as code below.
Next, when we finished the code we have to verify/compile it will be done for no error.
And then, we have to upload into the Arduino (UNO) it will work.
(Learn more Simplest programing C on Arduino UNO)
How code works
We’ve learned about the button switch is applied in the code above.
When a button is pressed state is opposed to a state change from High to Low or from Low to High, change by the command.
And store value “buttonState” finally, to “lastState” too. To check whether the value of the press in this round. Logic signals “LOW” from the previous state. (no pressing) The status is “HIGH” is certainly to read once only.
The problem switch bounce
All switches has contact as metal. Often the problem of bouncing signals is the signal swing In a short time 5-50 nanoseconds in first time as Figure 3 It is caused by the contact not close, High or Low rapidly. Before into a stable state.
Figure 3 The problem switch bounce
We can solve the problem by add a “delay (10)”, it makes the system not working for this time 10mS.
Then, we apply the USB to computer to upload code. As Figure 4 We are testing the Button become Toggle Switch using Arduino.
Next step, as video we try to press LED is ON Even if we leave it to the LED is still ON. But when press again LED is OFF and still status util we press button again.
GET UPDATE VIA EMAIL
I always try to make Electronics Learning Easy .
Arduino toggle push power on off latch switch
by admin · Published March 17, 2017 · Updated December 2, 2020
A push power ON-OFF switch is a push-to-make, push-to-break switch which alternates its output between the two output states for repeated push action. That is each time the button is pressed the output turns ON if it is presently OFF and OFF if it is ON.
In the here circuit the Arduino changes its output for each positive edge triggering at the input pin; the transition of the state from LOW to HIGH is called a Positive edge. A positive transition occurs only at the instant when the switch in a released state is been pressed. So holding the switch makes no difference in the output, to change the output the switch has to release and press again.
For every trigger pulse or positive edge the arduino will toggle the state and hold it till the next pulse is received.
Below given is a sample code to ON and OFF LED with a push-button. The digital pin 2 is taken as the input pin connected with a pull-down resistor to avoid any false triggerings.
The circuit can be modified to operate with high power loads with the same arrangement by just replacing the LED with a relay circuit. Then 230V/110V AC loads or similar loads with external supply can be controlled by the circuit. Refer : Relay interface with the Arduino.
Arduino toggle switch code
To run additional codes or to operate devices or modules with the latching switch use the below code. Place the required code in the code block space shown in the code. The ”Else” state is true by default, thus the code placed inside it runs first. The ”if” condition becomes true only on the first pulse. Then the execution of code blocks toggles for the next successive actions.
when I tried it, it did not work for me
Could you explain more about the issue?
Works great for me!
I have a homemade midi footswitch with five guitar-pedal type buttons, each with an LED. I ran this against just one button & led and sent the value of digitalRead(Switch) and LEDstate out to serial monitor so I could see how they changed when I pressed the button.
const int Switch = 2, LED = 10;
int state = 0, LEDstate=0;
if (state == 0 && digitalRead(Switch) == HIGH) <
state = 1;
if (state == 1 && digitalRead(Switch) == LOW) <
state = 0;
Serial.print(“LEDstate = “);
Serial.print(” digReadSwitch = “);
* This works!
At beginning, without touching button, Ledstate = 1 (on), digReadSwitch = 1
One quick press and Ledstate = 0 (off) and digReadSwitch = 1 (because I’m not pressing it)
Another quick press and Ledstate = 1 (on) again, digReadSwitch = 1
Press and HOLD gives 0,0 : Ledstate = 0 (off) and digReadSwitch = 0
Arduino Toggle Pin
This tutorial will discuss toggling a digital pin using the digitalWrite() function in Arduino.
Arduino Toggle Pin
Arduino digital pin has three states: high, low, and floating. In the high state, the voltage of the pin will be 5 and low state; the voltage will be 0.
At the floating state, the voltage of the pin will be between 0 to 5. By default, all the pins are at a floating state, and if we read a pin value, it will give us a floating value.
We can use the digitalRead() function to read a digital pin and pass the pin number inside the function. We can use the digitalWrtie() function to write a digital pin and pass the pin number inside the function.
Before we start reading or writing a pin, we must set its mode to input or output. We can use the pinMode() function to set the mode of a pin.
The first argument of the pinMode() function is the pin number, and the second argument is the mode like output or input. For example, let’s toggle a digital pin 9 and attach a LED with it, which will toggle.
See the code below.
In the above code, we are toggling pin 9 of Arduino UNO with a one-second delay. The pin will stay HIGH for one second, and then it will change its state to LOW and maintain that state for one second.
We have used the ! symbol in the above code, which toggles the pin state HIGH to LOW and LOW to HIGH . We read the pin 9 status; toggle it using the ! symbol, and then write it to pin 9 .
If we attach a LED with a resistor to pin 9 , it will start blinking with a one-second delay. If we don’t add a delay, the LED’s blinking will be so fast that we will not see it physically with our eyes.
The toggle or blinking speed depends on the frequencies of the Arduino board. Different Arduino boards have different operating frequencies, like 8 MHz and 6 MHz.
Arduino – Turn LED ON and OFF With Button
In this Arduino tutorial I will show you how to turn an LED on and off with a push button. In fact, we’ll do 2 slightly different applications.
First, we will power on the LED when the button is pressed, and power off the LED when the button is not pressed.
And then we’ll modify the program to toggle the LED’s state only when we release the button.
For more info on each component, also check out this Arduino LED tutorial and this Arduino push button tutorial.
Let’s get started!
>> Watch this video as an additional resource:
You are learning how to use Arduino to build your own projects?
Check out Arduino For Beginners and learn step by step.
After watching the video, subscribe to the Robotics Back-End Youtube channel so you don’t miss the next tutorials!
Table of Contents
Arduino circuit with an LED and a button
To build the circuit you will need those components:
- Arduino board (any board, if you don’t have Uno you can easily adapt by finding corresponding pins).
- LED – any color.
- Push button.
- 220 Ohm resistor for the LED. If you don’t have this specific value, any resistor from 330 to 1k Ohm will do.
- 10k Ohm resistor for the push button. If you don’t have, you can go until 20k-50k Ohm.
- A bunch of male to male wires (including if possible black, red, and other colors).
Here’s the circuit you have to make.
Step by step instructions to build the circuit (more info about Arduino pins here):
- First, make sure to power off your Arduino – remove any USB cable.
- Plug a black wire between the blue line of the breadboard and a ground (GND) pin on the Arduino board.
- Plug the LED. You can notice that the LED has a leg shorter than the other. Plug this shorter leg to the ground (blue line here) of the circuit.
- Connect the longer leg of the LED to a digital pin (here pin no 8, you can change it). Add a 220 Ohm resistor in between to limit the current going through the LED.
- Add the push button to the breadboard, like in the picture.
- Connect one leg of the button to the ground, and put a 10k Ohm resistor in between. This resistor will act as a “pull down” resistor, which means that the default button’s state will be LOW.
- Add a red wire between another leg of the button and VCC (5V).
- Finally, connect a leg of the button (same side as the pull down resistor) to a digital pin (here 7).
All right your circuit is now finished. You can start writing code.
Turn on the LED when button is pressed, turn it off otherwise
What we want to achieve is simple: when the button is not pressed, the LED is off. And when we press the button the LED should be on.
Let’s break this code down line by line.
First, as a best practice, we use some defines to keep the pin number for the LED and push button. That way, if you have used different pins than I, you just need to modify those 2 lines. Also, in the future if you want to change the LED from pin 8 to pin 11 for example, you can modify this line without touching anything else in the code.
The setup function is executed once at the beginning of the program. This is the perfect time to initialize our pins with the pinMode() function:
- OUTPUT for the LED, as we’re going to write data to it.
- INPUT for the push button, as we’re going to read data from it.
Now, the digital pins are correctly set up.
Loop – Turn on the LED when button is pressed
In the loop function, we start by reading the button’s state with the digitalRead() function. As we have a pull down resistor on the button, we know that the non-pressed state will give us the value LOW.
(Note: if you were using a pull up resistor, or no resistor at all – with the INPUT_PULLUP option for pinMode – this would be the opposite. HIGH when the button is not pressed, and LOW when it’s pressed.)
So, once we get the button’s state, we check if it’s HIGH or LOW:
- HIGH (pressed): we power on the LED with digitalWrite() and the HIGH state.
- LOW (not pressed): we power off the LED with digitalWrite() and the LOW state.
OK, now let’s do something a little bit more complex.
Toggle LED’s state with the push button – first iteration
What we want to do is to toggle the LED’s state when you press + release the button. So, the first time you release the button, the LED will turn on. The second time, it will turn off. Etc.
Let’s analyze the code.
Those defines are the same as before.
We need to create 2 global variables, to keep the state of the button and the LED. In the loop we’ll use those variables to compare the previous state to the new state.
The void setup stays the same. We just set the mode for both pins.
And now the serious stuff is coming. We enter the void loop function.
Monitor the button’s state
The first thing we do is to read the button’s state and to store it inside a new local variable.
Then we can compare the current state to the last one (from the previous execution of the loop function). 4 possibilities here:
- LOW -> LOW (last -> current).
- LOW -> HIGH.
- HIGH -> LOW.
- HIGH -> HIGH.
With the condition, we only enter the next block of code if the current and last state are different. If the 2 states are the same, then we don’t enter the if and the loop function is finished for this turn.
Also, now that we have the information we want, we directly store the current state into the last state variable, so that we have the correct value for the next time we enter the loop.
At this point we have only 2 possibilities left:
- Either the previous state was LOW and the current state is HIGH (not pressed to pressed).
- Or the previous state was HIGH and the current state is LOW (pressed to not pressed).
We are only interested in the second option, so here we just have to check if the current button’s state is LOW. If that’s the case, we can now turn the LED on or off.
Toggle the LED when the button has been released
Here we toggle the state of the LED. I’m not a big fan of one-liners but this one is really handful when you just need to toggle a state. This will save you 3-4 lines of code for something really trivial.
Here’s the template for this one-liner: (condition to evaluate) ? if true use this value : if false use this value.
So, if the LED is currently powered on (ledState == HIGH), we assign the value LOW. If the LED is powered off (ledState != HIGH), we assign the value HIGH.
And the last thing we need to do is of course to physically set the state for the LED, with the new computed state.
Turn LED on and off with button – using debounce
One thing you might notice with the previous experiment: sometimes when you press and release the button, the LED’s state doesn’t change, or blinks quickly multiple times.
This is because the button is physically bouncing when you press it. Thus, many false positives will be interpreted by the Arduino. What you can do to prevent that is to add a debounce delay in your code. For example, you can decide that when the program detects a change in the button’s state, it will wait 50 milliseconds before considering another change viable.
Let’s add a few lines to our previous code.
The improved code
Now, if you run this program, you won’t have any problem with the LED’s state being changed quite randomly when you press/release the button.
And here is how we achieve that.
We create 2 new global variables:
- One to decide how long we want to wait before validating a second change in the button’s state. Here it means that if the state changes, any changes after that in the next 50 milliseconds will be ignored. 50 millis is a good value, you can experiment with lower and upper values to check the behavior.
- Another one to keep the last time the state was changed, so we have a starting point to compare to.
Then, in the loop, we only start the button/LED functionality if enough time has passed since the last time the button’s state was changed.
To do that it’s quite simple: we compare the duration since the last update time to the required debounce duration.
Once the debounce delay has been passed, then we can do what we did before. And don’t forget to update the starting point for the “debounce timer” just after you detect a change in the button’s state. So, the next time the program enters the loop, it will wait for 50 milliseconds (or the value you’ve chosen) to detect new changes in the button’s state.
Conclusion – Arduino turn Led ON and OFF with button
In this tutorial you have seen how to build an Arduino circuit with an LED and a push button, and also how to control this circuit to turn the LED on and off with the button.
Even if it’s a rather simple application, there are many ways to program it. You can power on the LED only when the button is pressed, or make the LED blink when you release the button, and so on.
Another way to write the code (for the exact same functionalities) is to use Arduino interrupts – available for the boards having interrupt pins.
To go further from here, check out:
Did you find this tutorial useful?
Do you want to learn Arduino from scratch?
If yes, this course is for you:
Did you find this tutorial useful?
Do you want to become better at programming robots, with Arduino, Raspberry Pi, or ROS2?
If yes, subscribe to receive exclusive content and special offers!