Skip to content
Home » Arduino Code For Led On Off | Controlling The Arduino’S Led

Arduino Code For Led On Off | Controlling The Arduino’S Led

Arduino tutorial 2- LED Blink program with code explained | How to blink an LED using Arduino |

Step 6: Next, Try…

Now that you know how to blink an LED using Arduino’s digital output, you’re ready to try other Arduino exercises that utilize the

digitalWrite();

function. In the next lesson, you’ll try using a breadboard to add more LEDs and code to control.

  1. Experiment with this simulation by adding more blocks to create flashing patterns. Can you create a program that flashes out a message using Morse Code?
  2. Continue on with the next lesson about adding more LEDs and using a solderless breadboard.

How to Wire and Program a Button

Learn how to wire and program a pushbutton to control an LED.

Pushbuttons or switches connect two points in a circuit when you press them. This example turns on the built-in LED on pin 13 when you press the button.

Hardware

  • Arduino Board

  • Momentary button or Switch

  • 10K ohm resistor

  • hook-up wires

  • breadboard

Circuit

Connect three wires to the board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pull-down resistor (here 10K ohm) to ground. The other leg of the button connects to the 5 volt supply.

When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that we read a HIGH.

You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button.

If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is because the input is “floating” – that is, it will randomly return either HIGH or LOW. That’s why you need a pull-up or pull-down resistor in the circuit.

Schematic

Code

Learn more

You can find more basic tutorials in the built-in examples section.

You can also explore the language reference, a detailed collection of the Arduino programming language.

Last revision 2015/07/28 by SM

Suggested changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.

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).
  • Breadboard.
  • 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.

Arduino tutorial 2- LED Blink program with code explained | How to blink an LED using Arduino |
Arduino tutorial 2- LED Blink program with code explained | How to blink an LED using Arduino |

Controlling the Arduino’s LED

To turn on an LED, the Arduino needs to send a HIGH signal to one of it’s pins. To turn off the LED, it needs to send a LOW signal to the pin. You can make the LED flash by changing the length of the HIGH and LOW states.

The Arduino has an on-board surface mount LED that’s hard wired to digital pin 13. It’s the one with an “L” next to it:

To get this LED flashing, upload the “Blink” program to your Arduino:


void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); }

The LED should now be blinking on and off at a rate of 1000 milliseconds (1000 milliseconds = 1 second).

The

delay()

function on line 6 tells the Arduino to hold the HIGH signal at pin 13 for 1000 ms. The

delay()

function on line 8 tells it to hold the LOW signal at pin 13 for 1000 ms. You can change the blinking speed by changing the number inside the parentheses of the

delay()

functions.

Step 4: Use the Blink Circuit Starter

This is a circuit we think you’ll want to make frequently, so it’s saved as a circuit starter!

  1. Grab this circuit and code combo any time using the starter available in the components panel (dropdown menu -> Starters -> Arduino).
  2. For a more advanced version of this Arduino code, also check out the Blink Without Delay starter, which uses the current time to keep track of blink intervals instead of

    delay();
  3. If you added the circuit starter to the existing breadboard circuit workplane, delete the duplicate Arduino board and components by clicking on them and then clicking the trash icon (you can also press delete on your keyboard).
  4. Continue to the next step.
Arduino - Turn LED On and Off With Push Button
Arduino – Turn LED On and Off With Push Button

Electrical Signals

The Arduino communicates with modules and sensors by switching on and off electrical current. It’s very similar to the one’s and zero’s in binary code. When current is switched on, it’s known as a “HIGH signal”. That’s comparable to the “one” in binary code. When the current is switched off, that’s a “LOW signal”, which is similar to the zero in binary code. The length of time the current stays on or off can be changed from a microsecond up to many minutes.

Watch the video for this tutorial:

Controlling Multiple LEDs Together

You can control as many LEDs as you want as long as you have enough pins available. Let’s make the external LED flash along side the on-board LED to demonstrate. All we need to do is duplicate the code for pin 8, and change the pin numbers to pin 13.

Here’s an example of that:


void setup() { pinMode(8, OUTPUT); pinMode(13, OUTPUT); } void loop() { digitalWrite(8, HIGH); delay(1000); digitalWrite(13, HIGH); delay(1000); digitalWrite(8, LOW); delay(1000); digitalWrite(13, LOW); delay(1000); }

You should be able to see both LEDs blinking. But they won’t be blinking in sync, they’ll be alternating.

