Chuyển tới nội dung
Home » Arduino Uno Code For Led | Arduino – Blinking Led

Arduino Uno Code For Led | Arduino – Blinking Led

Arduino Blinking LED Tutorial

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.

PWM functionality with Arduino LED

As for now, you’ve seen that you can control an LED with 2 states: HIGH (fully on with 5V), or LOW (fully off with 0V). What if you want to control the brightness of the LED, for example to 40% of the max brightness?

That’s where the PWM functionality is useful.

Very basically put, a PWM will allow you to output a voltage which is a percentage of the max voltage. So, if you want 40% brightness, you’d have to provide 40% of the voltage, which is 40% * 5V = 2V. Even if that sounds complicated, you will see that it’s super easy to do in the code.

What pins are compatible with PWM?

Not all pins are compatible with PWM functionality. Only the pins with a “~” next to the number are compatible. On Arduino Uno, you have pins 3, 5, 6, 9, 10 and 11.

As our LED is currently connected to digital pin 12, which doesn’t support PWM, we will need to modify the circuit.

First, power off the Arduino, and then simply change the wire from pin 12 to pin 11 (or any other compatible pin).

Power on the LED with analogWrite()

Let’s write the code to power on the LED, but with just 40% of the max voltage.

#define LED_PIN 11 void setup() { pinMode(LED_PIN, OUTPUT); analogWrite(LED_PIN, 102); } void loop() {}

First, we update the define line with the pin number 11 instead of 12. As you can see this is very practical, as we don’t have to change the number anywhere else in the code.

Then, instead of using digitalWrite(), we use analogWrite() with 2 parameters:

  • Digital pin, here LED_PIN as previously defined.
  • Percentage of the voltage, scaled to 0-255 (one byte of data). If we want 40% we need to do 255 * 0.4 = 102. This will correspond to an output of 5V * 0.4 = 2V.

You can use any value between 0 and 255 to try different intensities for the LED.

Note: even if you are connected to a PWM compatible pin and using analogWrite(), you can still use digitalWrite() any time you want. Also:

  • using analogWrite(LED_PIN, 0) is the same as digitalWrite(LED_PIN, LOW),
  • and analogWrite(LED_PIN, 255) is the same as digitalWrite(LED_PIN, HIGH).

Important note: do not be confused between PWM pins and analog pins. Basically you can use:

  • digitalWrite() with any digital pin and any analog pin (to fully power on/off an LED).
  • analogWrite() with only digital pins which have a “~” next to the number (to change the brightness of an LED for example).

This can be confusing because you can use analogWrite() for certain digital pins, but on the other hand, you can’t use the analogWrite() on analog pins. There is no real sense to make here, this is just how it has been defined. The “analogWrite()” function could have been named “pwm()” or something similar, but now it’s probably too late to change this kind of convention.

Make the LED fade in/fade out

Let’s try something more interesting with PWM. Here we want to make the LED fade in (which means the brightness will slowly increase until the max), and then fade out (brightness will slowly decrease), so we can create a nice effect with the LED.

#define LED_PIN 11 void setup() { pinMode(LED_PIN, OUTPUT); } void loop() { for (int i = 0; i <= 255; i++) { analogWrite(LED_PIN, i); delay(10); } for (int i = 255; i >= 0; i–) { analogWrite(LED_PIN, i); delay(10); } }

Let’s analyze this code.

#define LED_PIN 11 void setup() { pinMode(LED_PIN, OUTPUT); }

Nothing new here, we define the pin for the LED, and then initialize the mode to OUTPUT. We don’t do anything else in the void setup().

void loop() { for (int i = 0; i <= 255; i++) { analogWrite(LED_PIN, i); delay(10); }

The void loop() is separated in 2. Here we make the LED “fade in”, which means that we apply all values from 0 to 255 to the pin, with analogWrite(). Between each update we add a small delay of 10 milliseconds, so we have the time to see what’s happening.

Once we reach 255, the for loop ends.

for (int i = 255; i >= 0; i–) { analogWrite(LED_PIN, i); delay(10); } }

Now, we do the same thing but on the way back to 0. This for loop will start at 255 and each time will decrease the index. We make the LED “fade out”, also with a small delay.

