Lesson 4: Fade
Lesson 4: Fade
Lesson: Fade
Objective: At the end of this lesson, you will be able to smoothly fade an LED in and out using Pulse Width Modulation (PWM) with an Arduino board.
Materials Required:
- Arduino board
- LED (any color)
- Jumper wires
- USB cable
Circuit Connections:
- Connect the longer leg (anode) of the LED to digital pin 9 on the Arduino board.
- Connect the shorter leg (cathode) of the LED to the ground (GND) pin on the Arduino board.
Arduino Code:
void setup() {
pinMode(9, OUTPUT); // Set digital pin 9 as output
}
void loop() {
for (int brightness = 0; brightness <= 255; brightness++) { // Fade in
analogWrite(9, brightness); // Set the LED brightness
delay(10); // Delay for smooth fading effect
}
for (int brightness = 255; brightness >= 0; brightness--) { // Fade out
analogWrite(9, brightness); // Set the LED brightness
delay(10); // Delay for smooth fading effect
}
}
Experiment Steps:
- Set up the circuit connections as described above.
- Connect the Arduino board to your computer using a USB cable.
- Open the Arduino IDE software and create a new sketch.
- Copy and paste the provided code into the Arduino IDE.
- Click the "Upload" button to upload the code to the Arduino board.
- Observe the LED smoothly fading in and out, creating a pulsating effect.
- Experiment with modifying the delay values and brightness ranges to adjust the fading speed and range.
Explanation:
The Arduino code above utilizes Pulse Width Modulation (PWM) to control the brightness of an LED. The pinMode()
function is used to set digital pin 9 as an output. Inside the loop()
function, a for
loop is used to increment the brightness
value from 0 to 255, gradually increasing the LED brightness and creating a fade-in effect. The analogWrite()
function is then used to set the brightness of the LED. A delay()
is added to create a smooth fading effect by introducing a small delay (10 milliseconds) between each increment.
After the fade-in loop is completed, another for
loop is used to decrement the brightness
value from 255 back to 0, gradually decreasing the LED brightness and creating a fade-out effect. The analogWrite()
and delay()
functions are used in a similar manner as in the fade-in loop.
By adjusting the delay values and the brightness ranges in the code, you can modify the fading speed and the range of brightness for different visual effects.
Challenge: Can you modify the code to fade the LED in and out at different speeds? For example, try increasing the delay value in the fade-in loop to slow down the fade-in effect, or decrease the delay value in the fade-out loop to speed up the fade-out effect.
Comments
Post a Comment