The Arduino executes the instructions in the code from top to bottom. It reads each line and performs the task before moving onto the next line. Once it has read through to the end, it loops back to line 6 and starts over again.

In the program above, the code is executed in this order:

  1. HIGH signal sent to pin 8
  2. Wait for 1000 ms
  3. HIGH signal sent to pin 13
  4. Wait for 1000 ms
  5. LOW signal sent to pin 8
  6. Wait for 1000 ms
  7. LOW signal sent to pin 13
  8. Wait for 1000 ms
  9. Return to step 1

To get both LEDs blinking at the same time, we need to remove the delay between the HIGH and LOW signals of each pin, as shown in this program:


void setup() { pinMode(8, OUTPUT); pinMode(13, OUTPUT); } void loop() { digitalWrite(8, HIGH); digitalWrite(13, HIGH); delay(1000); digitalWrite(8, LOW); digitalWrite(13, LOW); delay(1000); }

Now both LEDs should turn on and off at the same time. The tasks are executed in this order:

  1. HIGH signal sent to pin 8
  2. HIGH signal sent to pin 13
  3. Wait for 1000 ms
  4. LOW signal sent to pin 8
  5. LOW signal sent to pin 13
  6. Wait for 1000 ms
  7. Return to step 1

Now that you’ve seen how to control LEDs with the Arduino, check out part 2 of this series, where I’ll show you how to use a light dependent resistor to control how fast the LED flashes and how to control the pitch of sound output by a speaker.

If you have any questions or have trouble getting this project to work, just leave a comment below and I’ll try help you get it going. And be sure to subscribe! We send out an email each time we publish a new tutorial…

Use a Push Button with Arduino

Arduino Tutorial: LED Sequential Control- Beginner Project
Arduino Tutorial: LED Sequential Control- Beginner Project

Controlling an External LED

An external LED or any other powered module can be controlled in a similar way.

LEDs need to have a resistor placed in series (in-line) with it. Otherwise, the unrestricted current will quickly burn out the LED. The resistor can be any value between 100 Ohms and about 10K Ohms. Lower value resistors will allow more current to flow, which makes the LED brighter. Higher value resistors will restrict the current flow, which makes the LED dimmer.

Also, most LED’s have polarity, which means that they need to be connected the right way around. Usually, the LED’s shortest lead connects to the ground side.

If you connect the LED to pin 13 as shown in the image below, you can use the same code we used above to make the LED flash on and off.

Turn an LED on and off with the Arduino

Written By: Marcus Schappi

Difficulty

Easy

Steps

Push button switches are inexpensive and versatile components that have many uses.

In this guide, we will learn how to use a push button switch together with an Arduino, to turn an LED on and off. The circuit we will be building, uses a Little Bird Uno R3, a fully compatible Arduino development board. A mini pushbutton switch, a 5mm LED, jumper wires, and a mini breadboard is also required.

Other uses for push buttons are in custom gamepads, DIY radio buttons, MIDI controllers with push buttons that in conjunction with LEDs would light up when pressed, and many more!

Insert an LED into the breadboard with the Anode (positive leg) on the left and the Cathode (negative leg on the right).

Insert a 220 Ohm Resistor so that one leg is inline with the LED’s Cathode leg.

Resistors are not polarised, so orientation doesn’t matter.

This resistor will be used to limit the current going to our LED.

const int ledPin = 13;// We will use the internal LED const int buttonPin = 7;// the pin our push button is on void setup() { pinMode(ledPin,OUTPUT); // Set the LED Pin as an output pinMode(buttonPin,INPUT_PULLUP); // Set the Tilt Switch as an input } void loop() { int digitalVal = digitalRead(buttonPin); // Take a reading if(HIGH == digitalVal) { digitalWrite(ledPin,LOW); //Turn the LED off } else { digitalWrite(ledPin,HIGH);//Turn the LED on } }

Upload this code to your Arduino.

When you run this code, the LED on Pin 13 will turn on when the button is held down. That is all.

const unsigned int buttonPin = 7; const unsigned int ledPin = 13; int buttonState = 0; int oldButtonState = LOW; int ledState = LOW; void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); } void loop() { buttonState = digitalRead(buttonPin); if (buttonState != oldButtonState && buttonState == HIGH) { ledState = (ledState == LOW ? HIGH : LOW); digitalWrite(ledPin, ledState); delay(50); } oldButtonState = buttonState; }

Upload this code to your Arduino.

