Zed-King Institute

    Arduino LED Fade Using PWM (analogWrite)

    mediumPWMArduino (C++)

    PWM switches a pin on and off very fast; the share of "on" time sets how bright the LED looks.

    The question

    An LED is on PWM pin 10. Make it fade in from 0 to 255 and then fade out back to 0, changing the brightness by 1 each step with a 20 ms delay.

    The sketch

    sketch.ino

    void setup() {
      pinMode(10, OUTPUT);
    }
    
    void loop() {
      for (int b = 0; b <= 255; b += 1) {
        analogWrite(10, b);
        delay(20);
      }
      for (int b = 255; b >= 0; b -= 1) {
        analogWrite(10, b);
        delay(20);
      }
    }

    Wiring

    LED → 220Ω → pin 10 (a ~ PWM pin); cathode → GND.

    How it works

    1. 1Only pins marked ~ (3, 5, 6, 9, 10, 11 on an Uno) support PWM.
    2. 2analogWrite(pin, value) takes 0 (off) to 255 (full brightness).
    3. 3One for loop counts up to fade in, a second counts down to fade out.

    Common mistakes

    • Using a non-PWM pin such as 7 — the LED only switches fully on or off.
    • Going above 255, which wraps around and makes the LED flicker.

    Now solve a similar question yourself

    A new Arduino question every time, checked instantly.

    Practice questions