Analog Write

PWM - Fading

PWM stands for Pulse Width Modulation. We can use this as an analog output. This is not really an analog output, but a digital approximation of analog. Basically it sends signals of varying lengths causing our led to be on and off for varying lengths of time. The net effect is that it will look dim. Not all pins are capable of PWM. The pins that are, are labeled on your boards (pins: 3,5,6,9,10,11).

You will use pin 9, instead of pin 13 for this lesson, so you will need a resistor to protect your led. Pin 13 doesn't do PWM (by default).

// Fading LED

// by BARRAGAN <>

int value = 0; // variable to keep the actual value

int ledpin = 9; // light connected to digital pin 9

void setup()


// nothing for setup


void loop()


for(value = 0 ; value <= 255; value+=5) // fade in (from min to max)


analogWrite(ledpin, value); // sets the value (range from 0 to 255)

delay(30); // waits for 30 milli seconds to see the dimming effect


for(value = 255; value >=0; value-=5) // fade out (from max to min)


analogWrite(ledpin, value);




PWM can have values ranging from 0 - 255 (256 possible states). When set to zero the led will be off, when set to 255 the led will be at its brightest.

In the sketch, you can see a "for" loop. It starts at zero and increases to 255 in increments of 5.

value+=5 means value=value+5 (it's the lazy way of writing it)

Additional Tasks

    1. Use the tri-color LED I gave you and make a color mixer. We made yellow, magenta, and cyan earlier by mixing red, green and blue. Can you make orange? What other colors can you make?

    2. Fade in and out from one color to another.

    3. Have the color fader respond to a button push.