This program will toggle on and off the LED every time you push the button.

I have 2 questions related to each other, well at least in my case –

How can I read the status of an LED to check of it is ON or OFF, or may be Black or White?

How can I put 2 or 3 conditions using if else if to read the status of LEDs and execute the code accordingly?
For example –

if LED 1 is ON and LED 10 is ON, do something
if LED 1 is ON and LED 10 is OFF, do something else
if LED 1 is OFF and LED 10 is OFF, do nothing

I am trying the code below but no luck.

#include

#define NUM_LEDS 60
#define DATA_PIN 12
CRGB leds[NUM_LEDS];
const CRGB Test_Color = CRGB::White;
Void setup() {
FastLED.addLeds

(leds, NUM_LEDS);
FastLED.clear();
FastLED.show();
void buttonThree() {
Serial.println(“Button 3 has been pressed”);
if (leds[10] == Test_Color && leds[30] == Test_Color){
for (int k = 40, j = NUM_LEDS-40; k < NUM_LEDS- 40, j > 0 ; j–, k++){ // Lights_ON from 2/3
for(int whiteLed = 0; whiteLed < NUM_LEDS-k; whiteLed = whiteLed + 1) { // Move a single led
leds[whiteLed] = CRGB::White; // Turn our current led on to white, then show the leds
FastLED.show(); // Show the leds (only one of which is set to white, from above)
delay(10); // Wait a little bit
if ( whiteLed != j-1){ // Turn our current led back to black for the next loop around
leds[whiteLed] = CRGB::Black;
}}}}
else if {
do stuff
}
}

Oh wow! why didn’t I think about that. Thanks Brattain Member for your reply to a Newbie.

The problem is that I know when it is ON but Arduino can’t see unfortunately, at least mine can’t.
So like I explained in my original post, I want to get the ON/OFF status of LEDs after last code execution and based on that, decide which set of code to run when a button is pressed. If you need more information, here you go –

4 button for 4 light presets which are –

1/3 of total LEDs ON

2/3 of total LEDs ON

All LEDs ON

All LEDs OFF

To explain further for better understanding, there are different set of codes for going to preset 1 from preset 2,3 and 4

Blink

Turn an LED on and off every second.

This example shows the simplest thing you can do with an Arduino to see physical output: it blinks the on-board LED.

Hardware Required

  • Arduino Board

optional

  • LED

  • 220 ohm resistor

Circuit

This example uses the built-in LED that most Arduino boards have. This LED is connected to a digital pin and its number may vary from board type to board type. To make your life easier, we have a constant that is specified in every board descriptor file. This constant is LED_BUILTIN and allows you to control the built-in LED easily. Here is the correspondence between the constant and the digital pin.

  • D13 – 101

  • D13 – Due

  • D1 – Gemma

  • D13 – Intel Edison

  • D13 – Intel Galileo Gen2

  • D13 – Leonardo and Micro

  • D13 – LilyPad

  • D13 – LilyPad USB

  • D13 – MEGA2560

  • D13 – Mini

  • D6 – MKR1000

  • D13 – Nano

  • D13 – Pro

  • D13 – Pro Mini

  • D13 – UNO

  • D13 – Yún

  • D13 – Zero

If you want to light an external LED with this sketch, you need to build this circuit, where you connect one end of the resistor to the digital pin correspondent to the LED_BUILTIN constant. Connect the long leg of the LED (the positive leg, called the anode) to the other end of the resistor. Connect the short leg of the LED (the negative leg, called the cathode) to the GND. In the diagram below we show an UNO board that has D13 as the LED_BUILTIN value.

The value of the resistor in series with the LED may be of a different value than 220 ohms; the LED will light up also with values up to 1K ohm.

Schematic

Code

After you build the circuit plug your Arduino board into your computer, start the Arduino Software (IDE) and enter the code below. You may also load it from the menu File/Examples/01.Basics/Blink . The first thing you do is to initialize LED_BUILTIN pin as an output pin with the line


pinMode(LED_BUILTIN, OUTPUT);

In the main loop, you turn the LED on with the line:


digitalWrite(LED_BUILTIN, HIGH);

This supplies 5 volts to the LED anode. That creates a voltage difference across the pins of the LED, and lights it up. Then you turn it off with the line:


digitalWrite(LED_BUILTIN, LOW);

That takes the LED_BUILTIN pin back to 0 volts, and turns the LED off. In between the on and the off, you want enough time for a person to see the change, so the

commands tell the board to do nothing for 1000 milliseconds, or one second. When you use the

delay()

command, nothing else happens for that amount of time. Once you’ve understood the basic examples, check out the BlinkWithoutDelay example to learn how to create a delay while doing other things.

delay()

Once you’ve understood this example, check out the DigitalReadSerial example to learn how read a switch connected to the board.

See Also

Learn more

You can find more basic tutorials in the built-in examples section.

You can also explore the language reference, a detailed collection of the Arduino programming language.

Last revision 2015/07/28 by SM

Suggested changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.

1
6
7 #include

8
9 int RECV_PIN = 12;
10 int led1 = 8;
11 int led2 = 9;
12 int led3 = 10;
13 int led4 = 11;
14 int itsONled[] = {0,0,0,0,0};
15
19 #define code1 33772
20 #define code2 52972
21 #define code3 3494
22 #define code4 65160
23 IRrecv irrecv(RECV_PIN);
24
25 decode_results results;
26
27 void setup()
28 {
29 Serial.begin(9600);
30 irrecv.enableIRIn();
31 pinMode(led1, OUTPUT);
32 pinMode(led2, OUTPUT);
33 pinMode(led3, OUTPUT);
34 pinMode(led4, OUTPUT);
35 }
36
37 void loop() {
38 if (irrecv.decode(&results)) {
39 unsigned int value = results.value;
40 switch(value) {
41 case code1:
42 if(itsONled[1] == 1) {
43 digitalWrite(led1, LOW);
44 itsONled[1] = 0;
45 } else {
46 digitalWrite(led1, HIGH);
47 itsONled[1] = 1;
48 }
49 break;
50 case code2:
51 if(itsONled[2] == 1) {
52 digitalWrite(led2, LOW);
53 itsONled[2] = 0;
54 } else {
55 digitalWrite(led2, HIGH);
56 itsONled[2] = 1;
57 }
58 break;
59 case code3:
60 if(itsONled[3] == 1) {
61 digitalWrite(led3, LOW);
62 itsONled[3] = 0;
63 } else {
64 digitalWrite(led3, HIGH);
65 itsONled[3] = 1;
66 }
67 break;
68 case code4:
69 if(itsONled[4] == 1) {
70 digitalWrite(led4, LOW);
71 itsONled[4] = 0;
72 } else {
73 digitalWrite(led4, HIGH);
74 itsONled[4] = 1;
75 }
76 break;
77 }
78 Serial.println(value);
79 irrecv.resume();
80 }
81 }

Use a Push Button with Arduino

Arduino Blinking LED Tutorial
Arduino Blinking LED Tutorial

Step 1: LED Resistor Circuit

The LED’s legs are connected to two pins on the Arduino: ground and pin 13. The component between the LED and pin 13 is a resistor, which helps limit the current to prevent the LED from burning itself out. Without it, you’ll get a warning that the LED might burn out soon. It doesn’t matter whether the resistor comes before or after the LED in the circuit, or which way around it goes. The colored stripes identify the resistor’s value, and for this circuit, anywhere from 100 ohms to 1000 ohms will work great.

The LED, on the other hand, is polarized, which means it only works when the legs are connected a certain way. The positive leg, called the anode, usually has a longer leg, and gets wired to power, in this case coming from your Arduino’s output pin. The negative leg, called the cathode, with its shorter leg, connects to ground.

  1. In the components panel, drag a resistor and LED onto the workplane.
  2. Edit the resistor’s value by adjusting it to 220 ohms in the component inspector, which appears when the resistor is selected.
  3. Back in the components panel, find and bring over an Arduino Uno board.
  4. Click once to connect a wire to a component or pin, and click again to connect the other end. Connect your resistor to either side of the LED.
  5. If you connected your resistor to the LED’s anode (positive, longer), connect the resistor’s other leg to Arduino’s digital pin 13. If you connected your resistor to the LED’s cathode (negative, shorter leg), connect the resistor’s other leg to Arduino’s ground pin (GND).
  6. Create another wire between the unconnected LED leg and pin 13 or ground, whichever is still not connected.
  7. Extra credit: you can learn more about LEDs in the free Instructables LEDs and Lighting class.
  8. Continue to the next step.

Blink

Turn an LED on and off every second.

This example shows the simplest thing you can do with an Arduino to see physical output: it blinks the on-board LED.

Hardware Required

  • Arduino Board

optional

  • LED

  • 220 ohm resistor

Circuit

This example uses the built-in LED that most Arduino boards have. This LED is connected to a digital pin and its number may vary from board type to board type. To make your life easier, we have a constant that is specified in every board descriptor file. This constant is LED_BUILTIN and allows you to control the built-in LED easily. Here is the correspondence between the constant and the digital pin.

  • D13 – 101

  • D13 – Due

  • D1 – Gemma

  • D13 – Intel Edison

  • D13 – Intel Galileo Gen2

  • D13 – Leonardo and Micro

  • D13 – LilyPad

  • D13 – LilyPad USB

  • D13 – MEGA2560

  • D13 – Mini

  • D6 – MKR1000

  • D13 – Nano

  • D13 – Pro

  • D13 – Pro Mini

  • D13 – UNO

  • D13 – Yún

  • D13 – Zero

If you want to light an external LED with this sketch, you need to build this circuit, where you connect one end of the resistor to the digital pin correspondent to the LED_BUILTIN constant. Connect the long leg of the LED (the positive leg, called the anode) to the other end of the resistor. Connect the short leg of the LED (the negative leg, called the cathode) to the GND. In the diagram below we show an UNO board that has D13 as the LED_BUILTIN value.

The value of the resistor in series with the LED may be of a different value than 220 ohms; the LED will light up also with values up to 1K ohm.

Schematic

Code

After you build the circuit plug your Arduino board into your computer, start the Arduino Software (IDE) and enter the code below. You may also load it from the menu File/Examples/01.Basics/Blink . The first thing you do is to initialize LED_BUILTIN pin as an output pin with the line


pinMode(LED_BUILTIN, OUTPUT);

In the main loop, you turn the LED on with the line:


digitalWrite(LED_BUILTIN, HIGH);

This supplies 5 volts to the LED anode. That creates a voltage difference across the pins of the LED, and lights it up. Then you turn it off with the line:


digitalWrite(LED_BUILTIN, LOW);

That takes the LED_BUILTIN pin back to 0 volts, and turns the LED off. In between the on and the off, you want enough time for a person to see the change, so the

commands tell the board to do nothing for 1000 milliseconds, or one second. When you use the

delay()

command, nothing else happens for that amount of time. Once you’ve understood the basic examples, check out the BlinkWithoutDelay example to learn how to create a delay while doing other things.

delay()

Once you’ve understood this example, check out the DigitalReadSerial example to learn how read a switch connected to the board.

See Also

Learn more

You can find more basic tutorials in the built-in examples section.

You can also explore the language reference, a detailed collection of the Arduino programming language.

Last revision 2015/07/28 by SM

Suggested changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.

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

How to Blink an LED with Arduino (Lesson #2)
How to Blink an LED with Arduino (Lesson #2)

Introduction: Blink an LED With Digital Output

Let’s learn how to blink an LED (light emitting diode) using Arduino’s digital output. If you’re new to Arduino, this is a great place to start. We’ll connect an LED to the Arduino Uno and compose a simple program to turn the LED on and off. Here in Tinkercad Circuits, you can explore the sample circuit and build your own right next to it.

  1. Click “Start Simulation” to watch the LED blink. You can use the simulator any time to test your circuits.
  2. Continue to the next step.

Changing the Pin

If you want to use a different pin to power the LED, it’s easy to change it. For example, say you want to use pin 8 instead of pin 13. First move the signal wire from pin 13 over to pin 8:

Now you’ll need to edit a line of code in the program so the Arduino knows which pins to use as output pins. That’s done on line 2 of the code above, where it says:


pinMode(13, OUTPUT);

To use pin 8, you just have to change the 13 to an 8:


pinMode(8, OUTPUT);

Next you’ll need to change the code that tells the Arduino which pins will get the HIGH and LOW output signals. That’s done everywhere there’s a

digitalWrite()

function. In the program above, there’s one on line 5 and one on line 7:


digitalWrite(13, HIGH);


digitalWrite(13, LOW);

To specify that pin 8 should get the HIGH and LOW signals, you just need to change the 13’s to 8’s:


digitalWrite(8, HIGH);


digitalWrite(8, LOW);

The finished program should look like this:


void setup() { pinMode(8, OUTPUT); } void loop() { digitalWrite(8, HIGH); delay(1000); digitalWrite(8, LOW); delay(1000); }

After uploading, the LED should flash just like it did when it was connected to pin 13.

Arduino: Use a Button to Toggle an LED
Arduino: Use a Button to Toggle an LED

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:

In this tutorial, I’ll show you how to use an Arduino to control LEDs. This is a pretty simple project, but you should learn how to do it early on because lots of other sensors and modules are programmed the exact same way.

First I’ll show you how to turn on and off the Arduino’s on-board LED. Then I’ll show you how to turn on and off an LED connected to one of the Arduino’s digital pins. I’ll explain how to change the LEDs flashing rate, and how to change the pin that powers the LED. At the end I’ll show you how to control multiple LEDs. Before starting, you should have the Arduino IDE software installed on your computer.

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.

The code

#define LED_PIN 8 #define BUTTON_PIN 7 void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); } void loop() { if (digitalRead(BUTTON_PIN) == HIGH) { digitalWrite(LED_PIN, HIGH); } else { digitalWrite(LED_PIN, LOW); } }

Let’s break this code down line by line.

Setup

#define LED_PIN 8 #define BUTTON_PIN 7

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.

void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); }

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

void loop() { if (digitalRead(BUTTON_PIN) == HIGH) { digitalWrite(LED_PIN, HIGH); } else { digitalWrite(LED_PIN, LOW); } }

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.

Arduino for Beginners: Using Push button to turn ON LED light
Arduino for Beginners: Using Push button to turn ON LED light

Arduino Code

/* Blink Turns on an LED on for one second, then off for one second, repeatedly. */ // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin 13 as an output. pinMode(2, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(2, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }

Turn an LED on and off with the Arduino

Written By: Marcus Schappi

Difficulty

Easy

Steps

Push button switches are inexpensive and versatile components that have many uses.

In this guide, we will learn how to use a push button switch together with an Arduino, to turn an LED on and off. The circuit we will be building, uses a Little Bird Uno R3, a fully compatible Arduino development board. A mini pushbutton switch, a 5mm LED, jumper wires, and a mini breadboard is also required.

Other uses for push buttons are in custom gamepads, DIY radio buttons, MIDI controllers with push buttons that in conjunction with LEDs would light up when pressed, and many more!

Insert an LED into the breadboard with the Anode (positive leg) on the left and the Cathode (negative leg on the right).

Insert a 220 Ohm Resistor so that one leg is inline with the LED’s Cathode leg.

Resistors are not polarised, so orientation doesn’t matter.

This resistor will be used to limit the current going to our LED.

const int ledPin = 13;// We will use the internal LED const int buttonPin = 7;// the pin our push button is on void setup() { pinMode(ledPin,OUTPUT); // Set the LED Pin as an output pinMode(buttonPin,INPUT_PULLUP); // Set the Tilt Switch as an input } void loop() { int digitalVal = digitalRead(buttonPin); // Take a reading if(HIGH == digitalVal) { digitalWrite(ledPin,LOW); //Turn the LED off } else { digitalWrite(ledPin,HIGH);//Turn the LED on } }

Upload this code to your Arduino.

When you run this code, the LED on Pin 13 will turn on when the button is held down. That is all.

const unsigned int buttonPin = 7; const unsigned int ledPin = 13; int buttonState = 0; int oldButtonState = LOW; int ledState = LOW; void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); } void loop() { buttonState = digitalRead(buttonPin); if (buttonState != oldButtonState && buttonState == HIGH) { ledState = (ledState == LOW ? HIGH : LOW); digitalWrite(ledPin, ledState); delay(50); } oldButtonState = buttonState; }

