Fading

Use an analog output (PWM pin) to fade an LED.

This example demonstrates the use of analog output (Pulse Width Modulation (PWM)) to fade an LED. PWM is a technique for getting an analog-like behavior from a digital output by switching it off and on very fast and with different ratio between on and off time.

Hardware Required

  • Arduino board

  • LED

  • 220 ohm resistor

  • hook-up wires

  • breadboard

Circuit

An LED connected to digital output pin 9 through a 220 ohm resistor.

circuit

Schematic

schematic

Code

In this example two loops are executed one after the other to increase and then decrease the value of the output on pin 9.

1/*
2
3 Fading
4
5 This example shows how to fade an LED using the analogWrite() function.
6
7 The circuit:
8
9 - LED attached from digital pin 9 to ground.
10
11 created 1 Nov 2008
12
13 by David A. Mellis
14
15 modified 30 Aug 2011
16
17 by Tom Igoe
18
19 This example code is in the public domain.
20
21 https://www.arduino.cc/en/Tutorial/Fading
22
23*/
24
25int ledPin = 9; // LED connected to digital pin 9
26
27void setup() {
28
29 // nothing happens in setup
30}
31
32void loop() {
33
34 // fade in from min to max in increments of 5 points:
35
36 for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
37
38 // sets the value (range from 0 to 255):
39
40 analogWrite(ledPin, fadeValue);
41
42 // wait for 30 milliseconds to see the dimming effect
43
44 delay(30);
45
46 }
47
48 // fade out from max to min in increments of 5 points:
49
50 for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
51
52 // sets the value (range from 0 to 255):
53
54 analogWrite(ledPin, fadeValue);
55
56 // wait for 30 milliseconds to see the dimming effect
57
58 delay(30);
59
60 }
61}

Learn more

You can find more basic tutorials in the built-in examples section.

You can also explore the language reference, a detailed collection of the Arduino programming language.

Last revision 2015/07/29 by SM

Contribute to Arduino

Join the community and suggest improvements to this article via GitHub. Make sure to read out contribution policy before making your pull request.

Missing something?

Check out our store and get what you need to follow this tutorial.

Suggest Changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.