Fading LED With Analog Output

by circuits in Circuits > Arduino

8602 Views, 1 Favorites, 0 Comments

Fading LED With Analog Output

fade.gif

Let's learn to adjust an LED's brightness using one of the Arduino's analog outputs. You already learned how to use Arduino's digital i/o pins to send HIGH and LOW signals to an LED, but some of these pins are capable of simulating a signal somewhere in between. These pins are labeled on the Arduino Uno with tildes (~) next to the pin number. We'll connect an LED to one of these special pins and compose a simple program to slowly fade the LED brighter and dimmer. Here in Tinkercad Circuits, you can explore the sample circuit (click Start Simulation to watch the LED fade off and on) and build your own right next to it. Optionally grab your electronics supplies and build along with a physical Arduino Uno, USB cable, breadboard, LED, resistor (any value from 100-1K ohms will do), and some breadboard wires. We'll learn about the oscilloscope (signal graph) later on in this lesson.

  1. Continue to the next step.

Build the Circuit

fadestarter.jpg
arduino-class-35.jpg
Screen Shot 2018-04-06 at 2.32.03 PM.png

Take a look at the circuit in the workplane. Remember that the breadboard rows are connected inside, so you can plug in components and wires to make quick temporary connections. Since you're still getting used to the breadboard, it's useful to take a look at the free-wired version of this sample circuit.

  1. Identify the LED, resistor, and wires connected to the Arduino in the Tinkercad Circuits workplane.
  2. Drag an Arduino Uno and breadboard from the components panel to the workplane, next to the existing circuit.
  3. Connect breadboard power (+) and ground (-) rails to Arduino 5V and ground (GND), respectively, by clicking to create wires.
  4. Connect the LED cathode (negative, shorter leg) to one leg of a resistor (anywhere from 100-1K ohms is fine).

    HINT:

    The resistor can go in either orientation because resistors aren't polarized, unlike LEDs, which must be connected in a certain way to function.

  5. Connect other resistor leg to ground.
  6. Connect LED anode (positive, longer leg) to Arduino pin 9.
  7. Continue to the next step.

Build Brightness Adjustment Code With Blocks

code blocks 2.gif

Let's go over the simple program responsible for fading the LED, which can be built in code blocks or composed using the Arduino programming language. Click the "Code" buttonto open the code blocks editor. While the sample circuit is selected, that Arduino Uno's code is shown in the code editor. Click on the Arduino Uno you added to see its code, or select it from the dropdown menu "1 (Arduino Uno R3)". You can toggle back and forth to compare the sample code with your own.

  1. The Arduino comes preloaded with the Blink sketch. Remove these blocks to start fresh.
  2. Click on the Control category and drag out the "Count up by..." block. Set it to count up by five. Click the dropdown next to "for" and select "rename variable...", then rename it to "brightness". Adjust the "from" and "to" values to 0 and 255, respectively.
  3. Inside the counting loop, add an analog output block "set pin [3] to (0)", and adjust it to pin 9. Navigate to Variables and drag the brightness block to the output block (to replace the zero) to set pin 9 to the current value of brightness, which changes over the course of the counting loop.
  4. Add a wait block (also in the Control category), and set it to 30 milliseconds. This gives time for the light to shine at each brightness level so you have time to see it before it changes. The duration of this block can be changed to slow down or speed up the fading effect.
  5. The counting loop you created fades the LED from off to all the way on. To fade the LED back off again, we have to create another counting loop. Either drag a new counting loop into the editor, or duplicate this one (right click), and this time change it to count down, start with 255, and go down to zero.
  6. Continue to the next step.

Brightness Adjustment Arduino Code Explained

In the code text editor, you can see the Arduino code generated by the code blocks.

  1. /*
      Fade
      This example shows how to fade an LED on pin 9
      using the analogWrite() function.
    
      The analogWrite() function uses PWM, so if  you
      want to change the pin you're using, be  sure to
      use another PWM capable pin. On most Arduinos,
      the PWM pins are identified with   a "~" sign,
      like ~3, ~5, ~6, ~9, ~10 and ~11.
    */
    

    This first section is a comment, describing what the program does. We'll define and explore PWM in the next steps.

  2. int brightness = 0;
    
    void setup()
    {
      pinMode(9, OUTPUT);
    }
    

    The main body of the program starts out by creating a variable called brightness and sets it equal to zero, then inside the setup() pin 9 is initialized as an output.

  3. void loop()
    {
      for (brightness = 0; brightness <= 255; brightness += 5) {
        analogWrite(9, brightness);
        delay(30); // Wait for 30 millisecond(s)
      }
      for (brightness = 255; brightness >= 0; brightness -= 5) {
        analogWrite(9, brightness);
        delay(30); // Wait for 30 millisecond(s)
      }
    }

    The program's loop uses two for loops to count up from 0 to 255 by increments of 5. The analogWrite() function takes two arguments: the Arduino pin number (9 in our case), and a value between 0 (off) and 255 (all the way on).

  4. Continue to the next step.

Fade Circuit Starter

Screen Shot 2017-11-29 at 5.54.36 PM.png

This circuit is also available as a circuit starter. You can use this circuit starter anytime you want to fade an LED.

  1. Grab this circuit and code combo any time using the starter available in the components panel (dropdown menu -> Starters -> Arduino).
  2. HINT:

    Notice how the resistor in this version is "upstream" of the LED, connected between power and the LED instead of the LED and ground. The resistor can be placed on either side of the LED.

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

Pulse Width Modulation

fade90.gif

The Arduino board is only capable of generating digital signals (HIGH and LOW), but analogWrite(); simulates the appearance of varying brightness between on and off using pulse width modulation (PWM). The LED flashes on and off very quickly, and your eye interprets a dimmer light. The ratio of time the LED spends on vs. off determines how bright or dim the LED appears.

Pulse width modulation (PWM) creates an oscillating digital signal, alternately driven high and low in a repeating pattern. Each high to low to high period of time is called a cycle.

  1. Click Start Simulation. You should see an oscillating digital signal on the oscilloscope like the animation above.
  2. Notice that for each cycle, the width of the HIGH and LOW portions of the graph are changing, hence the term pulse width modulation, or PWM for short.
  3. Identify the other digital pins on the Arduino Uno capable of PWM, marked with a ~: 3, 5, 6, 9, 10, and 11.
  4. Continue to the next step.

Build the Physical Circuit (Optional)

fade.gif

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. Wire up the Arduino Uno circuit by plugging in components and wires to match the connections shown here in Tinkercad Circuits. For a more in-depth walk-through on working with your physical Arduino Uno board, check out the free Instructables Arduino class (a similar circuit is described in the second lesson).
  2. 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.
  3. Plug in your USB cable and select your board and port in the software’s Tools menu.
  4. Upload the code and watch your LED fade!
  5. Continue to the next step.

Next, Try...

lesson-thumbnail.jpg

Now that you know how to fade an LED using pulse width modulation (PWM), you're ready to try other Arduino exercises that utilize the analogWrite() function.

  • RGB LEDs use analogWrite() to mix ratios of red, green, and blue LEDs. Simultaneously controlling the brightness of one LED of each of these colors can create almost any color of light.
  • You can use analogWrite() to control the speed of a DC motor.
  • The tone library uses analogWrite() to generate different musical notes with a piezo buzzer.
  1. Experiment with changing the values in the code's counting loops, and notice the effect on the resulting simulation. Can you make the fading animation go faster or slower?
  2. Explore analog outputs more with the next lesson about RGB LEDs.