Electronics Software Development

Blink: Making An LED Blink On An Arduino Uno

Blink Blue LEDs
Written by John Woolsey

Last Updated: October 23, 2020
Originally Published: May 24, 2018

Skill Level: Beginner

Table Of Contents

Introduction

This tutorial will teach you how to connect and control an LED on 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 configure the Arduino IDE to recognize your 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.

There is also an Arduino Basics cheatsheet available if you are interested.

The sketches used in this tutorial is available on GitHub for your reference.

What Is Needed

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 hobbyists to construct circuits without having to permanently (for the most part) attach your electronic components or having to deal with soldering them together. If you are not familiar with solderless breadboards, please refer to the Core Electronics’ How to Use Breadboards and Science Buddies’ How to Use a Breadboard guides for details on how they work.

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++ library routines. 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 Getting Started page 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.

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 just above D13 on the Arduino Uno DIGITAL pins header. Once completed, your circuit should look like the one shown below.

Arduino Uno Blink Circuit
LED Circuit Attached To Arduino Uno

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 Getting Started guide on Arduino’s website.

Once installed, we need to let the IDE know which development board you are using. This is accomplished by selecting Tools > Board: from the main menu and then continuing through the sub-menus to choose your particular board. For the Arduino Uno, this will be Tools > Board: > Arduino AVR Boards > Arduino Uno.

We then need to specify the serial port that the board will use to communicate with your computer. Select Tools > Port: from the main menu and then the appropriate port for your board. The board name should show up in parenthesis after the port name. For instance, the port for my Arduino WiFi Rev2 on my macOS system is displayed as /dev/cu.usbmodem14202 (Arduino Uno WiFi Rev2).

This process is further detailed for the specific boards listed on the right-hand side of the page in the Getting Started guide.

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 through 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 pin mode as an output in this example.

The loop() function runs repeatedly over and over after the setup() function has 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. The status bar just below the code area will display Compiling sketch…, then Uploading…, then Done uploading. and the message area below the status bar will display information about your uploaded sketch. 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.

Arduino Blink Sketch Window
Blink Sketch Window In Arduino IDE

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 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 circuit to the Arduino Uno DIGITAL header. Now let’s change line 33 from

digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

to

digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)

and line 35 from

digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW

to

digitalWrite(2, LOW);    // turn the LED off by making the voltage 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 displayed. 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 finally clicking 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!

The Blink sketch used in the previous section is the quintessential first sketch used for blinking an LED on an Arduino Uno. But we can make it better.

Create a new sketch by selecting File > New from the main menu. The default name given to the sketch will be named as 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 October 23rd, would be named sketch_oct23a, the second sketch created that same day would be named sketch_oct23b, and so on.

Let’s give our new sketch a different name. Select File > Save As… from the main menu or click the down arrow (Save) button within the toolbar. A new window will appear where you can change the sketch’s name and choose where it will be saved. Save this new sketch as BetterBlink. The title of the sketch window should change to reflect the new sketch name.

Replace the contents of sketch with the following.

// Arduino sketch that blinks an LED without using delay().

const byte RedLED = 2;                   // reference digital pin 2 as RedLED
const unsigned long BlinkPeriod = 1000;  // blinking period in milliseconds

void setup() {
   pinMode(RedLED, OUTPUT);  // set RedLED pin as an output
}

void loop() {
   static unsigned long previousBlinkTime = 0;              // capture initial previous time
   unsigned long currentTime = millis();                    // capture current time
   if (currentTime - previousBlinkTime >= BlinkPeriod/2) {  // run every half blinking period (500 ms)
      digitalWrite(RedLED, !digitalRead(RedLED));           // toggle on/off LED
      previousBlinkTime = currentTime;                      // save previous time
   }
}

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 are making is to define a constant, RedLED, for pin 2, as shown on line 3 of the sketch. Now, whenever we see RedLED later in the program, line 14 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 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 particular time has gone by before executing an operation. This essentially provides us the ability to run multiple operations simultaneously.

This is accomplished on line 4 and lines 11-16 of the sketch. The BlinkPeriod constant is defined as 1000 milliseconds which means the LED will blink every second. Line 12 captures the current time using the millis() function which returns the number of milliseconds passed since the Arduino board began running the current sketch. Lines 11 and 15 keep track of the last time the LED blinked.

Line 13 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 14 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 in one line. This is the reason that half of a period is used in line 13.

Just to be clear, the periods used in the original Blink sketch and the improved BetterBlink sketch are different. Since Blink has a delay of 1 second between state changes, it has an effective blink period of 2 seconds. The BetterBlink sketch, with its 1 second blink period, waits for 500 ms (1000/2) before making any state changes, therefore it will blink quicker.

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, but at a faster rate this time. Test some other periods by changing the BlinkPeriod to other times and see how the blinking rate changes.

Although we won’t do it here, hopefully you can see the benefits of the BetterBlink approach. In addition to the current blinking operations, we could add operations for say reading a sensor. 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.

Before closing the Arduino IDE and disconnecting the board from your computer, it is always a good idea to run the BareMinimum sketch to reset all pins back to their default state in order to avoid accidental damage to the Arduino board. 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 configure the Arduino IDE to recognize your 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 is available on GitHub.

Thank you for joining me in this journey and I hope you enjoyed the experience. Please feel free to share your thoughts in the comments section below.

About the author

John Woolsey

John is an electrical engineer who loves science, math, and technology and teaching it to others even more.
 
He knew he wanted to work with electronics from an early age, building his first robot when he was in 8th grade. His first computer was a Timex/Sinclair 2068 followed by the Tandy 1000 TL (aka really old stuff).
 
He put himself through college (The University of Texas at Austin) by working at Motorola where he worked for many years afterward in the Semiconductor Products Sector in Research and Development.
 
John started developing mobile app software in 2010 for himself and for other companies. He has also taught programming to kids for summer school and enjoyed years of judging kids science projects at the Austin Energy Regional Science Festival.
 
Electronics, software, and teaching all culminate in his new venture to learn, make, and teach others via the Woolsey Workshop website.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.