# Fade an LED in and Out

1,201

6

0

The following steps are experiments to illustrate how LEDs work. They illustrate how to dim an LED at an even rate and how to fade it in and out.

You will need:

• Arduino (I used a duo)
• 5 mm red LED
• 330 Ω Resistor (Not critical 330-560 Ω will work.)
• 22 Gauge Solid Hookup Wire

The parts needed for these experiments are included in all the Arduino startup kits.

### Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

## Step 1: Pulse Modulation Explained

LEDs always run at the same voltage regardless of the brightness. The brightness is determined by a square wave oscillator and the amount of time that the voltage is high determines the brightness. This is called Pulse Width Modulation (PWM). This is controlled by the Arduino analogWrite(pin, n) function where n has a value from 0 to 255. The analogWrite() outputs PWM, not true analog. If n=2 the LED will be twice as bright as n=1. The brightness always doubles when n doubles. So n=255 will be twice as bright as n=128.

The value of n is often expressed as a percentage called the duty cycle. The pictures show oscilloscope traces for 25, 50 and 75% duty cycles.

## Step 2: Un-even Dimming

Build the circuit like in the diagram. This is just like the circuit to blink an LED. It uses pin 9 because you need to use a PWM enabled pin.

Copy/Paste the sketch below into the Arduino IDE and run it.

You will notice that the brighter the LED is the slower it dims. As it gets near the dimmest it will be getting dimmer very fast.

```void setup()
{
pinMode(9, OUTPUT);
}

void loop()
{
int pin = 9;
for (int i = 255; i > -1; i--)
{
analogWrite(pin, i);
delay(10);
}

for (int i = 0; i < 256; i++)   {
analogWrite(pin, i);
delay(10);
}
}```

}

The next step shows how to dim the LED at a constant rate, and in one for statement.

## Step 3: Up and Down in One For()

For the LED to dim at a constant rate the delay() must increase at an exponential rate because half the duty cycle will always produce half the brightness. My first thought was to try to use the map() function but it is linear.

The line:

`int d = (16-i/16)^2;`

calculates the inverse square of the brightness to determine the length of the delay.

Copy/Paste the sketch below into the Arduino IDE and you will see that the LED will fade in and out at a constant rate.

```void setup()
{
pinMode(9, OUTPUT);
}

void loop()
{
int x = 1;
int pin = 9;
for (int i = 0; i > -1; i = i + x)
{
int d = (16-i/16)^2;
analogWrite(pin, i);
delay(d);
if (i == 255) x = -1;   // switch direction at peak
}
}```

Participated in the
LED Contest 2017

## Recommendations

• ### Internet of Things Class

22,809 Enrolled