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.
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  Fading4
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 200812
13  by David A. Mellis14
15  modified 30 Aug 201116
17  by Tom Igoe18
19  This example code is in the public domain.20
21  https://www.arduino.cc/en/Tutorial/Fading22
23*/24
25int ledPin = 9;    // LED connected to digital pin 926
27void setup() {28
29  // nothing happens in setup30}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 effect43
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 effect57
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
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.
 
  