This project demonstrates how to gradually fade an LED's brightness up and down using Pulse Width Modulation (PWM) on an Arduino.
- Arduino board (e.g., Uno, Nano)
- LED
- 220-ohm resistor
- Breadboard
- Jumper wires
- Connect the longer leg (anode) of the LED to digital pin 9 on the Arduino.
- Connect the shorter leg (cathode) of the LED to one end of the 220-ohm resistor.
- Connect the other end of the resistor to the GND (ground) pin on the Arduino.
int led = 9;
: This variable stores the pin number where the LED is connected.int brightness = 0;
: This variable stores the current brightness level of the LED (from 0 to 255).int fadeAmount = 5;
: This variable determines the amount by which the brightness will change each loop iteration.
void setup()
: Thesetup()
function runs once when the program starts. Inside this function:pinMode(led, OUTPUT);
: This sets theled
pin as an output pin, meaning it will be used to control the LED.
void loop()
: Theloop()
function runs continuously aftersetup()
. Inside this function:analogWrite(led, brightness);
: This sets the LED's brightness using PWM. The value ofbrightness
can range from 0 (completely off) to 255 (fully on).brightness = brightness + fadeAmount;
: This line increments or decrements thebrightness
value byfadeAmount
to gradually change the LED's brightness.if (brightness <= 0 || brightness >= 255) { fadeAmount = -fadeAmount; }
: This checks if thebrightness
value has reached the maximum (255) or minimum (0) and reverses the direction of fading by changing the sign offadeAmount
.delay(30);
: This pauses the program for 30 milliseconds to create a smooth fading effect.
- Connect your Arduino board to your computer.
- Open the Arduino IDE.
- Copy and paste the provided code into a new sketch.
- Upload the sketch to your Arduino board.
- Watch the LED fade in and out continuously.
This project is open-source and available under the MIT License.
Enjoy experimenting with PWM and LED fading effects!