Arduino Activity 2: LEDs

Arduino Activity 2: LEDs

by ACROBOTIC Industries


Time to complete: 2–10min; Level of difficulty: Beginner

In this activity, we’ll build an electronic circuit with LEDs and control their brightness using our Arduino board.

List of Materials

  • 1 x Arduino Uno R3
  • 1 x USB-A to USB-B Male / Male Cable
  • 1 x 3mm Color LED Set (10-Pack)
  • 1 x Resistor 1/4W Through Hole (1KOhm)
  • 1 x Jumper Wires Male/Male - 10-pack
  • 1 x Mounting Plate for Arduino Uno
  • 1 x Half-Sized Solderless Breadboard

Obtaining the Code

For this activity, we'll be loading 3 different programs to our Arduino Uno board, which are available in our Github repository:

We can open a new window in the Arduino environment and copy-paste the code.  We'll start out with the program Blink External.


Before jumping into this activity, let's discuss a few important details about Light-Emitting Diodes (or LEDs, for short).

Diodes (and transistors!) have been a fundamental part of the evolution of the digital electronics world.  In fact, LEDs are a type of diode that are capable of transforming electric current into light!  These devices come in all shapes and sizes, and are used ubiquitously around us.  Likely, the next artificial light you see will be emmitted by an LED.

The low energy consumption, low maintenance and small size of LEDs make them very usful as status indicators and displays on a variety of equipment and installations.  In addition, advances in high-power and high-efficiency have made them useful for general lighting purposes, such as in traffic stop lights, car headlights, and in a large number of different applications.

LED costume for professional stage performers, created by the artist Beo Beyond.

There are a couple of practical things we need to remember when working with these devices:


LEDs are made from a variety of semiconductor compounds mixed at different ratios to produce a distinct wavelength of color.  Different compounds emit light in specific regions of the visible light spectrum and therefore produce different intensity levels.  

Note that the color of an LED is not given by the plastic casing around it, but rather by the compounds that comprise it as shown by the color of the clear-capsule LEDs above!


Similar to regular diodes, LEDs only allow current flow in one direction.  Thus, reversing the polarity of the power supply to an LED will not damage it (fortunately!), but no light will be emitted either.

LED Anatomy

For LEDs that have terminals (or legs)—like those used in this activity—the positive terminal (anode) is denoted by a longer lead.  In addition, the negative terminal (cathode) is also denoted by a flat side on the capsule around the LED itself!

Forward Voltage

In order to emit light, LEDs need to operate under what's called a "forward bias" condition.  For doing so, a power supply should provide enough power (current and voltage) to meet that condition.  The specific voltage and current values for this condition vary for each LED model, and they're specificied in the corresponding datasheet (a technical user guide for the component).

Forward Voltage vs Forward Current Chart

Typically, we would connect a resistor in series with the LED to protect if from excessive current flow.  The value of the resistor will depend on the forward voltage and current of the LED.  For this activity we'll use a 1KOhm resistor and a red LED.  Note that different colors and types of LEDs will need different current and voltage levels to emit light at the same intensity and brightness.

Luminous Flux vs. Luminous Intensity

Characterizing the brightness of LEDs is typically done using two measurements:  luminous flux (in lumens), which is a measure of the total light output from a source; and, luminous intensity (in candelas), which is a measure of how bright the beam of light is in a particular direction.

LED Cone Angles

A great example of this, illustrated above, can be seen by comparing two LEDs with identical luminous flux of 0.2 lumens (at a current of 30mA).  Because the LED on the left has a lens that narrows the cone of light emitted to 15°, in contrast to the one on the right that uses a lens that concentrates the light in a cone of 30°, the luminous intensity is 3.7 candelas for the former, and 0.9 candelas for the latter.

Wiring: Blink External

It is important to disconnect the Arduino board from any power source including the USB port from our computer.  This allows us to catch any wiring mistakes before turning it on, preventing components from being damaged.  Once power is off, we can proceed with wiring the following circuit:

