Last Updated: January 16, 2023
Originally Published: May 24, 2018
Skill Level: Beginner
Table Of Contents
- Introduction
- What Is Needed
- Background Information
- Building The Circuit
- Installing The Arduino IDE
- Writing The Sketch
- A Better Blink
- Summary
Introduction
This tutorial will teach you how to connect and control an LED with an Arduino Uno development board.
We will cover the following topics:
- How to construct an LED circuit on a breadboard and attach it to an Arduino board.
- How to write a Sketch program in the Arduino IDE.
- How to compile and upload a sketch to run on the Arduino board.
- How to build a more robust blinking sketch.
A basic understanding of electronics and programming is expected, but not required.
Fully commented versions of all source code used in this tutorial are available on GitHub for your reference.
What Is Needed
- Linux, macOS, Or Windows Based Computer With A USB Port
- Arduino IDE
- Arduino Uno (available on Arduino and SparkFun) With Compatible USB Cable
- Solderless Breadboard (available on Adafruit and SparkFun)
- 2 x Male-Male Jumper Wires (available on Adafruit and Arrow)
- Standard 5mm Red LED (available on Adafruit and SparkFun)
- 330 Ω Resistor (available on SparkFun and Amazon)
Background Information
A light emitting diode (LED) is a semiconductor device that emits light when energized and comes in an assortment of different colors. It is similar to a light bulb, but is much smaller and consumes much less power. LEDs are typically used as indicator lights in consumer electronics.
A solderless breadboard will be used to assemble the electronic circuit. These breadboards allow engineers and hobbyists to construct circuits without having to permanently (for the most part) attach your electronic components or have to deal with soldering them together. If you are not familiar with solderless breadboards, the Core Electronics’ How to Use Breadboards and Science Buddies’ How to Use a Breadboard guides are good resources for learning how to use one.
Although the Arduino platform has many Arduino development boards of different sizes and purposes available, we will be using the Arduino Uno that is by far the most popular Arduino board in use today. My board is an Arduino Uno WiFi Rev2. If you are using a different model, the vast majority of this tutorial should still apply, however, some minor changes may be necessary.
The Arduino IDE (Integrated Development Environment) is the application used to develop and upload programs to an Arduino development board. The programming language used by the IDE is Sketch which is based on C++ and allows for the use of standard C and C++ libraries. A file containing a Sketch program is called a sketch and has a .ino extension. It is my understanding the Arduino IDE works the same across all platforms, however, I am using the Arduino Desktop IDE on macOS for this tutorial so you may see some slight differences.
The Arduino website is a great resource for hobbyists looking to purchase and experiment with Arduino development boards. The Arduino Documentation site is a great place to start if you are new to the Arduino platform. They also provide tutorials, a Sketch language reference, and many more resources. I urge you to check it out if you haven’t already.
If you need assistance with your particular setup, post a question in the comments section below and I, or someone else, can try to help you.
Building The Circuit
Before connecting any circuitry to your Arduino board, disconnect it from power and your computer. This avoids accidental damage during wiring.
Attach the red LED to the solderless breadboard by connecting one end of the LED to one of the breadboard’s terminal strips and the other end to an adjacent terminal strip. The terminal strips are the horizontal rows of terminals grouped together in sets of 5 in the center of the board. The anode (positive terminal) of an LED is longer than the cathode (negative terminal). Connect one end of the 330 Ω resistor to the terminal strip containing the LED’s anode and the other end of the resistor to an empty adjacent terminal strip.
Next, we will connect the LED and resistor circuit to the Arduino Uno board. Attach one end of a jumper wire to the breadboard’s terminal strip containing the open end of the resistor. Attach the other end of the jumper wire to pin D2 on the Arduino Uno DIGITAL pins header. This is the 3rd pin up from the bottom.
Attach another jumper wire from the terminal strip containing the open end (cathode) of the LED on the breadboard to the ground (GND) pin located just above D13 on the Arduino Uno DIGITAL pins header. Once completed, your circuit should look like the one shown below.
The circuit is complete so you can now connect the Arduino Uno to your computer via the USB cable.
Installing The Arduino IDE
If you have not done so already, install and configure the Arduino IDE for your particular operating system according to the instructions in the installation and getting started guides on Arduino’s website.
Once installed, you need to let the IDE know which development board you are using. This is accomplished by selecting your board and serial port from the automatic board selector located within the toolbar at the top of the sketch window. Alternatively, you can also select your board (Tools > Board) and port (Tools > Port) from the main menu as well.
Board specific getting started guides are available by entering the name of your board into the Set Up Your Arduino Board section of the Arduino Documentation site.
Writing The Sketch
Once the Arduino IDE is configured, select File > Examples > 01.Basics > Blink from the main menu to open the example sketch we will use in this project. This example sketch already contains the software to blink an LED, albeit one already built onto the board. We will modify the code to use our LED circuit later.
Peruse the code and look at the various functions defined and used. The setup()
function runs only once and is where we place all initialization code, like setting the mode for the pin connected to the LED as an output in this example.
The loop()
function runs repeatedly over and over after the setup()
function has been completed. This is where we put code that is always in action. In this case, the loop()
function repeatedly turns on and off the built-in LED with 1 second delays in between. The digitalWrite()
function sets the pin state to either a HIGH
or LOW
logic level. The delay()
function pauses the program for a specific amount of time. Its argument is 1000
in this case because the function is expecting milliseconds.
Let’s run the example sketch without modification and watch it in action. To upload and run the sketch on the Arduino board, select Sketch > Upload from the main menu. An Output panel will appear just below the code area that will include pop-up messages stating Compiling sketch…, Done compiling., Uploading…, and Done uploading. that will disappear after a couple of seconds. Once the sketch has been uploaded to the Arduino development board, it will begin running automatically on the board. You should now see the built-in LED blinking.
You can also accomplish this task by clicking on the right arrow button (Upload) located on the left-hand side of the toolbar at the top of the Blink sketch window. This toolbar provides a convenient way to run commands without always having to go through the main menu.
Next, let’s change the code to use our LED circuit instead of the built-in LED. Change line 28 of the example Blink sketch that sets the specified Arduino pin to be an output from
pinMode(LED_BUILTIN, OUTPUT);
to
pinMode(2, OUTPUT);
where pin 2
refers to pin D2 we used previously to connect our LED circuit to the Arduino Uno DIGITAL header. Now let’s change line 33 from
digitalWrite(LED_BUILTIN, HIGH);
to
digitalWrite(2, HIGH);
and line 35 from
digitalWrite(LED_BUILTIN, LOW);
to
digitalWrite(2, LOW);
for turning on and off the LED respectively.
Next, let’s verify and save our updated sketch program. To verify the code compiles correctly, select Sketch > Verify/Compile from the main menu or click the check mark button (Verify) located at the far left of the toolbar and fix any syntax errors that are reported. Once that is done, save the sketch by selecting File > Save As… from the main menu, entering the name and location of the new sketch (you could name it MyBlink or whatever you like), and then click the Save button. The Arduino IDE will create a new directory with the same name as the one you entered that contains a file with the same entered name and a .ino extension.
Click the Upload button, located just to the right of the Verify button we clicked earlier, to run our updated sketch. You should now see the LED blinking in the circuit you built. Congratulations, we now have a blinking LED!
A Better Blink
The Blink sketch used in the previous section is the quintessential first sketch used for blinking an LED on an Arduino. But we can make it better.
Create a new sketch by selecting File > New Sketch from the main menu. The default name given to the new sketch will be named sketch_ followed by the current date and then a letter denoting the creation sequence. For example, the first sketch created on a particular date, such as January 14th, would be named sketch_jan14a, the second sketch created that same day would be named sketch_jan14b, and so on.
Let’s give our new sketch a different name. Select File > Save As… from the main menu. A new window will appear where you can change the sketch’s name and choose where it will be saved. Save this sketch as BetterBlink. The title of the sketch window should change to reflect the new sketch name.
Replace the contents of the new sketch with the following.
const uint8_t RedLED = 2; const unsigned long BlinkPeriod = 2000; void setup() { pinMode(RedLED, OUTPUT); } void loop() { static unsigned long previousBlinkTime = 0; unsigned long currentTime = millis(); if (currentTime - previousBlinkTime >= BlinkPeriod/2) { digitalWrite(RedLED, !digitalRead(RedLED)); previousBlinkTime = currentTime; } }
This sketch is a bit more complicated but provides a more robust starting point for building larger programs in the future that involve multiple components and operations. The first change we make is to define a constant, RedLED
, for pin 2, as shown in line 1 of the sketch above. Now, whenever we see RedLED
later in the program, line 12 for instance, we know we are operating on the red LED. Just seeing a pin number does not offer much context.
The biggest drawback of the original Blink sketch is the use of the delay()
function. This function pauses the execution of the program for the time specified. This means no other operations can occur during that pause. To resolve that issue, we can instead check if a certain time has elapsed before executing an operation. This essentially provides us the ability to run multiple operations simultaneously.
This is accomplished on line 2 and lines 9-14 of the sketch. The BlinkPeriod
constant is defined as 2000
milliseconds, meaning the LED blinks every two seconds, just like in the original example sketch. Line 9 defines and initializes the previousBlinkTime
variable; the static
keyword tells the compiler to preserve the variable’s value in between loop()
function invocations. Line 10 captures the current time using the millis()
function which returns the number of milliseconds passed since the Arduino board began running the current sketch. Line 13, in conjunction with line 9, keep track of the last time the LED blinked.
Line 11 is where the magic happens. This line compares the last time a blink operation occurred to the current time. If the current time is over half a period away from the last blink time, the enclosed statements will be executed.
Line 12 toggles the on/off state of the LED. We could have used two digitalWrite()
statements that separately set the states to HIGH
and LOW
, but I chose to just read the current state and set it to the opposite state in one line. This is the reason that half of a period is used in line 11.
Verify the code compiles properly by clicking the Verify (checkmark) button and fix any syntax issues that are reported.
Test the BetterBlink sketch is functioning properly by uploading (Upload button) the new sketch to the Arduino Uno. You should again see the LED blinking. Test some other periods by changing the BlinkPeriod
to other times and see how the blinking rate changes.
Hopefully, you can see the benefits of the BetterBlink approach. Although we won’t do it here, we could add operations, for instance, to read a sensor in addition to the current blinking operations. That would entail adding a new period for how often you want to read the sensor and then checking the current time against that new period before reading the sensor. The beauty of it all is that it all happens without delays allowing us to run more operations.
Once a sketch is uploaded to an Arduino board, the sketch will begin running automatically any time power is supplied to the board. This is a very nice feature for completed projects that don’t need a connection to your computer, but it can cause problems during development. If an old project sketch begins running when you have attached different electronics to the Arduino board’s pins for a new project, the sketch could be driving outputs that could not only damage the new electronics but the Arduino board itself. For this reason, it is always a good idea to run the BareMinimum sketch to reset all pins back to their default states before closing the Arduino IDE and disconnecting the board from your computer. It never hurts to be extra cautious, right? This sketch is located at File > Examples > 01.Basics > BareMinimum from the main menu and contains only empty setup()
and loop()
functions. After loading the sketch, click the Upload button to run the BareMinimum sketch.
You can now safely exit the Arduino IDE application and disconnect your Arduino Uno from your computer.
Summary
In this tutorial, we learned how to construct an LED circuit and control it with a sketch running on an Arduino development board.
Specifically, we learned
- how to construct an LED circuit on a breadboard and attach it to an Arduino board,
- how to write a Sketch program in the Arduino IDE,
- how to compile and upload a sketch to run on the Arduino board, and
- how to build a more robust blinking sketch.
The final sketches used in this tutorial are available on GitHub. The GitHub versions of the code are fully commented to include additional information, such as the program’s description, circuit connections, and code clarifications.
I also created the Arduino Basics Cheatsheet that you may want to download and reference in the future.
Thank you for joining me on this journey and I hope you enjoyed the experience. Please feel free to share your thoughts or questions in the comments section below.
This tutorial is provided as a free service to our valued readers. Please help us continue this endeavor by considering a donation.
hello , what is Delay high and low for this frequencies : 5 hz 5,5 hz 25 hz and 40 hz because i want to blinking LED with this frequencies and it is possible to blinking LED with 2 frequencies 5 hz in left and 25 hz in right .
Since the
delay()
function takes the delay time in milliseconds for its argument, all you need to do to determine the appropriate blink period is to divide 1000 (ms for 1 Hz) by the desired frequency to get the full period and then by 2 to evenly divide that period for the respective LED on and off times.For example, the on and off delays for an LED blinking at 5 Hz would be 1000 / 5 / 2 = 100. So use
delay(100)
in between changing the LED states.Since the delay time for a frequency of 5.5 Hz is 1000 / 5.5 / 2 ≈ 90.91, you will need to round it to the closest integer value, 91 in this case.
I’m sorry, but I don’t know what you mean by “blinking LED with 2 frequencies 5 hz in left and 25 hz in right”. Could you please explain this further?