Upload this code to your Arduino.

This program will toggle on and off the LED every time you push the button.

  • Arduino Tutorial
  • Arduino – Home
  • Arduino – Overview
  • Arduino – Board Description
  • Arduino – Installation
  • Arduino – Program Structure
  • Arduino – Data Types
  • Arduino – Variables & Constants
  • Arduino – Operators
  • Arduino – Control Statements
  • Arduino – Loops
  • Arduino – Functions
  • Arduino – Strings
  • Arduino – String Object
  • Arduino – Time
  • Arduino – Arrays
  • Arduino Function Libraries
  • Arduino – I/O Functions
  • Arduino – Advanced I/O Function
  • Arduino – Character Functions
  • Arduino – Math Library
  • Arduino – Trigonometric Functions
  • Arduino Advanced
  • Arduino – Due & Zero
  • Arduino – Pulse Width Modulation
  • Arduino – Random Numbers
  • Arduino – Interrupts
  • Arduino – Communication
  • Arduino – Inter Integrated Circuit
  • Arduino – Serial Peripheral Interface
  • Arduino Projects
  • Arduino – Blinking LED
  • Arduino – Fading LED
  • Arduino – Reading Analog Voltage
  • Arduino – LED Bar Graph
  • Arduino – Keyboard Logout
  • Arduino – Keyboard Message
  • Arduino – Mouse Button Control
  • Arduino – Keyboard Serial
  • Arduino Sensors
  • Arduino – Humidity Sensor
  • Arduino – Temperature Sensor
  • Arduino – Water Detector / Sensor
  • Arduino – PIR Sensor
  • Arduino – Ultrasonic Sensor
  • Arduino – Connecting Switch
  • Motor Control
  • Arduino – DC Motor
  • Arduino – Servo Motor
  • Arduino – Stepper Motor
  • Arduino And Sound
  • Arduino – Tone Library
  • Arduino – Wireless Communication
  • Arduino – Network Communication
  • Arduino Useful Resources
  • Arduino – Quick Guide
  • Arduino – Useful Resources
  • Arduino – Discussion

