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.
Hardware Required
Components | Buy From Amazon |
Arduino UNO | Buy Link |
LED 5mm | Buy Link |
Button | Buy Link |
Resistor 220Ω | Buy Link |
Jumper Wires | Buy Link |
Breadboard | Buy Link |
How can we make the LED less bright?
LED brightness is controlled by current. So, to dim an LED, we need to reduce current. But how? Recall Ohm’s Law: \(V=I * R\) or \(I = \frac{V}{R}\). Thus, we can reduce current either by:
- Decreasing voltage
- Increasing resistance
In future tutorials, we’ll show how you can control voltage output programmatically by writing code for the Arduino microcontroller. But, for now, let’s dim the LED by first decreasing voltage using the Arduino’s 3.3V pin (rather than the 5V pin) and then by using higher value resistors. This is similar to the activities in our LED lessons but now we are using the Arduino’s pins as a voltage source.
Hooking up the LED to the 3.3V supply pin
The Arduino Uno provides both a 5V power supply (which we just used) and a 3.3V power supply.
Let’s move the LED anode (long leg) from the 5V pin to the 3.3V pin but keep the 220Ω resistor. What do you observe? The LED should be less bright! This is because there is less current flowing through the 3.3V circuit.
Recall from above that with 5V, we have \(I=\frac{V_R}{R}=\frac{3V}{220Ω}=13.6mA\). With the 3.3V output pin, this drops to \(I=\frac{V_R}{R}=\frac{1V}{220Ω}=4.5mA\)
Here’s a workbench photo of the LED wired to the 3.3V port. The LED is noticeably less bright:
Full video walkthrough
Here’s a full video walkthrough of wrapping the resistor around the LED anode leg, wiring the circuit to 5V and GND, and then switching from the 5V to the 3.3V supply.
Using higher value resistors
We just showed how reducing the supply voltage (\(V_s\)) proportionally reduces current and, therefore, the LED brightness. Now, let’s play around with higher-value resistors such as a 680Ω, 2.2kΩ, or 10kΩ, and see their effect. What happens?
You should observe that the LED’s brightness decreases as the resistance increases as the LED brightness depends on current (\(I = \frac{V_R}{R}\)).
Resistor | Resistor Image | Vs | Resulting Current |
220Ω | 5V | \(I = \frac{3V}{220Ω}= 13.6mA\) | |
680Ω | 5V | \(I = \frac{3V}{680Ω}= 4.4mA\) | |
1kΩ | 5V | \(I = \frac{3V}{1,000Ω}= 3mA\) | |
2.2kΩ | 5V | \(I = \frac{3V}{2,200Ω}= 1.4mA\) | |
10kΩ | 5V | \(I = \frac{3V}{10,000Ω}= 0.3mA\) |
We can verify these theoretical predictions using a multimeter to measure (\(V_s\)), the actual resistor values, and the current \(I\). We conducted these measurements using a Fluke 115 True RMS Multimeter.
A few important notes:
- Each electronic component that we use from the LED to the resistors to the supply voltage (\(V_s\)) are going to differ slightly from ideal. Our carbon film resistors, for example, have a tolerance of 5% (indicated by the gold band), and I measured our supply voltage on the Arduino Uno to be (\(V_s\)=4.902V) rather than 5V.
- The Fluke 115 provides three digits of precision. So, the multimeter reads 0.013A, 0.004A, etc. Thus, it’s not possible to compare our theoretical predictions to the 4th digit of precision (which impacts our low current—milliamp—comparisons).
Again, we assume a \(V_f=2V\) for our red LED (we could also measure this directly in each circuit):
Resistor | Resistor Image | Measured Resistance | Measured Vs | Measured Current | Ohm’s Law |
220Ω | 218.8Ω | 4.902V | 13mA | \(I = \frac{2.902V}{218.8Ω}= 13.3mA\) | |
680Ω | 680Ω | 4.902V | 4mA | \(I = \frac{2.902V}{680Ω}= 4.3mA\) | |
1kΩ | 994Ω | 4.902V | 3mA | \(I = \frac{2.902V}{994Ω}= 2.9mA\) | |
2.2kΩ | 2.204kΩ | 4.902V | 1mA | \(I = \frac{2.902V}{2,204Ω}= 1.3mA\) | |
10kΩ | 9.92kΩ | 4.902V | < 0mA | \(I = \frac{2.902V}{9,920Ω}= 0.3mA\) |
If you want to know more about how to use a multimeter, here are a few “getting started” guides:
- How to use a multimeter, Sparkfun Tutorials
- Multimeters, Adafruit Learning
They have multimeters in Tinkercad Circuits, so you can also use and play with them there (if you do not have one at home).
Next Lesson
In the next lesson, we will learn how to programmatically control the output voltage of a digital I/O pin to switch between
LOW
(0V) or
HIGH
(5V) using
digitalWrite(int pin, int value)
.
Next: Blinking an LED with Arduino
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
Use a Push Button with Arduino
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:
- HIGH signal sent to pin 8
- Wait for 1000 ms
- HIGH signal sent to pin 13
- Wait for 1000 ms
- LOW signal sent to pin 8
- Wait for 1000 ms
- LOW signal sent to pin 13
- Wait for 1000 ms
- 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:
- HIGH signal sent to pin 8
- HIGH signal sent to pin 13
- Wait for 1000 ms
- LOW signal sent to pin 8
- LOW signal sent to pin 13
- Wait for 1000 ms
- 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…
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.
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.
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.
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
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:
Tổng kết
Qua bài học đầu tiên các bạn sẽ nắm được những kiến thức về kiểu dữ liệu số nguyên (int), cách sử dụng biến như thế nào, sử dụng hàm và cách làm việc của vòng lặp.
Nếu các bạn bạn thấy bài viết bổ ích nhớ Like và Share để mọi người cùng học nha.
- Để nhận thêm nhiều kiến thức bổ ích Đăng ký để nhận thông báo khi có bài viết mới nhất.
- Tham gia Cộng đồng Arduino KIT trên Fanpage.
Chúc các bạn thành công!
Trân trọng.
Stepping down power supply voltages
If we plug in a 7-12V wall adapter or a 9V battery to the Arduino’s barrel jack, then how does the Arduino convert these higher voltages to 5V? Using a component called a voltage regular, which can take in a range of DC voltages and step it down (but not up) to a stable constant voltage. You can buy and use voltage regulators in your own projects. If you want to learn more about about the Arduino Uno’s power supply sub-system, read this technobyte blog post.
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 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.
Features:
- Compact design: Push button switches to have a small and compact design that makes them easy to install and use.
- Versatile: Push button switches are available in a variety of configurations, including momentary and latching types, and with different switch functions.
- Easy to operate: Push-button switches easily operate with a single finger or hand.
- Durable: Push button switches are typically designed to withstand repeated use, making them a reliable option for controlling electrical circuits.
- Color-coded: Push button switches are often color-coded to indicate their function or status, making them easy to identify.
- Affordable: Push button switches are generally affordable and cost-effective compared to other types of switches.
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.
Table of Contents
- Materials
-
Hook up LED to Arduino’s 5V supply pin
- Step 1: Wrap resistor around LED leg
- Step 2: Connect components to Arduino
- Step 3: Connect your Arduino to power
- Let’s analyze our circuit
- Maximum current draw
- Stepping down power supply voltages
- How can we make the LED less bright?
- Next Lesson
For our first learning activity, we are going to use Arduino to turn on an LED. We’re not going to write any code. Instead, our goal is to build some initial familiarity with Arduino hardware and connecting components to Arduino pins before we introduce programming, which we do in the next lesson.
Figure The movement of current in the circuit is illustrated by the animated yellow circles. This visualization is a coarse abstraction designed to emphasize the direction of current flow. A more accurate visualization would show that electrons are already distributed throughout a wire before a voltage is applied. See our Introduction to Electronics series, specifically the lesson on Voltage, Current, and Resistance.
Code
//For more info Visits: www.arduinocircuit.com int ledPin = 13; //The LED is connected to pin 13 int button = 7; //The button is connected to pin 7 int val = 0; void setup() { pinMode(ledPin, OUTPUT); //The pin of the led is an output pinMode(button, INPUT); //The pin of the button is an input } void loop() { val = digitalRead(button); //Read the button if (val == 1){ //If the button's value is 1 digitalWrite(ledPin, HIGH); //Turn on the led } else { // Else: digitalWrite(ledPin, LOW); //Turn off the led } }
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
Sơ đồ đấu nối
Các linh kiện cần thiết cho bài học
Tên linh kiện | Số lượng | Shopee |
Arduino Uno R3 | Mua ngay | |
Cáp nạp | Mua ngay | |
Dây cắm (Đực – Đực) | Mua ngay | |
Điện trở 220R | Mua ngay | |
Led 5mm | Mua ngay | |
Breadboard | Mua ngay |
Giải thích Code
Comment
Trong Arduino bạn sẽ bắt gặp 2 dạng comment: Comment đơn dòng và đa dòng
- Comment theo kiểu đa dòng
Mở đầu bằng /* và kết thúc */ ở dạng comment này không giới hạn ký tự và số dòng.
/* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */
- Comment theo kiểu đơn dòng
Mở đầu bằng // và kéo dài cho tới cuối dòng
digitalWrite(ledPin,HIGH); // turn the LED on (HIGH is the voltage level)
Kiểu số nguyên int
int ledPin = 10;
Kiểu dữ liệu | Độ rộng bit | Dãy giá trị |
int (số nguyên) | 2 byte (16bit) | -32,768 đến 32,767 |
- ledPin = 10: Là tên biến (ở đây bạn có thể đặt tên gì mà bạn mong muốn, tốt nhất là các bạn đặt theo tên của chức năng để dễ dàng nhớ khi code. Ở đây mình kết nối LED vào chân số 10 trên Arduino UNO).
- Kết thúc khai báo bằng dấu (;): Trong trường hợp bạn không có (;) thì trình biên dịch sẽ báo lỗi.
Hàm setup()
void setup() {}
Hàm setup() được Arduino đọc khi bắt đầu khởi động. Nó dùng để khởi tạo biến, khởi tạo thư viện và thiết lập thông số.
Hàm setup()
chỉ chạy một lần khi bật nguồn hoặc reset lại chương trình.
Code ví dụ chớp tắt Led
/* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 10 has an LED connected on most Arduino boards. // give it a name: int ledPin = 10; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(ledPin, OUTPUT); } // the loop routine runs over and over again forever: void loop() { digitalWrite(ledPin,HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(ledPin,LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }
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.
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.
Materials
For this lesson, you will need the following materials. Please build with us to advance your understanding and skillset—the best way to learn is by doing!. For those students enrolled in our courses, please document your creation journeys in your prototyping journals and attempt to answer and reflection on posed questions.
Arduino | LED | Resistor |
Arduino Uno, Leonardo, or similar | Red LED | 220Ω Resistor |
We’ll be using the Arduino Leonardo for these introductory microcontroller lessons but any 5V board will work, including the Arduino Uno, Adafruit’s METRO 328, Sparkfun’s RedBoard, etc. Each of these boards have the same pin layout and general specifications.
pinMode
pinMode(ledPin, OUTPUT);
-
"pinMode"
: Cấu hình quy định hoạt động của một chân như là một đầu vào (INPUT) hoặc đầu ra (OUTPUT). - “Pin”: Là chân mà bạn muốn đặt.
- “Mode”: INPUT, OUTPUT hoặc INPUT_PULLUP.
Vòng lặp
void loop() {}
Sau khi hàm
setup ()
chạy xong, những lệnh trong vòng
loop ()
sẽ thực hiện và chúng sẽ lặp đi lặp lại cho đến khi Arduino bị ngắt nguồn hoặc reset lại chương trình.
digitalWrite(ledPin,HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite
ghi giá trị mức “CAO” (bật) hoặc mức “THẤP” (tắt) vào chân được cấu hình. Nếu chân được cấu hình là OUTPUT bởi pinMode, thì điện áp của nó sẽ tương ứng với giá trị được đặt: 5V (hoặc 3.3V trên bo là 3.3V) là mức “CAO”, 0V là mức “THẤP”.
Delay()
delay(1000); // wait for a second
-
delay()
: Tạm dừng chương trình trong khoảng thời gian chỉ định (được tính bằng mili giây) và ở đây (1000 mili giây sẽ bằng 1 giây).
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:
- 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.
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.
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 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.
Specifications:
- Contact rating: The contact rating of a push button switch specifies the maximum current and voltage that it can handle.
- Switch function: The switch function of a push button switch determines how it behaves when the button is pressed or released. Common functions include on/off, momentary, and latching.
- Actuation force: The actuation force of a push button switch specifies the amount of force required to press the button and activate the switch.
- Contact configuration: The contact configuration of a push button switch determines how the contacts connect in the switch, such as normally open (NO), normally closed (NC), or changeover (CO).
- Termination style: The termination style of a push button switch specifies how it connects to a circuit, such as through soldering, wiring, or a PCB mount.
- Environmental rating: The environmental rating of a push button switch specifies its resistance to factors such as temperature, moisture, and dust.
Hook up LED to Arduino’s 5V supply pin
Step 1: Wrap resistor around LED leg
Grab a 220Ω resistor (or any resistor 220Ω or greater) and twist one leg around an LED leg. If you want to follow my example exactly, connect the resistor to the LED’s anode (long leg) but either leg will work. (Remember, a current limiting resistor can go on either side of an LED, see our LED lesson).
To wire wrap your components, simply twist the legs together like this:
Video. An example of wire wrapping a 220Ohm resistor leg (or lead) directly around the anode of an LED
Step 2: Connect components to Arduino
Insert the LED + resistor into the Arduino: the LED’s cathode (short leg) to GND and the LED’s anode (long leg) + resistor to the Arduino’s voltage supply, which you can access via the 5V pin.
Step 3: Connect your Arduino to power
Now connect your Arduino to power and the LED should light up. You did it!
Here’s a photo of the version I made. I found it easier to stretch the wiring across the Arduino from the 5V port to the GND on the opposite side.
For power, you can use a USB cable (which supplies 5V) or a 9V battery (which supplies 9V). Either way, the Arduino supplies 5V through the 5V pin. How? Using a voltage regulator. See “More Info” below.
USB Power | 9V Power |
With USB power, the 5V pin supplies 5V | Using the Arduino’s barrel jack, we can connect an external power supply like a 7-12V wall adapter or a 9V battery. The Arduino’s internal voltage regulator reduces these higher voltages to output a clean 5V |
Let’s analyze our circuit
Just as we did in our LED lesson, let’s analyze how much current is flowing through this simple LED-based circuit. To do this, we first need to determine the voltage drop across the resistor \(V_R\) and then use Ohm’s Law to figure out the current (\(I = \frac{V_R}{R}\)).
Step 1: Identify nodes and what we know
We always start by identifying nodes and what we know. We know that as long as \(V_f\) is satisfied, that there will be a voltage drop \(V_R\) across our resistor and a voltage drop \(V_D\) across our LED.
Due to Kirchhoff’s Circuit Laws, we know that the total voltage drop across both the resistor and LED (\(V_R + V_D\)) must equal our supply voltage \(V_S=5V\). From our LED lesson, we know that our circuit is off until the “on” or “forward” voltage of our LED is met, which for a red LED is ~2V. Thus, we can set \(V_D=2V\) and solve for \(V_R\).
Step 2: Solve for voltage drop across the resistor
Solving for \(V_R\):
\[V_S = V_R + V_D \\ V_R = V_S – V_D \\ V_R = 5V – 2V = 3V\]
Step 3: Solve for current
From Ohm’s Law, we know that the total current in our circuit is equal to the voltage drop across our resistor \(V_R\) divided by the resistance value \(R\). That is, \(I = \frac{V_R}{R}\). And we know that \(V_R=3V\) and \(R=220Ω\). Thus, the current through our circuit is:
\[I = \frac{V_R}{R} \\ I = \frac{3V}{220Ω} = 0.014A = 13.6mA\]
So, with the 5V supply pin, our circuit is drawing 13.6mA of current. Is this a lot or a little? Let’s put this in context below.
Maximum current draw
The Arduino has a variety of pin types, each with their own maximum current ratings.
-
I/O Pins: The maximum current draw of any single I/O pin—which we haven’t used yet but we will in the next lesson—is 40 mA (a safer, continuous range is ~20mA). The total current across all I/O pins together is 200mA. If we exceed these values, we could damage our Arduino board or the underlying microcontroller (the ATmega328 for the Uno or the ATmega32u4 for the Leonardo)
-
Power supply pins: The 5V output pin can supply ~400-500mA when powered by USB and ~900-1000mA when using an external power adapter. The 3.3V output pin can supply ~150mA; however, if you have both 3.3V and 5V output pins connected, any current drawn from the 3.3V pin will be counted against 5V’s total current.
The only protection fuse is a resettable polyfuse on the USB port, which limits current to 500mA on the 5V output pin (but only when powered by USB).
There are a variety of discussions about the Arduino Uno and Leonardo’s maximum current draw online. The best resource I’ve found are these StackExchange posts, which also link to datasheets (post1, post2).
Maximum number of LEDs in series
An interesting question to ponder then is: with the Arduino powered via USB (max 500mA current), how many red LEDs could you hook up in series to the 5V supply pin? How about in parallel? What is the limiting factor for each?
Well, for a simple series configuration, the total number of series LEDs is limited to the voltage supply, which is 5V. With a 200Ω resistor and a red LED with a “forward” voltage of \(V_f=2V\), we are limited to a maximum of two LEDS: \(2 * 2V = 4V\). However, in practice, I was able to get three LEDs in series (because the LED begins to turn on a bit around ~1.7-1.8V) though they were quite dim. See the table and image below for my measurements.
Resistor | Num Red LEDs in Series | Voltage Drop Across Each LED | Voltage Drop Across Resistor | Current |
200Ω | 2.02V | 2.95 | 14.9mA | |
200Ω | 1.92V | 1.21V | 6.1mA | |
200Ω | 1.71V | 0.021V | 0.1mA | |
200Ω | 1.01V | ~0V | ~0 mA |
Table. For this empirical measurement test, I used the Sparkfun 5mm diffused RED LEDs.
Here’s a picture of the test setup and circuits for the measurements above:
Figure. Measuring the individual LED voltage drop and current through the circuit using two multimeters: the yellow multimeter configured as a voltmeter to measure the voltage drop \(V_D\) over the first LED in the circuit and the red multimeter configured as a ammeter to measure the current \(I\) through the circuit.
Finally, we can also examine this circuit in a simulator, which mirrors our empirical measurements:
Video. A CircuitJS simulation of various LED series configurations with a 5V voltage supply.
Maximum number of LEDs in parallel
For the parallel configuration, the limiting factor is the total amount of current we can source, which with the 5V pin powered by USB, is 500mA. How many red LEDs does it take to exceed 500mA using 200Ω resistors?
Well, in a parallel configuration, each resistor+LED branch is getting ~\(I=\frac{V_R}{R}=\frac{3V}{200}=15mA\). Thus, the maximum number of LEDs in parallel is \(\frac{500mA}{15mA}=33.3\) rounded to 34.
Figure. 34 LEDs in parallel draws 514.1mA of current, which exceeds the maximum amount of the 5V output pin on the Arduino (when powered by USB). Here’s the CircuitJS link.
I attempted to “stress” test the maximum values a bit using the USB port on an old MacBook Pro (do not do this!). Even though I exceeded both the 500mA limit with the 5V output pin (563mA) and the 150mA limit with the 3.3V pin (314mA), I did not trigger the fuse. However, I only kept the board plugged in for a short time.
Figure. I “stress tested” the 5V output pin using the USB for power. Do not attempt! Despite exceeding the rated maximums, I failed to trigger the Arduino’s internal fuse on the 5V or 3.3V supplies. Note, the I/O pins do not have such protect so you could damage your board if you overdraw current.
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:
Applications:
- Industrial equipment: Push button switches commonly uses in industrial equipment such as machinery, conveyor systems, and control panels.
- Automotive: Push button switches often use in automotive applications, such as in dashboard controls and door locks.
- Medical devices: Push button switches to use in medical devices such as infusion pumps and patient monitors.
- Appliances: Push button switches uses in various home appliances such as washing machines, refrigerators, and microwaves.
- Consumer electronics: Push button switches to use in various electronic devices such as remote controls, audio equipment, and gaming consoles.
- Lighting: Push button switches are often used in lighting systems, such as in switches for turning lights on and off or changing their brightness.
Other Arduino Codes and Videos by Robojax
دروس آردوینو به فارسی
/* * This is the Arduino code for push button to turn LED ON and OFF * the output pen 10 is connected to relay * watch video instruction on video http://youTu.be/2WwedCRwmgA * * * Written by Ahmad Nejrabi for Roboja Video, www.Robojax.com * Date: Dec 14, 2017, in Ajax, Ontario, Canada * Permission granted to share this code given that this * note is kept with the code. * Disclaimer: this code is "AS IS" and for educational purpose only. Be carefull working with AC is dangrous. Disconnect from AC power when working and wear protective gloves when touch the AC components. * http://robojax.com/learn/arduino/ * */ void setup() { pinMode(2, INPUT_PULLUP);// define pin two as input for push button pinMode(10, OUTPUT);// defind pin 10 as output } void loop() { int pusshed = digitalRead(2);// read pin 2 and put the result in the "pusshed" variable if(pusshed == LOW){ digitalWrite(10, HIGH);// if pusheed is equal LOW, turn the pin 10 HIGH (give it 5v) }else{ digitalWrite(10, LOW);// else set pin 10 to low or zero volt } }
If you found this tutorial helpful, please support me so I can continue creating content like this. support me via PayPal
Bài 1: Chớp tắt LED trên Arduino Uno
Trong bài viết hôm nay mình xin giới thiệu với các bạn cách chớp tắt Led trên Arduino Uno.
Và cách tạo một biến ra sao, cách thức làm việc của các hàm trên Arduino IDE.
Nếu bạn là một người mới chưa biết Arduino là cái quái gì? Và cần học Arduino để làm gì?
Thì xem 2 bài viết bên dưới nhé.
- Xem bài viết: Arduino IDE là gì?
- Xem bài viết: Arduino Uno là gì?
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.
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.
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:
- HIGH signal sent to pin 8
- Wait for 1000 ms
- HIGH signal sent to pin 13
- Wait for 1000 ms
- LOW signal sent to pin 8
- Wait for 1000 ms
- LOW signal sent to pin 13
- Wait for 1000 ms
- 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:
- HIGH signal sent to pin 8
- HIGH signal sent to pin 13
- Wait for 1000 ms
- LOW signal sent to pin 8
- LOW signal sent to pin 13
- Wait for 1000 ms
- 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…
Lesson 1: Turning on an LED
Keywords searched by users: arduino led on off code
Categories: Tóm tắt 12 Arduino Led On Off Code
See more here: kientrucannam.vn
See more: https://kientrucannam.vn/vn/