A few things to note about the wiring are:

  • The positive lead (anode) of the LED is connected to pin 13 on the Arduino Uno; this can be done directly or using a jumper wire (as illustrated).  It's important to remember that the wiring diagrams denote the anode with a little kink near the casing of the LED
  • The negative lead is connected to the same row as one of the leads of our 1KOhm resistor (note that the resitor markings should be Brown-Black-Red)
  • The other lead of the resistor is connected to a ground (GND) pin on the Arduino Uno; this can be done directly or using a jumper wire

After ensuring that we've wired up things correctly, we can upload the Blink External program to our Arduino Uno board.  To do so, we connect the board to the computer's USB port, we select the port and board model, and hit the upload button (more details on doing this can be found in our "Blink" tutorial).

Code Walkthrough: Blink External

We've already dissected the operation of the code in a previous tutorial!  However, after uploading it to the board a couple of things are worth noting.

The ‘L’ LED turns on and off simultaneously with the LED we've connected to pin 13!  This is not an error, but a consequence of the ‘L’ LED being connected internally on the Arudino board to pin 13.​

Remember that it's useful to use this built-in mechanism for quickly testing the operation of the board.  Thus, connecting a simple device with perceivable output (such as an LED) to one of the Input/Output pins of the microcontroller is a great way of doing this.  Thanks to the Open-Source licenses of the Arduino hardware, we can verify on the schematic diagram of the board that this connection is included in the board design.

Wiring: Blink Compare

In our Getting Started with Arduino tutorial we learned that by modifying the two time delays in the program we could alter the blink rate of the LED.  Naturally, we wonder:

What happens if we set the delays to very small values?

To address this question we can setup a quick experiment where we wire up a second LED connected to pin 12.  Then, we can have one of the two blinking while the other is always on (using the program Blink Compare listed above).  This will allow us to compare their brightness and convince ourselves of the difference.

Code Walkthrough: Blink Compare

The short answer to the question above is that as the delays in the program get shorter our eyes will have a harder time observing the period in which the LED is off due to a phenomenon called flicker fusion.  However, even if we set the value of the delays to 0 (delay(0);) the LED will be off for a very short amount of time due to the digitalWrite(led_flicker, LOW) instruction on the code. Despite not being able to see the light go off, our eyes will perceive a lower LED brightness than if the LED was always on.

// the loop routine runs over and over again forever:
void loop()
  digitalWrite(led_flicker, HIGH); // turn the LED on (HIGH is the voltage level)
  delay(1); // wait for 1ms
  digitalWrite(led_flicker, LOW);// turn the LED off by making the voltage LOW

Despite having very short delays between the on-off switching of the LED, its brightness is noticeably lower than that of the one where we apply power constantly.  Although we'd need a high-speed video camera to clearly show the difference, setting a fast shutter speed on a DSLR and taking multiple shots gives us some insight:

Although the LED's luminance alternates between fully on and fully off, we perceive it as something of an averaged value.  Thus, considering the average power (voltage x current) applied to each LED—1/10th of a watt for the constant case, and 1/5th in the flickering one—it's understandable that there be a difference between the two.  After all, the relative intensity of an LED is a function of its forward voltage (current).  We'll go into more detail about this topic in a future tutorial, but for now we can use this to make a dimmable LED. 

Brightness Control and PWM

We can modify our Blink External program in order to control the brightness of an LED.  As we've seen, thanks to flicker fusion if we shorten the delays between switching the on-off state of the LED, its brigtness will increase.  If we increase the delays, the LED will be dimmer.  However, increasing the delay up to a certain threshold will allow us to notice the on-off flicker, which is undesirable.

We could then change our code to allow for the following 3 cases:

  • Fully ON: no delay and no digitalWrite(ledPin,LOW); statement
  • Dimming: increase the delay from 1ms to 30ms (flicker fusion stops at around 30Hz for the human eye)
  • Fully OFF: no digitalWrite(ledPin,HIGH); statement