Arduino – Blinking LED

LEDs are small, powerful lights that are used in many different applications. To start, we will work on blinking an LED, the Hello World of microcontrollers. It is as simple as turning a light on and off. Establishing this important baseline will give you a solid foundation as we work towards experiments that are more complex.

Dancing lights || LED chaser circuit with 32 cool effects || Arduino Project
Dancing lights || LED chaser circuit with 32 cool effects || Arduino Project

Step 2: Simple Code With Blocks

Let’s go through the simple code blocks controlling the blink by opening the code editor (button labeled “Code”). You can resize the code editor by clicking and dragging the left edge.

The code starts out with two gray comment blocks, which are just notes for us humans to read. The first blue output block sets the built-in LED HIGH, which is Arduino’s way of describing “on.” This output command will activate a 5V signal to anything connected to the specified pin. Next up is a a yellow command block that waits for one second, simple enough. So the program will pause while the LED is on for one second. Next after another comment is a blue output block to set the LED back to LOW, or “off,” followed by another second-long pause.

  1. Try customizing this code by changing the wait times, and clicking “Start Simulation”.
    You can even add more output and wait blocks to create longer flashing patterns.

    HINT: Did you notice the small LED flashing on the board itself? This built in LED is also connected to pin 13, and is meant to be used for testing purposes without the need to connect any external components. It even has its own tiny resistor, soldered directly to the surface of the board.

  2. Continue to the next step.

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.

