Podbean logo
  • Discover
  • Podcast Features
    • Podcast Hosting

      Start your podcast with all the features you need.

    • Podbean AI Podbean AI

      AI-Enhanced Audio Quality and Content Generation.

    • Blog to Podcast

      Repurpose your blog into an engaging podcast.

    • Video to Podcast

      Convert YouTube playlists to podcasts, videos to audios.

  • Monetization
    • Ads Marketplace

      Join Ads Marketplace to earn through podcast sponsorships.

    • PodAds

      Manage your ads with dynamic ad insertion capability.

    • Apple Podcasts Subscriptions Integration

      Monetize with Apple Podcasts Subscriptions via Podbean.

    • Live Streaming

      Earn rewards and recurring income from Fan Club membership.

  • Podbean App
    • Podcast Studio

      Easy-to-use audio recorder app.

    • Podcast App

      The best podcast player & podcast app.

  • Help and Support
    • Help Center

      Get the answers and support you need.

    • Podbean Academy

      Resources and guides to launch, grow, and monetize podcast.

    • Podbean Blog

      Stay updated with the latest podcasting tips and trends.

    • What’s New

      Check out our newest and recently released features!

    • Podcasting Smarter

      Podcast interviews, best practices, and helpful tips.

  • Popular Topics
    • How to Start a Podcast

      The step-by-step guide to start your own podcast.

    • How to Start a Live Podcast

      Create the best live podcast and engage your audience.

    • How to Monetize a Podcast

      Tips on making the decision to monetize your podcast.

    • How to Promote Your Podcast

      The best ways to get more eyes and ears on your podcast.

    • Podcast Advertising 101

      Everything you need to know about podcast advertising.

    • Mobile Podcast Recording Guide

      The ultimate guide to recording a podcast on your phone.

    • How to Use Group Recording

      Steps to set up and use group recording in the Podbean app.

  • All Arts Business Comedy Education
  • Fiction Government Health & Fitness History Kids & Family
  • Leisure Music News Religion & Spirituality Science
  • Society & Culture Sports Technology True Crime TV & Film
  • Live
  • How to Start a Podcast
  • How to Start a Live Podcast
  • How to Monetize a podcast
  • How to Promote Your Podcast
  • How to Use Group Recording
  • Log in
  • Start your podcast for free
  • Podcasting
    • Podcast Features
      • Podcast Hosting

        Start your podcast with all the features you need.

      • Podbean AI Podbean AI

        AI-Enhanced Audio Quality and Content Generation.

      • Blog to Podcast

        Repurpose your blog into an engaging podcast.

      • Video to Podcast

        Convert YouTube playlists to podcasts, videos to audios.

    • Monetization
      • Ads Marketplace

        Join Ads Marketplace to earn through podcast sponsorships.

      • PodAds

        Manage your ads with dynamic ad insertion capability.

      • Apple Podcasts Subscriptions Integration

        Monetize with Apple Podcasts Subscriptions via Podbean.

      • Live Streaming

        Earn rewards and recurring income from Fan Club membership.

    • Podbean App
      • Podcast Studio

        Easy-to-use audio recorder app.

      • Podcast App

        The best podcast player & podcast app.

  • Advertisers
  • Enterprise
  • Pricing
  • Resources
    • Help and Support
      • Help Center

        Get the answers and support you need.

      • Podbean Academy

        Resources and guides to launch, grow, and monetize podcast.

      • Podbean Blog

        Stay updated with the latest podcasting tips and trends.

      • What’s New

        Check out our newest and recently released features!

      • Podcasting Smarter

        Podcast interviews, best practices, and helpful tips.

    • Popular Topics
      • How to Start a Podcast

        The step-by-step guide to start your own podcast.

      • How to Start a Live Podcast

        Create the best live podcast and engage your audience.

      • How to Monetize a Podcast

        Tips on making the decision to monetize your podcast.

      • How to Promote Your Podcast

        The best ways to get more eyes and ears on your podcast.

      • Podcast Advertising 101

        Everything you need to know about podcast advertising.

      • Mobile Podcast Recording Guide

        The ultimate guide to recording a podcast on your phone.

      • How to Use Group Recording

        Steps to set up and use group recording in the Podbean app.

  • Discover
  • Log in
    Sign up free
Learn Programming and Electronics with Arduino

