Project 1.07 LED Fade
This is a simple example of using pulse-width modulation (PWM) to make LED1 fade in and out. Remember that computers have a hard time creating analog signals, but they can turn things on and off very quickly. Upload this sketch and watch LED1 fade on and off.
Concepts: pulse-width modulation, AnalogWrite
Circuits:
Concepts: pulse-width modulation, AnalogWrite
Circuits:
We’re going to use two additional variables in this sketch. The variable bright sets the brightness of LED1 while goTo sets how we change bright during each cycle of the loop() block:
int bright = 5;
int goTo = 1;
As in the previous sketches, we need to set LED1 as an OUTPUT in the setup() block:
void setup(){
pinMode(LED1,OUTPUT);
}
We control what percentage of time that LED1 remains on (or the duty cycle) using the analogWrite statement. The first argument is the pin number and the second argument is the duty cycle. The duty cycle ranges from 0 (always off) to 255 (always on).
void loop(){
analogWrite(13,bright);
In each cycle of the loop() block, we increment bright by adding goTo. The initial value of goTo is 1:
bright = bright + goTo;
Once bright gets close to zero or above 255, we change the sign of goTo by resetting its value to -1 if it’s currently 1 or 1 if it’s currently -1. This is accomplished by setting its new value to its old value times – 1. When goTo is -1, it causes the value of bright to decrease, which then makes LED1 dimmer:
if(bright > 255 || bright < 5) goTo = goTo*-1;
A short delay and then it’s back to the top of the loop:
delay(5);
}
int bright = 5;
int goTo = 1;
As in the previous sketches, we need to set LED1 as an OUTPUT in the setup() block:
void setup(){
pinMode(LED1,OUTPUT);
}
We control what percentage of time that LED1 remains on (or the duty cycle) using the analogWrite statement. The first argument is the pin number and the second argument is the duty cycle. The duty cycle ranges from 0 (always off) to 255 (always on).
void loop(){
analogWrite(13,bright);
In each cycle of the loop() block, we increment bright by adding goTo. The initial value of goTo is 1:
bright = bright + goTo;
Once bright gets close to zero or above 255, we change the sign of goTo by resetting its value to -1 if it’s currently 1 or 1 if it’s currently -1. This is accomplished by setting its new value to its old value times – 1. When goTo is -1, it causes the value of bright to decrease, which then makes LED1 dimmer:
if(bright > 255 || bright < 5) goTo = goTo*-1;
A short delay and then it’s back to the top of the loop:
delay(5);
}