The code

#define LED_PIN 8 #define BUTTON_PIN 7 byte lastButtonState = LOW; byte ledState = LOW; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); } void loop() { byte buttonState = digitalRead(BUTTON_PIN); if (buttonState != lastButtonState) { lastButtonState = buttonState; if (buttonState == LOW) { ledState = (ledState == HIGH) ? LOW: HIGH; digitalWrite(LED_PIN, ledState); } } }

Let’s analyze the code.

Setup

#define LED_PIN 8 #define BUTTON_PIN 7

Those defines are the same as before.

byte lastButtonState = LOW; byte ledState = LOW;

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.

void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); }

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

void loop() { byte buttonState = digitalRead(BUTTON_PIN);

The first thing we do is to read the button’s state and to store it inside a new local variable.

if (buttonState != lastButtonState) {

Then we can compare the current state to the last one (from the previous execution of the loop function). 4 possibilities here:

  1. LOW -> LOW (last -> current).
  2. LOW -> HIGH.
  3. HIGH -> LOW.
  4. 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.

lastButtonState = buttonState;

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.

if (buttonState == LOW) {

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

ledState = (ledState == HIGH) ? LOW : HIGH;

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.

digitalWrite(LED_PIN, ledState); } } }

And the last thing we need to do is of course to physically set the state for the LED, with the new computed state.