Learn Programming and Electronics with Arduino

Technology

Fade an LED with Arduino

Fade an LED with Arduino

2017-03-13
Download Right click and do "save link as"

Let’s expand the repertoire of output that we can use by looking at the function analogWrite().

I experienced much confusion with analogWrite(), because I suspected that it had to do with the analog pins on the Arduino. The function, however, has nothing to do with the analog pins.

There are 5 pins on most Arduino boards marked with ‘PWM’ next to the pin number (on some boards it is an “~” symbol) – these pins can be invoked to rapidly change the power being applied at the pin – this is a technique called pulse width modulation (PWM).

If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it.

You Will Need
LED – any color is fine
220 Ohm Resistor
Alligator Clip
Glacial ice cubes
Step-by-Step Instructions
Take the short leg of the LED and insert it in the GND pin.
Take either leg of the resistor and place it in pin 9.
Connect the long leg of the LED with the other leg of the resistor using an alligator clip
Plug the Arduino into your computer with the USB cable
Open up the Arduino IDE
Open the sketch for this section.
Click the Verify button (top left). The button will turn orange and then blue once finished.
Click the Upload button. The button will turn orange and then blue when finished.
Watch in mesmerizing amazement as the LED fades in and out.
Arduino Fade an LED BoardThis image built with Fritzing.

Discuss the Sketch
Below is the sketch in its entirety from the Arduino IDE:


/*
Fade

This example shows how to fade an LED on pin 9
using the analogWrite() function.

This example code is in the public domain.
*/

int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);

// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
Fade

This example shows how to fade an LED on pin 9
using the analogWrite() function.

This example code is in the public domain.
*/

int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);

// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
The sketch starts with the usual multiline comment describing the program and how to set up the circuit. The first block of code we encounter is the declaration and initialization of three integer variables. The variable names and comments are both descriptive and helpful – remember this when naming and commenting your own code – useful comments are a pillar of success!


int led = 9; // the pin that the LED is attached to

int brightness = 0; // how bright the LED is

int fadeAmount = 5; // how many points to fade the LED by
1
2
3
4
5
int led = 9; // the pin that the LED is attached to

int brightness = 0; // how bright the LED is

int fadeAmount = 5; // how many points to fade the LED by
The brightness variable will store the value of the current brightness of the LED. fadeAmount is the rate at which the LED will fade and brighten. And of course, as the comments explain, led is simply the pin number where we have attached the LED (through a 220-ohm resistor).

Now that we have declared and initialized our variables, we move on to setting up the board with the setup() function…


void setup() {

// declare pin 9 to be an output:

pinMode(led, OUTPUT);

}
1
2
3
4
5
6
7
void setup() {

// declare pin 9 to be an output:

pinMode(led, OUTPUT);

}
The only thing we do here is set the mode of pin 9 as an OUTPUT using the pinMode() function. Recall that pinMode() takes two arguments – the pin number and the mode. In this case, we assign the pin number using the variable led, which we previously initialized as the number 9. By now you know that setup() only runs once – the code inside the setup() curly bracket will only be executed a single time by the Arduino.

Where the real action happens is in loop().

The first function we encounter in the loop() is analogWrite(). This function invokes the Pulse Width Modulation capabilities of the Arduino board. Pulse Width Modulation basically adjusts the power output at the pin. So you can have a lot of power or a little power applied at the pin, it’s your call, just tell the analogWrite() function which pin to modulate and how much power you want to be applied. The scale is from 0 to 255 with zero being the lowest power setting and 255 being the highest. For a discussion of what is actually happening with pulse width modulation check out the further reading section.

As alluded to above, analogWrite() takes two arguments…


analogWrite(pin, value);
1
analogWrite(pin, value);
You can utilize analogWrite() with pins 3, 5, 6, 9, 10 and 11 – recall there is a “PWM” or “~” next to the pin number on the board.

In this sketch we use the arguments:


analogWrite(led, brightness);
1
analogWrite(led, brightness);
The first thing we do in the loop is write a value to pin 9 (recall that led holds the number 9) where we have our LED attached (through a resistor) – and we set the value to 0 (zero is what our brightness variable initially holds). This will keep our LED dark to start with.

Key Points about the analogWrite function

The next line of code we encounter is:


brightness = brightness + fadeAmount;

