Document directory
- Fading
- Hardware required
- Circuit
- Schematic
- Code
Fading
Demonstrates the use of the analogwrite () function in fading an led off and on. analogwrite uses pulse width modulation (PWM), turning a digital pin on and off very quickly, to create a fading effect.
Hardware required
- Arduino Board
- Breadboard
- A LED
- A 220 ohm resistor
Circuit
ConnectAnode(The longer, positive leg) of your led to digital output pin 9 on your Arduino through a 220-ohm resistor. ConnectCathode(The shorter, negative leg) directly to ground.
Click the image to enlarge
Schematic
Click the image to enlarge
Code
After declaring pin 9 to be yourledPin
, There is nothing to do insetup()
Function of your code.
TheanalogWrite()
Function that you will be using in the main loop of your code requires two arguments: one telling the function which pin to write to, and one indicating what PWM value to write.
In order to fade your led off and on, gradually increase your PWM value from 0 (all the way off) to 255 (all the way on ), and then back to 0 once again to complete the cycle. in the sketch below, the PWM value is set using a variable calledbrightness
. Each time through the loop, it increases by the value of the VariablefadeAmount
.
Ifbrightness
Is at either extreme of its value (either 0/255), thenfadeAmount
Is changed to its negative. In other words, iffadeAmount
Is 5, then it is set to-5. If it's 55, then it's set to 5. The next time through the loop, this change causesbrightness
To change direction as well.
analogWrite()
Can change the PWM value very fast, so the delay at the end of the sketch controls the speed of the fade. Try changing the value of the delay and see how it changes the program.
(:div class=code :)
/*
Fade
This example shows how to fade an LED on Pin 9
Using the analogwrite () function.
This example code is in the public domain.
*/
Int brightness = 0; // how bright the LED is
Int fadeamount = 5; // how to specify points to fade the led
Void setup (){
// Declare pin 9 to be an output:
Pinmode (9, output );
}
Void loop (){
// Set the brightness of Pin 9:
Analogwrite (9, brightness );
// Change the brightness for next time through the loop:
Brightness = brightness + fadeamount;
// Reverse the direction of the fading at the ends of the fade:
If (brightness = 0 | brightness = 255 ){
Fadeamount =-fadeamount;
}
// Wait for 30 milliseconds to see the dimming Effect
Delay (30 );
}