8x8x8 LED CUBE WITH ARDUINO UNO
8x8x8 LED CUBE WITH ARDUINO UNO

Step 3: Blink Arduino Code Explained

When the code editor is open, you can click the dropdown menu on the left and select “Blocks + Text” to reveal the Arduino code generated by the code blocks. All the extra symbols are part of Arduino’s syntax, but don’t be intimidated! It takes time to learn to write proper code from scratch. We’ll go through each piece here, and you can always use the blocks for comparison as you level up throughout the lessons on this site.

  1. /* This program blinks pin 13 of the Arduino (the built-in LED) */

    This first section is title block comment, describing what the program does. Block comments are bookended by an opening


    /*

    and closing

    */

    .

  2. void setup() { pinMode(13, OUTPUT); }

    Next is the code’s setup, which helps set up things your program will need later. It runs once when the program starts up, and contains everything within its curly braces


    { }

    . Our blink sketch’s setup configures pin 13 as an output, which prepares the board to send signals to it, rather than listen.

  3. void loop() { // turn the LED on (HIGH is the voltage level) digitalWrite(13, HIGH); delay(1000); // Wait for 1000 millisecond(s) // turn the LED off by making the voltage LOW digitalWrite(13, LOW); delay(1000); // Wait for 1000 millisecond(s) }

    The main body of the program is inside the loop, indicated by another set of curly braces


    { }

    . This part of the code will execute on repeat, so long as the board has power. The colored text following double slashes are also comments to help make the program easier to understand. The output command we’re using is called

    digitalWrite()

    , which is a function that sets a pin HIGH or LOW, on or off. To pause the program we’ll use

    delay()

    , which takes a number of milliseconds (1000ms = 1s).

  4. Continue to the next step.

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

#define LED_PIN 8 #define BUTTON_PIN 7 byte lastButtonState = LOW; byte ledState = LOW; unsigned long debounceDuration = 50; // millis unsigned long lastTimeButtonStateChanged = 0; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); } void loop() { if (millis() – lastTimeButtonStateChanged > debounceDuration) { byte buttonState = digitalRead(BUTTON_PIN); if (buttonState != lastButtonState) { lastTimeButtonStateChanged = millis(); lastButtonState = buttonState; if (buttonState == LOW) { ledState = (ledState == HIGH) ? LOW: HIGH; digitalWrite(LED_PIN, ledState); } } } }

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.

Debounce explained

unsigned long debounceDuration = 50; // millis unsigned long lastTimeButtonStateChanged = 0;

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.

void loop() { if (millis() – lastTimeButtonStateChanged > debounceDuration) {

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.

if (buttonState != lastButtonState) { lastTimeButtonStateChanged = millis();

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.

WS2812 WS2811 LED Video Arduino LEDStrip effects
WS2812 WS2811 LED Video Arduino LEDStrip effects

Procedure

Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.

Note − To find out the polarity of an LED, look at it closely. The shorter of the two legs, towards the flat edge of the bulb indicates the negative terminal.

Components like resistors need to have their terminals bent into 90° angles in order to fit the breadboard sockets properly. You can also cut the terminals shorter.

Step 5: Programming a Physical Arduino (Optional)

To program your physical Arduino Uno, you’ll need to install the free software (or plugin for the web editor), then open it up.

  1. Copy the code from the Tinkercad Circuits code window and paste it into an empty sketch in your Arduino software, or click the download button (downward facing arrow) and open the resulting file using Arduino. This beginner example is also available directly within the Arduino software under File-> Examples-> 01.Basics-> Blink.
  2. Plug in your USB cable and select your board and port in the software’s Tools menu.
  3. Upload the code and watch your onboard LED flash with the custom blink you created earlier! For a more in-depth walk-through on setting up and programming your physical Arduino Uno board, check out the free Instructables Arduino class (first lesson).
  4. Continue to the next step.
How To Control WS2812B Individually Addressable LEDs using Arduino
How To Control WS2812B Individually Addressable LEDs using Arduino

Keywords searched by users: arduino code for led on off

Multiple Blinking Led On The Arduino : 4 Steps - Instructables
Multiple Blinking Led On The Arduino : 4 Steps – Instructables
Arduino 2 Push Button One Led : Switch On/Off
Arduino 2 Push Button One Led : Switch On/Off
Led Blinking Using Arduino (4 Examples) With Code, Circuit And Video
Led Blinking Using Arduino (4 Examples) With Code, Circuit And Video
How Do I Make The Leds Stay On After Pressing A Switch? Then Stay Off When  The Switch Is Pressed Succeeding The Last - Programming Questions - Arduino  Forum
How Do I Make The Leds Stay On After Pressing A Switch? Then Stay Off When The Switch Is Pressed Succeeding The Last – Programming Questions – Arduino Forum
Arduino - Turn Led On And Off With Push Button - Youtube
Arduino – Turn Led On And Off With Push Button – Youtube

See more here: kientrucannam.vn

Leave a Reply

Your email address will not be published. Required fields are marked *