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:

  1. Connect the longer leg (anode) of the LED to digital pin 9 on the Arduino board.
  2. 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:

  1. Set up the circuit connections as described above.
  2. Connect the Arduino board to your computer using a USB cable.
  3. Open the Arduino IDE software and create a new sketch.
  4. Copy and paste the provided code into the Arduino IDE.
  5. Click the "Upload" button to upload the code to the Arduino board.
  6. Observe the LED smoothly fading in and out, creating a pulsating effect.
  7. 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.

Link for testing and simulating the project

Comments

Popular Posts