( 0 ) = ( 0 ) + (5) 1
2
3
brightness = brightness + fadeAmount;

( 0 ) = ( 0 ) + (5) We take the current value of ‘brightness’ and add the ‘fadeAmount’ to it, then we save this new value back to the brightness variable. Now the ‘brightness’ variable holds the number 5.

You can see that we are increasing the brightness variable, this, in turn, will make the LED brighter. When we start the loop over and use analogWrite(led, brightness) – it will be 5 “levels” brighter than it was before. Every time through the loop we add 5 to our brightness variable until we have one very bright LED.

You see, however, that if this were to continue, the brightness variable will quickly go over the top range of 255 our analogWrite() limit – not to mention, it won’t fade if the brightness variable only increases in value. We need a way to test the value of the brightness variable, and then change it when it gets to its limit.

Welcome “if statement”. The if statement is my favorite function – it can do so much and is so easy to use. An if statement checks a condition – if that condition is met, then it does something – if the condition is not met, then it does nothing. That easy.

Let’s say you are picking apples. You have an if statement running in your brain – something like…


if(apple is ripe AND not rotten) {

pick_apple()

put_in_basket()

}
1
2
3
4
5
6
7
if(apple is ripe AND not rotten) {

pick_apple()

put_in_basket()

}
The condition is what you type inside the parenthesis after the word ‘if’. Inside the curly braces, you type the code that you want to execute if the condition is met. If the condition is not met, the instructions are not executed – in the example above you would not want to pick unripened or rotten apples.

Let’s take a look at how the if statement helps us to fade the LED.


if (brightness == 0 || brightness == 255) {

fadeAmount = -fadeAmount ;

}
1
2
3
4
5
if (brightness == 0 || brightness == 255) {

fadeAmount = -fadeAmount ;

}
The condition here looks a little confusing, but let’s walk through it.

For starters, the || lines mean OR in computer speak. This condition says, “if the brightness variable equals zero OR if the brightness variable equals 255”.

You probably noticed the fact that they use a double equal sign – weird eh? The double equal sign is a comparison operator that asks “are these two values equal?”. The reason we need a double equal sign is because if we use a single equal sign, then we would be assigning a value to the brightness variable – and we do not want to assign anything – we want to compare! It is a subtle change in syntax but a huge change in application. There are several comparison operators that you will use. Further Reading at the end of this section has a link to more comparison operators.


brightness = 0 //this statement assigns a value to the brightness variable

brightness == 0 //this statement compares the brightness variable with 0
1
2
3
brightness = 0 //this statement assigns a value to the brightness variable

brightness == 0 //this statement compares the brightness variable with 0
The condition in an if statement will be either TRUE or FALSE. If it is TRUE, then the code enclosed in the curly brackets will execute.

Let’s say that our brightness variable is all the way up to the value 255.


if (brightness == 0 || brightness == 255) {

fadeAmount = -fadeAmount ;

//applying a negative sign to the variable will change its sign from positive to negative

}
1
2
3
4
5
6
7
if (brightness == 0 || brightness == 255) {

fadeAmount = -fadeAmount ;

//applying a negative sign to the variable will change its sign from positive to negative

}
This condition is met – now what?

All we do is a sneaky change of sign.


fadeAmount = -fadeAmount;

//applying a negative sign to the variable will change its sign from positive to negative
1
2
3
fadeAmount = -fadeAmount;

//applying a negative sign to the variable will change its sign from positive to negative
By assigning the fadeAmount variable to a negative version of itself, we are able to change its sign from positive to negative. The fadeAmount was being used to increase the value of the brightness variable – now that it is negative, each time through the loop() we will subtract 5 from the brightness variable – and the LED will start to dim because the value we write with analogWrite() is decreasing.

The best part about this clever line of code is that once the brightness variable decreases to zero, it will switch fadeAmount to positive and start the whole process over again! A fading LED – and easy to do!

Explanation of fadeAmount codeThe final step is slowing down the fading process. We use the delay() function to make sure we get to see the fading.


// wait for 30 milliseconds to see the dimming effect

delay(30);
1
2
3
// wait for 30 milliseconds to see the dimming effect

delay(30);
There is an interesting aspect of human vision called persistence of vision. Basically, if something flashes very rapidly – then we don’t perceive it as flashing, we perceive it as a steady image. Since our microcontroller operates rapidly, all this fading and brightening would not be noticeable if we didn’t slow it down with a delay.

