How to Fade LED in Arduino: Simple PWM Example
To fade an LED in Arduino, connect the LED to a PWM-capable pin and use
analogWrite(pin, value) where value ranges from 0 (off) to 255 (fully on). Gradually change this value in a loop to create a smooth fading effect.Syntax
The main function to control LED brightness is analogWrite(pin, value).
pin: The Arduino pin connected to the LED (must support PWM).value: Brightness level from 0 (off) to 255 (full brightness).
Use a loop to change value gradually for fading.
arduino
analogWrite(pin, value);
Example
This example fades an LED connected to pin 9 smoothly from off to fully on and back repeatedly.
arduino
const int ledPin = 9; // PWM pin connected to LED void setup() { pinMode(ledPin, OUTPUT); } void loop() { // Fade in from 0 to 255 for (int brightness = 0; brightness <= 255; brightness++) { analogWrite(ledPin, brightness); delay(10); // Wait 10ms for visible fade } // Fade out from 255 to 0 for (int brightness = 255; brightness >= 0; brightness--) { analogWrite(ledPin, brightness); delay(10); } }
Output
LED brightness smoothly increases from off to fully on, then decreases back to off repeatedly.
Common Pitfalls
Common mistakes when fading an LED include:
- Using a pin that does not support PWM (LED will only turn fully on or off).
- Not setting the pin mode to
OUTPUTinsetup(). - Using
digitalWrite()instead ofanalogWrite()for fading. - Changing brightness too fast or too slow, making the fade look abrupt or too slow.
arduino
/* Wrong: Using digitalWrite for fading (LED will not fade smoothly) */ const int ledPin = 9; void setup() { pinMode(ledPin, OUTPUT); } void loop() { for (int brightness = 0; brightness <= 255; brightness++) { digitalWrite(ledPin, brightness > 127 ? HIGH : LOW); // Incorrect usage fixed delay(10); } } /* Right: Use analogWrite for smooth fading */ // See example section for correct code.
Quick Reference
Tips for fading LED on Arduino:
- Use PWM pins (marked with ~ on Arduino boards).
- Use
analogWrite()to set brightness. - Brightness values range from 0 to 255.
- Use delays between brightness changes for smooth fading.
- Always set pin mode to
OUTPUTinsetup().
Key Takeaways
Use PWM pins and analogWrite() to control LED brightness smoothly.
Brightness values range from 0 (off) to 255 (full brightness).
Gradually change brightness in a loop with small delays for fading effect.
Set pin mode to OUTPUT before using analogWrite().
Avoid using digitalWrite() for fading as it only turns LED fully on or off.