As explained in our Pulse-Width Modulation (PWM) tutorial, controlling the on-off duration of a digital signal is very common (and useful), thus there are easier ways to proceed than what we've outlined above.  In the Arduino environment, we can use the function:

  • analogWrite(pin, value);

We can write the maximum value (255) for the fully ON case, the minimum value (0) for the fully OFF case, and anything in between for dimming the emitted light.

Wiring: Heartbeat

The PWM functionality is so useful in electronics that it's been implemented in the hardware itself (though we can also use software implementations).  However, because of the many special functions that a microcontroller can contain, only certain pins are capable of hardware PWM.  We can immediately recognize these pins on the Arduino Uno board by the tilde (~) symbol preceding the pin number (on pins 3, 5, 6, 9, 10, 11).

In this activity we change the led pin to 11 to make use of PWM, which is available on that pin.

Code Walkthrough: Heartbeat

After wiring, we can upload the last piece of code (Heartbeat) of this activity.  This program was written to increase and decrease the brightness of the LED in a pulsating fashion that resembles the expansion and contraction of a beating heart.

In our setup() contains all the standard calls for setting up the hardware.  In our loop() we do 2 things, we start by setting the brightness value, which starts at 0.  We hold that value for a short amount of time (pre-defined as 5ms).  And, we increase (or decrease if step_size is negative) the brightness value for the next cycle.

  analogWrite(led_pin, value); //set the current LED brightness  
  delay(step_delay_ms); //hold the value for a short time
  value+=step_size; //increase the current value for the next iteration

Before going back to the top of the loop, we check that the brightness value is within bounds (0 to value_max).  If this check is false we return to the top of loop().  If it is true, then value is out of the bounds, thus we change the direction by reversing the sign of step_size, we force value to be within bounds, and if we're at the lower bound (i.e., 0) we pause for 1000ms.

  // if we've reached the maximum or minimum value, change direction of
  // change in brightness (i.e., increasing -> decreasing or viceversa)
  if( (value>value_max)||(value<0) )
    step_size *= -1;
    value+=step_size; // ensure that value stays within bounds
    if(value == 0)
      delay(cycle_delay_ms); // hold 1 second off starting each cycle

Code Tinkering

As an exercise, we encourage you to make the heartbeat a little more ‘realistic’.  Recalling that diastole (relaxation) takes about twice as long as systole (contraction), we can attempt to change the code so that the increase in brightness takes longer than the decrease.

Hint: an easy way to do this is to separate the conditional of the loop into two separate cases.

Leave a comment

  • Please note, comments must be approved before they are published