Once the for loop ends, the brightness of the LED is 0 (LED powered off), and the void loop() starts again to “fade in”.

Arduino Blinking LED Tutorial
Arduino Blinking LED Tutorial

What is LED?

LEDs (Light Emitting Diodes) are becoming increasingly popular among a wide range of people. When a voltage is given to a PN Junction Diode, electrons, and holes recombine in the PN Junction and release energy in the form of light (Photons). An LED’s electrical sign is comparable to that of a PN Junction Diode. When free electrons in the conduction band recombine with holes in the valence band in forward bias, energy is released in the form of light.

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.
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 |

C++


int


LEDpin = 13;


int


delayT = 1000;


void


setup() {


pinMode(LEDpin, OUTPUT);


void


loop() {


digitalWrite(LEDpin, HIGH);


delay(delayT);


digitalWrite(LEDpin, LOW);


delay(delayT);

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.

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

Sơ đồ Lắp Đặt :

Mã code

// the setup function runs once when you press reset or power the board

// the loop function runs over and over again forever

Tải file IDE : Điều Khiển Led Đơn

Bạn đang xem: Lập Trình Arduino Uno R3 Điều Khiển Led Đơn

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.

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ì?
BELAJAR CODING ARDUINO DARI DASAR (MEMPROGRAM LED) PART 1
BELAJAR CODING ARDUINO DARI DASAR (MEMPROGRAM LED) PART 1

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.

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 }

Getting Started with Arduino: The LED Blink Tutorial
Getting Started with Arduino: The LED Blink Tutorial

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.

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).
How to Blink an LED with Arduino (Lesson #2)
How to Blink an LED with Arduino (Lesson #2)

Working with multiple LEDs

For now I’ve made examples with just one LED. What if you want to use several LEDs on your Arduino circuit?

Arduino Circuit with 3 LEDs

Let’s create a circuit with 3 LEDs.

As you can see, once you know how to connect 1 LED in your Arduino circuit, adding more LEDs is not that hard. You just have to follow the same recipe:

  • Connect the shorter leg to the common ground (GND).
  • Connect the longer leg to a digital pin of the Arduino, with a 220 Ohm resistor in between.

Also, instead of directly connecting each shorter leg to a different GND pin, here we use the breadboard in a smart way. We connect all shorter legs to the “minus” line (or the blue line in some boards), and from there, we just plug one wire between this line and a GND pin of the Arduino.

Arduino code for 3 LEDs

Let’s make a very simple application: we want first the red LED to be powered on, then the yellow one, then the green one, and back to the red one.

#define LED_PIN_1 11 #define LED_PIN_2 10 #define LED_PIN_3 9 void setup() { pinMode(LED_PIN_1, OUTPUT); pinMode(LED_PIN_2, OUTPUT); pinMode(LED_PIN_3, OUTPUT); } void loop() { digitalWrite(LED_PIN_1, HIGH); digitalWrite(LED_PIN_2, LOW); digitalWrite(LED_PIN_3, LOW); delay(1000); digitalWrite(LED_PIN_1, LOW); digitalWrite(LED_PIN_2, HIGH); digitalWrite(LED_PIN_3, LOW); delay(1000); digitalWrite(LED_PIN_1, LOW); digitalWrite(LED_PIN_2, LOW); digitalWrite(LED_PIN_3, HIGH); delay(1000); }

Nothing really complicated: for the setup we just duplicate the code for each new LED. We add a define and we setup the mode with pinMode().

Then, well you can use digitalWrite() on each LED – and analogWrite() if the pin is PWM compatible – whenever you want. In this case we just power on each LED, once at a time, with a 1 second delay.

Circuit Diagram

In the circuit diagram, we used one 330-ohm resistor in series with the LED. This resistor is also called a current-limiting resistor. The Anode of the LED (the longer pin) is connected to one end of the resistor, and the cathode (the shorter pin) is connected to the ground. The other end of the resistor is connected to the Arduino pin. A step-by-step explanation is as follows:

  1. LED Connections: Connect the LED to the breadboard. The LED has two legs, the longer of which is the anode (positive) and the shorter of which is the cathode (negative).
  2. Resistor Connection: Insert one end of the resistor into the same row of the breadboard as the LED’s Anode. The resistor’s other end should be connected to the Arduino’s digital output pin.
  3. Ground (GND) Connection: Connect a jumper wire from the same row as the LED’s cathode to any Arduino board GND (Ground) pin. This connects the circuit to the ground of the Arduino.

The circuit is now complete. Here’s how it works:

When you upload a simple Arduino program that controls the LED, the microcontroller on the Arduino board executes the program, and the LED will blink according to the code you wrote.

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

Structure of an LED

Structure of LED

The flow of charge carriers (electrons and holes) across the P-N junction drives the activity of an LED. When a forward voltage (anode positive in comparison to the cathode) is applied, electrons and holes recombine at the junction, releasing energy in the form of photons (light). The semiconductor chip is linked to external terminals known as the anode (+) and the cathode (-). The anode is linked to the P-region, and the cathode to the N-region.

Going further with Arduino and LEDs

In this Arduino LED tutorial you’ve seen how to create a circuit with a LED, and how to write code to control it. As you’ve seen, even if we keep the examples at a basic level, there are quite a few things you can do with LEDs.

The amount of applications where you will use LEDs is endless. LEDs can be used to display some information (ex: green LED for a traffic light), to warn the user (ex: red LED as a warning that a robot is close from a collision), to add some light for a camera, or even just for nice looking purpose.

Now, to go further with LEDs, here are a few interesting resources which will expand your knowledge on the programming side, but also if you decide to add more components into your circuit and make it more complete:

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.

We will interface an LED (light-emitting diode) to the Arduino UNO board. An LED is a simple diode that emits light in a forward bias. We will write an LED-blinking program on the Arduino IDE and download it to the microcontroller board. The program simply turns ON and OFF LED with some delay between them.

How to control LED Strips with Arduino - Cosplay Tutorial
How to control LED Strips with Arduino – Cosplay Tutorial

Working procedure

setup() and loop() are two fundamental Arduino functions for controlling the behavior of your board. The Arduino framework automatically calls these functions, which form the foundation of any Arduino program.

The setup() function is only called once when the Arduino board boots up or is reset. Its goal is to set pin modes, initialize variables, and execute any other necessary setup tasks before the main loop begins. This function can be used to configure settings that should only be changed once over the board’s lifespan.

The

loop()

function is the heart of an Arduino program. After the

setup()

function is executed, the

loop()

function starts running repeatedly until the Arduino is powered off or reset. It contains the main code that performs the desired tasks, controls the board, user input. Whatever is included in the

loop()

function will be executed in a continuous loop, allowing the Arduino to perform its intended functions continuously.

In the code, we have declared two integers, LEDpin and delayT. LEDpin represents the pin number of the Arduino where LEDs need to be connected, and delayT is an integer variable for the delay() function. The delay() function accepts values in milliseconds.

Conclusion

The Arduino LED blinking project provides a hands-on introduction to microcontrollers, hardware interfaces, and programming ideas. It serves as a foundation for more sophisticated projects and allows you to experiment with numerous Arduino features and capabilities. Whether you’re new to electronics or an expert maker, this project will help you develop crucial skills and knowledge for future Arduino-based projects.

DIY Propeller LED Clock with Arduino || LED Clock POV Display
DIY Propeller LED Clock with Arduino || LED Clock POV Display

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.

C++


int


LEDpin = 13;


int


delayT = 1000;


void


setup() {


pinMode(LEDpin, OUTPUT);


void


loop() {


digitalWrite(LEDpin, HIGH);


delay(delayT);


digitalWrite(LEDpin, LOW);


delay(delayT);

Arduino sequential LED project | led chaser circuit | arduino project |
Arduino sequential LED project | led chaser circuit | arduino project |

Applications and Uses of LED Blinking

The LED blinking project is an important and straightforward method that can be utilized for a wide range of applications in microcontroller-based projects like :

  • Security Systems: To check the status of security systems
  • Warning Signals: In battery-operated devices, LED blinking can be used to indicate low battery levels.
  • In Testing and debugging.
  • Status Indication: LEDs can be used to indicate different states of a system. For example, in a home automation project, an LED might blink to indicate whether a device is connected to an internet network or not.

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.

How to make a 16x16x16 LED CUBE at home with Arduino platform
How to make a 16x16x16 LED CUBE at home with Arduino platform

Conclusion:

Interfacing LED with Arduino is a fundamental step towards understanding the basics of hardware programming. By understanding the concepts of LED, its pinout, connection with Arduino, and the code involved, you can create amazing projects that light up your world. With this guide, you can confidently take on the challenge of interfacing LED with Arduino and start experimenting with more complex hardware projects. So grab your Arduino and LED, and let your creativity shine!

If you appreciate our work don’t forget to share this post and leave your opinion in the comment box.

Please do check out other blog posts about Interfacing ACS712 with Arduino , Arduino Interfacing with Ultrasonic Sensor , Interfacing GSM Module with Arduino , Interfacing MAX30100 Pulse Oximeter with Arduino , IR Sensor Interfacing with Arduino , How to connect ZMPT101B to Arduino and How to use Buzzer with Arduino.

Make sure you check out our wide range of products and collections (we offer some exciting deals!)

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

Create the Arduino LED circuit

For this circuit we will need:

  • Arduino board.
  • LED (any color, I will use red).
  • Breadboard.
  • 220 Ohm resistor (more info on the value later on).
  • Some male to female wires.

Build the circuit

Here is the circuit.

How to build the circuit:

  • First make sure that the Arduino is powered off (no USB cable plugged to anything).
  • Check the LED, you will see that one of the leg is shorter than the other one.
  • Plug the shorter leg of the LED to a hole on the breadboard. Connect that leg to a GND pin of the Arduino, using a black cable if possible (convention for GND).
  • Plug the longer leg of the LED to a different hole, on a different and independent line of the breadboard.
  • Add a 220 Ohm resistor between this longer leg and a digital pin of the Arduino, using an additional colored wire (no red, no black) for convenience.

Here we choose digital pin 12 on the Arduino Uno.

Note: you could have chosen any of the digital pins ranging from 0-13, and also any of the analog pins, which you can use as digital pins. So, for the Arduino Uno, you get 20 possibilities. More info on Arduino Uno pins.

Why a 220 Ohm resistor for the LED?

This tutorial (and website) is more focused on software but I’ll make a quick parenthesis here to give you basic and simplified hardware explanation.

Basically, you want to limit the current that goes through the LED, so you will avoid damaging it and also damaging the pin on the Arduino board. The max value can depend, but let’s agree on 20mA max, which is 0.02A.

With the Ohm’s law, you get the relation between resistance, voltage, and current:

Voltage = Resistance * Current.

If you modify the order you get: Resistance = Voltage / Current.

So, if you want a max current of 0.02A, for a 5V voltage, you would need a 5V/0.02A = 250 Ohm resistor.

The thing is that, for LEDs, there is something more to take into account. This is the voltage drop of the LED. This voltage drop is going to be different for different colors, but let’s approximate it to 2V. So, the computation for the resistor becomes (5V – 2V)/0.02A = 150 Ohm.

With those values, you’d need a resistor which is at least 150 Ohm, so you can make sure the current stays under 20mA. The thing is that, finding a 150 Ohm resistor is not that common. 220 Ohm is more common, and it’s a higher value, so no problem. In fact, you could also use a 330 Ohm resistor and it will work, just with a slightly lower brightness, because the current will be lower. You could go as high as 1kOhm, for example if you want to add many LEDs, in order to reduce the overall current usage.

One thing to understand here: there’s no point in getting an exact resistor value. Any approximation that is above the minimum “safety” computation is fine.

OK, now that this is done, let’s go back to software.

How To Setup A ws2812b RGB LEDs With Arduino Nano
How To Setup A ws2812b RGB LEDs With Arduino Nano

Arduino code to power on an LED

Power on the LED with digitalWrite()

Let’s start with the most simple thing. Let’s say you just want to power on the LED when the Arduino program starts. This code will help us understand the setup and how digital pins work.

#define LED_PIN 12 void setup() { pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, HIGH); } void loop() {}

This code is very short and will just power on the LED on pin 12. Let’s analyze it.

#define LED_PIN 12

First, and this is a best practice, we create a define for the pin number. This way, anytime we need to use this digital pin, we can write LED_PIN instead of the hard-coded number. In the future, if you ever need to use a different digital pin (for example 11), then you just need to change the number here and it will update it everywhere in your program.

void setup() { pinMode(LED_PIN, OUTPUT);

We enter the void setup() function, which will be executed once at the beginning of the program.

Before we can actually use a digital pin, we need to set a mode. Basically you have 2 modes: output (if you want to control a component), or input (if you want to read some information from a component). Here, we want to control the LED, so we choose output. For that, we use the pinMode() function with 2 parameters:

  • Pin number: here we use the LED_PIN that we previously defined.
  • Mode: for output mode, we have to use OUTPUT (all uppercase).

After the execution of this line, the digital pin 12 will be set as output, and we can control the LED.

digitalWrite(LED_PIN, HIGH); }

Now, to control the LED, it’s very simple. We need to use the digitalWrite() function with 2 parameters:

  • Pin number: again, we use the defined LED_PIN.
  • State: we have 2 choices here. HIGH to power on the LED, and LOW to power it off.

So, after this line, the LED will be powered on.

Note: it’s important to call pinMode() before digitalWrite(), otherwise the LED won’t be powered on because the mode is not set.

void loop() {}

After the void setup() function is finished, we enter the void loop() and this function will be executed again and again, until you power off the Arduino.

Here we didn’t write anything in the void loop() because we just want to power on the LED and that’s it.

Test using only the built-in Arduino LED

If you don’t want to build the circuit, or want to test with something even simpler, you can use the built-in LED on the Arduino, which is soldered on digital pin 13.

You can use LED_BUILTIN which is already predefined for this LED.

void setup() { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); } void loop() {}

And you’ll see the built-in LED powered on. Note: the location of the LED can vary depending on the type of your Arduino board.

Make the blink LED example

Now that you have the circuit and the code to setup the LED, let’s do something a bit more interesting.

Let’s make the LED blink, which means that we are going to:

  1. Power on the LED,
  2. wait,
  3. Power off the LED,
  4. wait,
  5. Go back to 1.

Here’s the code to do that (using our LED connected to digital pin 12).

#define LED_PIN 12 void setup() { pinMode(LED_PIN, OUTPUT); } void loop() { digitalWrite(LED_PIN, HIGH); delay(500); digitalWrite(LED_PIN, LOW); delay(500); }

Let’s break down this code line by line.

#define LED_PIN 12

This is the same as before. We create a define so we can use the pin number later on in the code without having to hard-coding it.

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

In the void setup(), we initialize the mode for the pin to OUTPUT. Note that this is the only thing we do here.

void loop() { digitalWrite(LED_PIN, HIGH); delay(500); digitalWrite(LED_PIN, LOW); delay(500); }

And in the void loop(), we handle the blink mechanism. First we power on the LED with digitalWrite() and HIGH, then we wait using delay(). The delay() function will block the program for a given amount of time (in milliseconds). So, here, we block the program for 500 milliseconds, or 0.5 second.

After that, we power off the LED with digitalWrite() and LOW, and wait again for 0.5 seconds using delay(). This way, we have a complete cycle of “LED powered on” + “LED powered off”.

Once we exit the void loop(), it is called again, and thus the LED is powered on again, etc etc.

This blink example is maybe one of the most common example, but also super useful when you get started with Arduino. If you correctly understand the circuit and the code, you’ve already made big progress.

Conclusion

The Arduino LED blinking project provides a hands-on introduction to microcontrollers, hardware interfaces, and programming ideas. It serves as a foundation for more sophisticated projects and allows you to experiment with numerous Arduino features and capabilities. Whether you’re new to electronics or an expert maker, this project will help you develop crucial skills and knowledge for future Arduino-based projects.

How to make a 8x8x8 LED Cube at Home
How to make a 8x8x8 LED Cube at Home

Working procedure

setup() and loop() are two fundamental Arduino functions for controlling the behavior of your board. The Arduino framework automatically calls these functions, which form the foundation of any Arduino program.

The setup() function is only called once when the Arduino board boots up or is reset. Its goal is to set pin modes, initialize variables, and execute any other necessary setup tasks before the main loop begins. This function can be used to configure settings that should only be changed once over the board’s lifespan.

The

loop()

function is the heart of an Arduino program. After the

setup()

function is executed, the

loop()

function starts running repeatedly until the Arduino is powered off or reset. It contains the main code that performs the desired tasks, controls the board, user input. Whatever is included in the

loop()

function will be executed in a continuous loop, allowing the Arduino to perform its intended functions continuously.

In the code, we have declared two integers, LEDpin and delayT. LEDpin represents the pin number of the Arduino where LEDs need to be connected, and delayT is an integer variable for the delay() function. The delay() function accepts values in milliseconds.

Components Description

  1. 1 X LED: We are controlling only one LED in this program.
  2. 1 X Resistor, 330 Ohm: For every LED, we need one current limiting resistor.
  3. Breadboard: A breadboard is a fundamental tool used in electronics and prototyping to build and test circuits without soldering.
  4. Arduino UNO R4 or earlier versions.
  5. Jumper wires: Jumper wires are simple electrical wires with connectors on both ends used to create connections between various electronic components or points on a circuit on a breadboard.
LED chaser with 32 effects |led patterns with Arduino | Code in Discription
LED chaser with 32 effects |led patterns with Arduino | Code in Discription

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…

In this blog, we will see how to interface an LED with Arduino.

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.
100 Addressable LED Lights Arduino Build (Quick)
100 Addressable LED Lights Arduino Build (Quick)

FAQs on LED Blinking using Arduino

What is the need for interfacing LEDs with Arduino?

Interfacing LED is an important and straightforward method that can be utilized for a wide range of applications in Embedded System projects like security system, home automation etc.

What is the best way to connect an LED to a microcontroller?

A current-limiting resistor and two wires are required to connect an LED to a microcontroller. Connect longer one leg of the LED to the to the current-limiting resistor and the shorter leg to the ground. Then, connect the resistor’s other end to the microcontroller’s I/O pin.

How can I program the Arduino to blink the LED in different patterns?

You can change the loop() method in the Arduino code to make the LED blink in different patterns. For example, you can use conditional expressions (if-else) to design more sophisticated blinking patterns, or you can use numerous digitalWrite() and delay() statements to create unique on-off sequences.

In Arduino programming, how do I regulate the frequency of LED blinking?

The delay() method in the Arduino code controls the blinking frequency (the pace at which the LED turns on and off). The delay() option indicates the time in milliseconds between each on-off cycle. For example, delay(1000); will cause the LED to stay on for one second and then turn off for one second.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Last Updated :
18 Aug, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

In this complete tutorial you will learn how to use an LED with Arduino. First, you will setup your circuit with an Arduino board and an LED, and then discover different ways to control the LED.

I will use Arduino Uno for the examples but the instructions here apply to any Arduino board.

If you want to just try the LED code on your Arduino, without doing the circuit, well, good news! You can just use the internal LED on pin 13 if you want (more about that in the following).

>> Watch this video as an additional resource (covers about half of the written article):

After watching the video, subscribe to the Robotics Back-End Youtube channel so you don’t miss the next tutorials!

You are learning how to use Arduino to build your own projects?

Check out Arduino For Beginners and learn step by step.

And now let’s get started!

Table of Contents

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:

Arduino 74hc595 16 led with 18 effects | arduino led projects
Arduino 74hc595 16 led with 18 effects | arduino led projects

Connection of LED with Arduino:

GPIO 3 of Arduino

Anode pin of LED via 220ohm resistor

GND pin of Arduino

Cathode pin of the LED

Make the connections as per the circuit diagram shown in the above image. Next, we have to program our Arduino. For programming our Arduino to blink an LED, we need Arduino IDE to be installed on our PC. You can download and install Arduino IDE suitable for your computer OS from arduino.cc

Once, the Arduino IDE is installed on your PC, we have to write a code to blink an LED in the interval of one second. Below is the code for blinking LED using Arduino.

read more : Arduino Pin Configuration

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.

How to change LED Patterns using one button-11-LED!! 16-Pattern.LED-Arduino Project!!!
How to change LED Patterns using one button-11-LED!! 16-Pattern.LED-Arduino Project!!!

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 }

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.

RGB LEDs with Arduino - Standard & NeoPixel
RGB LEDs with Arduino – Standard & NeoPixel

FAQs on LED Blinking using Arduino

What is the need for interfacing LEDs with Arduino?

Interfacing LED is an important and straightforward method that can be utilized for a wide range of applications in Embedded System projects like security system, home automation etc.

What is the best way to connect an LED to a microcontroller?

A current-limiting resistor and two wires are required to connect an LED to a microcontroller. Connect longer one leg of the LED to the to the current-limiting resistor and the shorter leg to the ground. Then, connect the resistor’s other end to the microcontroller’s I/O pin.

How can I program the Arduino to blink the LED in different patterns?

You can change the loop() method in the Arduino code to make the LED blink in different patterns. For example, you can use conditional expressions (if-else) to design more sophisticated blinking patterns, or you can use numerous digitalWrite() and delay() statements to create unique on-off sequences.

In Arduino programming, how do I regulate the frequency of LED blinking?

The delay() method in the Arduino code controls the blinking frequency (the pace at which the LED turns on and off). The delay() option indicates the time in milliseconds between each on-off cycle. For example, delay(1000); will cause the LED to stay on for one second and then turn off for one second.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Last Updated :
18 Aug, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

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.

Structure of an LED

Structure of LED

The flow of charge carriers (electrons and holes) across the P-N junction drives the activity of an LED. When a forward voltage (anode positive in comparison to the cathode) is applied, electrons and holes recombine at the junction, releasing energy in the form of photons (light). The semiconductor chip is linked to external terminals known as the anode (+) and the cathode (-). The anode is linked to the P-region, and the cathode to the N-region.

Arduino Uno R4 Wifi LESSON 4: Building Clean and Neat Circuits on a Breadboard
Arduino Uno R4 Wifi LESSON 4: Building Clean and Neat Circuits on a Breadboard

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.

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.

We will interface an LED (light-emitting diode) to the Arduino UNO board. An LED is a simple diode that emits light in a forward bias. We will write an LED-blinking program on the Arduino IDE and download it to the microcontroller board. The program simply turns ON and OFF LED with some delay between them.

NO CODING Animated LEDs - Ultimate Beginner’s Guide - Cosplay and Props
NO CODING Animated LEDs – Ultimate Beginner’s Guide – Cosplay and Props

Explanation:

#define led_pin 3

#define led_pin 3 : First, we have declared a pin name and pin number to which we are going to connect the LED using #define preprocessor constant. We are assigning GPIO 3 pin of Arduino to connect LED and given a name to that pin as “led_pin”.

void setup()

pinMode(led_pin, OUTPUT);

void setup() : This function executes only once in our program. In this function, we have called a function called “pinMode(led_pin, OUTPUT);”. The pinMode function is used to tell Arduino, that the connected peripheral is either input or output peripheral. In this function, we are passing the “led_pin” as pin name and “OUTPUT” as type.

void loop()

digitalWrite(led_pin, HIGH);

delay(1000);

digitalWrite(led_pin, LOW);

delay(1000);

void loop() : This function executes infinitely in our program. In this function, we have called a function “digitalWrite();” in this function, we pass two arguments. Such as the pin name to which the LED is connected and the state of the pin. “digitalWrite(led_pin, HIGH);” makes the led_pin as HIGH means provides 5V at GPIO pin 3. “digitalWrite(led_pin, LOW);” makes the voltage on the GPIO pin 3 to 0V. In between these two functions, we have used a “delay();” function is used to pause the microcontroller for some period of time during the execution. In this program, we are passing “1000” as an argument to the delay(); function. Which gives a delay of 1000 milliseconds. i.e., 1 second.

read more : Exploring LCD Displays and Arduino UNO

Circuit Diagram

In the circuit diagram, we used one 330-ohm resistor in series with the LED. This resistor is also called a current-limiting resistor. The Anode of the LED (the longer pin) is connected to one end of the resistor, and the cathode (the shorter pin) is connected to the ground. The other end of the resistor is connected to the Arduino pin. A step-by-step explanation is as follows:

  1. LED Connections: Connect the LED to the breadboard. The LED has two legs, the longer of which is the anode (positive) and the shorter of which is the cathode (negative).
  2. Resistor Connection: Insert one end of the resistor into the same row of the breadboard as the LED’s Anode. The resistor’s other end should be connected to the Arduino’s digital output pin.
  3. Ground (GND) Connection: Connect a jumper wire from the same row as the LED’s cathode to any Arduino board GND (Ground) pin. This connects the circuit to the ground of the Arduino.

The circuit is now complete. Here’s how it works:

When you upload a simple Arduino program that controls the LED, the microcontroller on the Arduino board executes the program, and the LED will blink according to the code you wrote.

LEDs & Breadboards With Arduino in Tinkercad
LEDs & Breadboards With Arduino in Tinkercad

Components Description

  1. 1 X LED: We are controlling only one LED in this program.
  2. 1 X Resistor, 330 Ohm: For every LED, we need one current limiting resistor.
  3. Breadboard: A breadboard is a fundamental tool used in electronics and prototyping to build and test circuits without soldering.
  4. Arduino UNO R4 or earlier versions.
  5. Jumper wires: Jumper wires are simple electrical wires with connectors on both ends used to create connections between various electronic components or points on a circuit on a breadboard.

What is LED?

LEDs (Light Emitting Diodes) are becoming increasingly popular among a wide range of people. When a voltage is given to a PN Junction Diode, electrons, and holes recombine in the PN Junction and release energy in the form of light (Photons). An LED’s electrical sign is comparable to that of a PN Junction Diode. When free electrons in the conduction band recombine with holes in the valence band in forward bias, energy is released in the form of light.

Blink an LED With Arduino in Tinkercad
Blink an LED With Arduino in Tinkercad

Applications and Uses of LED Blinking

The LED blinking project is an important and straightforward method that can be utilized for a wide range of applications in microcontroller-based projects like :

  • Security Systems: To check the status of security systems
  • Warning Signals: In battery-operated devices, LED blinking can be used to indicate low battery levels.
  • In Testing and debugging.
  • Status Indication: LEDs can be used to indicate different states of a system. For example, in a home automation project, an LED might blink to indicate whether a device is connected to an internet network or not.

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.

4×4×4 LED Cube Light Using Arduino nano | Electronic Project
4×4×4 LED Cube Light Using Arduino nano | Electronic Project

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

Keywords searched by users: arduino uno code for led

Categories: Phát hiện thấy 61 Arduino Uno Code For Led

3- Blinking An Led With Arduino | Arduino For Beginners Tutorial - Youtube
3- Blinking An Led With Arduino | Arduino For Beginners Tutorial – Youtube
9 Led Patterns With Arduino - Hackster.Io
9 Led Patterns With Arduino – Hackster.Io
Led Blinking With Arduino Uno R3 : 6 Steps - Instructables
Led Blinking With Arduino Uno R3 : 6 Steps – Instructables
Blinking An Led - Javatpoint
Blinking An Led – Javatpoint
Led Blinking Using Arduino (4 Examples) With Code, Circuit And Video
Led Blinking Using Arduino (4 Examples) With Code, Circuit And Video
Blink An Led With Digital Output : 6 Steps - Instructables
Blink An Led With Digital Output : 6 Steps – Instructables
Blinking Two Led - Javatpoint
Blinking Two Led – Javatpoint
Tutorial 1 - Blinking The Arduino Builtin Led
Tutorial 1 – Blinking The Arduino Builtin Led
Arduino : Blink Two Leds Alternatively
Arduino : Blink Two Leds Alternatively
Turn Led On And Off With Button Arduino Code - Arduino Circuit
Turn Led On And Off With Button Arduino Code – Arduino Circuit
Controlling 2 Leds With 1 Pushbutton(Beginner) - Programming Questions -  Arduino Forum
Controlling 2 Leds With 1 Pushbutton(Beginner) – Programming Questions – Arduino Forum
Multiple Blinking Led On The Arduino : 4 Steps - Instructables
Multiple Blinking Led On The Arduino : 4 Steps – Instructables

See more here: kientrucannam.vn

See more: https://kientrucannam.vn/vn/

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *