To make an LED slowly get brighter and then dimmer again, you’ll need to control the LED’s brightness using Pulse Width Modulation (PWM), which is supported by several Arduino pins. You can achieve this by gradually changing the duty cycle of the PWM signal.
Components Needed:
- Arduino board (e.g., Uno, Nano)
- LED
- 220Ω resistor (to limit current)
- Breadboard (optional but useful for easier connections)
- Jumper wires
Circuit Setup:
- Connect the long leg (anode) of the LED to a PWM-capable pin on the Arduino (e.g., pin 9).
- Connect the short leg (cathode) of the LED to one leg of the 220Ω resistor.
- Connect the other leg of the resistor to the GND (ground) pin on the Arduino.
This limits the current flowing through the LED to prevent it from burning out.
Arduino Code:
// Pin where the LED is connected
const int ledPin = 9; // You can use any PWM-capable pin (3, 5, 6, 9, 10, 11 on most Arduinos)
// Variables for controlling the brightness
int brightness = 0; // Initial brightness level (0 - 255)
int fadeAmount = 5; // The amount to increase or decrease the brightness each time
void setup() {
// Set the LED pin as an output
pinMode(ledPin, OUTPUT);
}
void loop() {
// Set the LED brightness using PWM
analogWrite(ledPin, brightness);
// Change the brightness for the next loop
brightness = brightness + fadeAmount;
// Reverse the direction of the fade when the LED is fully bright or dim
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// Wait for a short amount of time to create a smooth fade effect
delay(30);
}
Explanation of the Code:
- Pin Declaration:
The LED is connected to pin9
, which is a PWM-capable pin. - Brightness Control:
Thebrightness
variable starts at0
(completely off) and increases byfadeAmount
in each loop. TheanalogWrite()
function controls the brightness of the LED by adjusting the PWM duty cycle. The value passed toanalogWrite()
can range from0
(off) to255
(maximum brightness). - Fade Logic:
If the brightness reaches either0
(dim) or255
(bright), the direction of fading is reversed by changing the sign offadeAmount
. This makes the LED go from bright to dim or dim to bright in a loop. - Smooth Transition:
Thedelay(30)
creates a short pause, which slows down the transition, making the fade effect smooth. You can adjust this delay to speed up or slow down the fading effect.
Result:
The LED will gradually get brighter, reach its maximum brightness, then slowly dim down to off, and this process will repeat.
Troubleshooting:
- LED not lighting up: Double-check your wiring to make sure the anode (long leg) is connected to the Arduino pin and the cathode (short leg) goes to the resistor and then to ground.
- Too bright or too dim: If the LED is too bright or too dim, adjust the
fadeAmount
or change the resistor value to limit the current properly.
This approach allows for a smooth and gradual transition of brightness, making the LED fade in and out.