Once we get to the end of the sketch we start back at the top of the loop(). We write the power level to the LED, we increment brightness, we check if brightness is maximized or minimized and then, if necessary, make the appropriate change to the sign of the fadeAmount variable.

Try On Your Own
At the top of the sketch, where the variable fadeAmount is declared and initialized, change the value and see what happens.
What happens if you reduce the delay time?
Can you fade multiple LEDs at the same time? (Hint: you will have to add another variable and use the analogWrite() function twice instead of once)
Further Reading
Pulse Width Modulation
analogWrite()
If Statement and Comparison Operators

view more

More Episodes

How to Make One Button Have the Functionality of Two or More with Arduino
2017-04-08
Understanding HIGH and LOW Arduino Pin States
2017-04-07
Floating Pins, Pull-Up Resistors and Arduino
2017-04-06
The MOST guaranteed way to NOT buy a Fake Arduino (The Story of Pizza-Duino)
2017-04-05
Throw out your breadboard! Dr. Duino: An Arduino Shield for debugging and developing Arduino projects
2017-04-04
Shorthand Arithmetic :: Using Compound Operators (+= , -= , *= , /= ) with Arduino
2017-04-03
Understanding Boolean Data Types and Using the Boolean NOT (!) operator to Switch Arduino Pin States
2017-04-02
What to do when you just don't know :: Arduino, ADXL345 triple axis accelerometer and an RGB LED
2017-04-01
3 Ways to Use Acceleration in an Arduino Sketch
2017-03-31
Check out our premium Arduino Training Course
2017-03-30
Understanding the Arduino uber functions loop() and setup()
2017-03-29
Functions: Let's make programming Arduino as easy as possible
2017-03-28
Data Types: One size does not fit all
2017-03-27
Understanding Variables
2017-03-26
Syntax; the spelling and grammar of programming
2017-03-25
Progress vs Perfection: Chicken Analogy
2017-03-24
The Arduino Development Toolchain - How it all gets done...
2017-03-23
Arduino Board Hardware overview for people like me
2017-03-22
Everything you need to know about the Arduino IDE (for now)
2017-03-21
Mac - Download and Install the Arduino IDE
2017-03-20
  • ←
  • 1
  • 2
  • 3
  • →
012345678910111213141516171819

Get this podcast on your
phone, FREE

Download Podbean app on App Store Download Podbean app on Google Play

Create your
podcast in
minutes

  • Full-featured podcast site
  • Unlimited storage and bandwidth
  • Comprehensive podcast stats
  • Distribute to Apple Podcasts, Spotify, and more
  • Make money with your podcast
Get started

It is Free

  • Podcast Services

    • Podcast Features
    • Pricing
    • Enterprise Solution
    • Private Podcast
    • The Podcast App
    • Live Stream
    • Audio Recorder
    • Remote Recording
    • Podbean AI
  •  
    • Create a Podcast
    • Video Podcast
    • Start Podcasting
    • Start Radio Talk Show
    • Education Podcast
    • Church Podcast
    • Nonprofit Podcast
    • Get Sermons Online
    • Free Audiobooks
  • MONETIZATION & MORE

    • Podcast Advertising
    • Dynamic Ads Insertion
    • Apple Podcasts Subscriptions
    • Switch to Podbean
    • YouTube to Podcast
    • Blog to Podcast
    • Submit Your Podcast
    • Podbean Plugins
    • Developers
  • KNOWLEDGE BASE

    • How to Start a Podcast
    • How to Start a Live Podcast
    • How to Monetize a Podcast
    • How to Promote Your Podcast
    • Mobile Podcast Recording Guide
    • How to Use Group Recording
    • Podcast Advertising 101
  • Support

    • Support Center
    • What’s New
    • Free Webinars
    • Podcast Events
    • Podbean Academy
    • Podbean Amplified Podcast
    • Badges
    • Resources
  • Podbean

    • About Us
    • Podbean Blog
    • Careers
    • Press and Media
    • Green Initiative
    • Affiliate Program
    • Contact Us
  • Privacy Policy
  • Cookie Policy
  • Terms of Use
  • Consent Preferences
  • Copyright © 2015-2025 Podbean.com