$1 Days
$2 Hours
$3 Minutes
$4 Second
{ "en":{ "general": { "field": { "required": "Required", "actions": "Actions", "top_btn": "Top" }, "accessibility": { "skip_to_content": "Skip to content", "close_modal": "Close (esc)" }, "meta": { "tags": "Tagged \"[[ tags ]]\"", "page": "Page [[ page ]]" }, "404": { "title": "404 Page Not Found", "subtext": "The page you requested does not exist.", "link": "Continue shopping" }, "pagination": { "previous": "Previous", "next": "Next", "current_page": "Page [[ current ]] of [[ total ]]" }, "password_page": { "opening_soon": "Opening Soon", "login_form_heading": "Enter store using password", "login_form_password_label": "Password", "login_form_password_placeholder": "Your password", "login_form_submit": "Enter", "signup_form_email_label": "Email", "signup_form_success": "We will send you an email right before we open!", "admin_link_html": "Are you the store owner? Log in here<\/a>", "password_link": "Enter using password", "powered_by_shopify_html": "This shop will be powered by [[ shopify ]]" }, "social": { "share_on_facebook": "Share", "share_on_twitter": "Tweet", "share_on_pinterest": "Pin it", "alt_text": { "share_on_facebook": "Share on Facebook", "share_on_twitter": "Tweet on Twitter", "share_on_pinterest": "Pin on Pinterest" } }, "search": { "no_results_html": "Your search for \"[[ terms ]]\" did not yield any results.", "results_with_count": { "one": "[[ count ]] result for \"[[ terms ]]\"", "other": "[[ count ]] results for \"[[ terms ]]\"" }, "title": "Search our site", "placeholder": "Search", "submit": "Submit", "close": "Close search" }, "newsletter_form": { "newsletter_email": "Join our mailing list", "email_placeholder": "Email address", "confirmation": "Thanks for subscribing", "submit": "Subscribe", "show_me_text": "Do not show me again" }, "filters": { "show_more": "Show More", "show_less": "Show Less" }, "breadcrumbs": { "home": "Home", "create_account": "Create account", "account": "Account", "addresses": "Addresses" }, "item": { "remove": "Remove Item" } }, "sections": { "header": { "top_header_login": "Login", "top_header_register": "Register", "top_header_wishlist": "Wish list", "register_dropdown": "No account? Create one here", "forgot": "Forgot password", "all_collection": "All Collections", "world_wide_delivery": "Worldwide delivery", "shipping_text": "Free UK Delivery on orders over £ 100", "hot_line": "Hot line" }, "menu": { "mobile_menu_tab": "Menu", "mobile_account_tab": "Account", "mobile_settings_tab": "Settings" }, "slideshow": { "next_slide": "Next slide", "previous_slide": "Previous slide", "pause_slideshow": "Pause slideshow", "play_slideshow": "Play slideshow", "play_video": "Play video", "close_video": "Close video" }, "map": { "get_directions": "Get directions", "address_error": "Error looking up that address", "address_no_results": "No results for that address", "address_query_limit_html": "You have exceeded the Google API usage limit. Consider upgrading to a Premium Plan<\/a>.", "auth_error_html": "There was a problem authenticating your Google Maps account. Create and enable the JavaScript API<\/a> and Geocoding API<\/a> permissions of your app." } }, "blogs": { "article": { "view_all": "View all", "all_topics": "All topics", "by_author": "by [[ author ]]", "posted_in": "Posted in", "read_more": "Read more", "back_to_blog": "Back to [[ title ]]" }, "comments": { "title": "Leave a comment", "name": "Name", "email": "Email", "message": "Message", "post": "Post comment", "moderated": "Please note, comments must be approved before they are published", "success_moderated": "Your comment was posted successfully. We will publish it in a little while, as our blog is moderated.", "success": "Your comment was posted successfully! Thank you!", "comments_with_count": { "one": "[[ count ]] comment", "other": "[[ count ]] comments" } } }, "cart": { "general": { "title": "Your cart", "note": "Add a note to your order", "remove": "Remove", "subtotal": "Subtotal", "savings": "You're saving", "shipping_at_checkout": "Shipping & taxes calculated at checkout", "update": "Update", "checkout": "Process Check out", "empty": "Your cart is currently empty.", "cookies_required": "Enable cookies to use the shopping cart", "edit": "Edit", "cancel": "Cancel", "continue_shopping": "Continue shopping", "recently_added_item": "Recently added item(s)", "remove_item": "Remove This Item", "view_and_edit_cart": "View and edit cart", "clear": "Clear cart", "empty_page_title": "Shopping Cart is Empty", "here": "here", "empty_continue_html": "Click here to continue shopping.", "processing": "Processing...", "items_count_label" : "[[ count ]] item(s) in your cart", "ok" : "Ok" }, "label": { "product": "Product", "price": "Price", "quantity": "Quantity", "total": "Total", "total_item": "Total item", "sub_total_top": "Cart Subtotal" } }, "collections": { "general": { "view_all": "View all", "clear_all": "Clear All", "no_matches": "Sorry, there are no products in this collection", "items_with_count": { "one": "[[ count ]] product", "other": "[[ count ]] products" }, "load_more": "Load More", "sidebar_btn": "Filter by" }, "sorting": { "title": "Sort by", "manual": "Featured", "best_selling": "Best Selling", "title_ascending": "Alphabetically, A-Z", "title_descending": "Alphabetically, Z-A", "price_ascending": "Price, low to high", "price_descending": "Price, high to low", "created_descending": "Date, new to old", "created_ascending": "Date, old to new" }, "filters": { "title_tags": "Filter", "all_tags": "All products", "categories": "categories", "title": "Filter", "color": "Color", "size": "Size", "brand": "Brand", "price": "Price", "green": "Green", "blue": "Blue", "red": "Red", "pink": "Pink", "black": "Black", "purple": "Purple", "white": "White", "orange": "Orange" }, "product_item": { "quick_shop": "Quick View", "compare": "Compare", "wishlist": "Add to Wishlist" } }, "contact": { "form": { "name": "Name", "email": "Email", "phone": "Phone Number", "message": "Message", "submit": "Submit", "post_success": "Thanks for contacting us. We'll get back to you as soon as possible.", "address": "Address", "telephone": "Telephone", "title": "Write us", "required": "Required" } }, "customer": { "account": { "title": "My Account", "details": "Account Details", "view_addresses": "View Addresses", "return": "Return to Account Details" }, "activate_account": { "title": "Activate Account", "subtext": "Create your password to activate your account.", "password": "Password", "password_confirm": "Confirm Password", "submit": "Activate Account", "cancel": "Decline Invitation" }, "addresses": { "title": "Your Addresses", "default": "Default", "add_new": "Add a New Address", "edit_address": "Edit address", "first_name": "First Name", "last_name": "Last Name", "company": "Company", "address1": "Address1", "address2": "Address2", "city": "City", "country": "Country", "province": "Province", "zip": "Postal\/Zip Code", "phone": "Phone", "set_default": "Set as default address", "add": "Add Address", "update": "Update Address", "cancel": "Cancel", "edit": "Edit", "delete": "Delete", "delete_confirm": "Are you sure you wish to delete this address?" }, "login": { "title": "Login", "desc": "If you have an account, sign in with your email address.", "email": "Email", "password": "Password", "forgot_password": "Forgot your password?", "sign_in": "Sign In", "guest_title": "Continue as a guest", "guest_continue": "Continue" }, "orders": { "title": "Order History", "order_number": "Order", "date": "Date", "payment_status": "Payment Status", "fulfillment_status": "Fulfillment Status", "total": "Total", "none": "You haven't placed any orders yet." }, "order": { "title": "Order [[ name ]]", "date": "Placed on [[ date ]]", "cancelled": "Order Cancelled on [[ date ]]", "cancelled_reason": "Reason: [[ reason ]]", "billing_address": "Billing Address", "payment_status": "Payment Status", "shipping_address": "Shipping Address", "fulfillment_status": "Fulfillment Status", "discount": "Discount", "shipping": "Shipping", "tax": "Tax", "product": "Product", "sku": "SKU", "price": "Price", "quantity": "Quantity", "total": "Total", "fulfilled_at": "Fulfilled [[ date ]]", "subtotal": "Subtotal" }, "recover_password": { "title": "Reset your password", "email": "Email", "submit": "Submit", "cancel": "Cancel", "subtext": "We will send you an email to reset your password.", "success": "We've sent you an email with a link to update your password." }, "reset_password": { "title": "Reset account password", "subtext": "Enter a new password for [[ email ]]", "password": "Password", "password_confirm": "Confirm Password", "submit": "Reset Password" }, "register": { "title": "Create Account", "first_name": "First Name", "last_name": "Last Name", "email": "Email", "password": "Password", "submit": "Create", "desc": "Creating an account is easy. Just fill in the form below." } }, "homepage": { "onboarding": { "product_title": "Your product's name", "product_description": "This area is used to describe your product’s details. Tell customers about the look, feel, and style of your product. Add details on color, materials used, sizing, and where it was made.", "collection_title": "Your collection's name", "blog_title": "Your post's title", "blog_excerpt": "Your store hasn’t published any blog posts yet. A blog can be used to talk about new product launches, tips, or other news you want to share with your customers. You can check out Shopify’s ecommerce blog for inspiration and advice for your own store and blog.", "blog_author": "Author name", "no_content": "This section doesn’t currently include any content. Add content to this section using the sidebar." } }, "layout": { "navigation": { "search": "Search", "toggle": "expand\/collapse", "expand": "expand", "collapse": "collapse", "all_categories": "All Categories" }, "cart": { "title": "Cart", "items_count": { "one": "item", "other": "items" } }, "customer": { "account": "Account", "log_out": "Log out", "logout": "Log out", "log_in": "Log in", "create_account": "Create account", "sign_up": "Sign up", "wishlist": "Wishlist" }, "footer": { "social_platform": "[[ name ]] on [[ platform ]]" }, "list_page": { "grid": "Grid", "list": "List" } }, "products": { "product": { "regular_price": "Regular price", "sold_out": "Sold out", "unavailable": "Unavailable", "on_sale": "Sale", "quantity": "Quantity", "add_to_cart": "Add to cart", "back_to_collection": "Back to [[ title ]]", "related_title": "Related Products", "qty_increase": "Increase", "qty_decrease": "Decrease", "deal_days": "Days", "deal_hours": "Hours", "deal_minutes": "Minutes", "deal_second": "Second", "select_option": "Select Option", "add_to_wishlist": "Add to Wishlist", "add_to_review": "Add to review", "compare_success_msg": "[[ product_title ]] has added to comparing box successful", "compare_exist_msg": "[[ product_title ]] is exist in comparing box", "compare_cart_msg": "[[ product_title ]] has added to shopping cart", "compare_remove_msg": "[[ product_title ]] has removed from comparing box", "compare_remove_msg": "[[ product_title ]] has removed from comparing box", "comparing_box": "Comparing box", "compare_no_items": "There is no items in comparing box", "wishlist_success_msg": "[[ product_title ]] has added to wishlist successful", "wishlist_exist_msg": "[[ product_title ]] is exist in wishlist", "wishlist_cart_msg": "[[ product_title ]] has added to shopping cart", "wishlist_box": "Wishlist", "wishlist_remove_msg": "[[ product_title ]] has removed from wishlist", "wislist_no_items": "There is no items in wishlist", "upsell_cart_msg": "\"[[ product_title ]]\" has added to shopping cart", "upsell_block_title": "Frequently bought with \"[[ product_title ]]\"", "upsell_cart_qty": "[[ count ]] item(s)", "upsell_product_page_title": "You may also like these products", "upsell_checkout_btn": "Checkout", "share": "Share product", "share_on_facebook": "Share on Facebook", "share_on_twitter": "Share on Twitter", "share_on_pinterest": "Share on Pinterest", "share_on_google": "Share on Google+", "share_on_linkedin": "Share on LinkedIn", "availability": "Availability", "in_stock": "In Stock", "out_of_stock": "Out of stock", "quick_overview": "Quick Overview", "details": "Details", "reviews": "Reviews", "first_review": "Be the first review", "tags": "Product Tags", "size_chart": "Size Chart", "options": "Options", "vendor": "Vendor", "features": "Features", "sale_left_text": "[[ sales ]] SOLD. HURRY! ONLY A FEW LEFT!", "checkout_text": "Secured and trusted checkout with" }, "upsell": { "recommend_text": "Someone purchased a", "minute_ago": "minutes ago" } }, "gift_cards": { "issued": { "title_html": "Here's your [[ value ]] gift card for [[ shop ]]!", "subtext": "Your gift card", "disabled": "Disabled", "expired": "Expired on [[ expiry ]]", "active": "Expires on [[ expiry ]]", "redeem_html": "Use this code at checkout to redeem your [[ value ]] gift card", "shop_link": "Start shopping", "print": "Print this gift card", "remaining_html": "[[ balance ]] left", "add_to_apple_wallet": "Add to Apple Wallet" } }, "date_formats": { "month_day_year": "%B %d, %Y" } } }