ENع
←PWM and analogWrite()
Lesson 16 · Interrupts, timers and PWM

PWM: dimming an LED

12 min10 steps5 questionsIntermediate
About this lesson

A microcontroller pin is either fully on or fully off, yet analogWrite() can dim an LED. The trick is pulse width modulation (PWM): switch the pin on and off about 980 times a second and change how long each “on” lasts. Follow pin 6 on an Arduino Uno: Timer0 counts 0 to 255 every 1,024 µs, the pin goes HIGH at 0 and LOW when the count matches the compare register OCR0A, and analogWrite() only writes that one number. It builds on the lesson “Hardware timers, prescalers and millis()”; the Circuits lesson on RC circuits shows how to smooth PWM into a steady voltage.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 16 · Interactive
01 / 10

A pin is on or off

A digital pin has two states. HIGH puts 5 V on pin 6 and the LED shines fully. LOW puts 0 V on it and the LED goes dark. There is no half-way setting. So how do we dim it?

digitalWrite(6, HIGH);   ->  5 V, LED fully on
digitalWrite(6, LOW);    ->  0 V, LED off
nothing in between: a digital pin is a switch
Loading figure…
or ← →
Read the lesson step by step
  1. A pin is on or off

    A digital pin has two states. HIGH puts 5 V on pin 6 and the LED shines fully. LOW puts 0 V on it and the LED goes dark. There is no half-way setting. So how do we dim it?

    digitalWrite(6, HIGH);   ->  5 V, LED fully on
    digitalWrite(6, LOW);    ->  0 V, LED off
    nothing in between: a digital pin is a switch
  2. Switch it on and off fast

    Switch the pin on and off about 980 times a second. Each on-off pair is one period. That is far too fast to see, so the LED looks steady but dimmer. This is PWM, pulse width modulation. Here it is slowed right down.

    PWM     pulse width modulation
    rate    976.5625 periods per second on pin 6
    period  1 / 976.5625 Hz = 1,024 µs
    here    on half of each period (analogWrite(6, 127))
    shown   slowed down a great deal
  3. The duty cycle sets brightness

    The duty cycle is the share of each period the pin is HIGH. At 50% the average is 2.50 V. Cut the HIGH part to about 25% and it drops to 1.27 V. The LED gets current a quarter of the time: dimmer.

    duty cycle = HIGH time / period
    average    = duty x 5 V
    50%    ->  2.50 V
    25.4%  ->  1.27 V
    same period, only the HIGH part changes
  4. Timer0 counts the period

    A timer makes the wave, not your code. On pin 6 it is Timer0, the one behind millis(). The prescaler gives it a tick every 4 µs, and TCNT0 counts 0 to 255. So one period is 256 × 4 µs = 1,024 µs.

    16,000,000 Hz / 64 = 250,000 ticks per second, 4 µs each
    TCNT0  0, 1, 2 ... 255, then 0 again  (fast PWM)
    period 256 x 4 µs = 1024 µs
    f = 16 MHz / (64 x 256) = 976.5625 Hz
    the reference rounds this to 980 Hz
  5. A compare register holds your number

    Next to the counter sits OCR0A, a compare register. Here it holds 64. On every tick, hardware checks: does TCNT0 equal OCR0A? Most ticks the answer is no. Once per period, when the count reaches 64, it is yes: a compare match.

    OCR0A   Output Compare Register A of Timer0
    value   64
    tick    TCNT0 == OCR0A ?   no, no, ... yes at 64
    one compare match per period
  6. HIGH at 0, LOW at match

    The timer drives pin 6 itself. When TCNT0 restarts at 0, the pin goes HIGH. At the compare match it goes LOW and stays LOW until the count wraps. That repeats every period, with no code running.

    TCNT0 = 0           pin 6 HIGH   (set at BOTTOM)
    TCNT0 = 64 (match)  pin 6 LOW    (cleared on compare match)
    TCNT0 65 .. 255      pin stays LOW
    datasheet: fast PWM, non-inverting mode
  7. analogWrite writes one number

    analogWrite(6, 64) does two small jobs. It stores 64 in OCR0A and connects pin 6 to the timer. Then it returns. Your code carries on and the timer keeps switching the pin, period after period.

    line 1   analogWrite(6, 64);
    core     pinMode(6, OUTPUT)
             sbi(TCCR0A, COM0A1)   connect pin 6 to Timer0
             OCR0A = 64            set the duty
             return: the CPU is free again
  8. A quarter of the time

    The pin is HIGH while the count is 0 to 64: 65 ticks out of 256. That is 25.4% of each 1,024 µs period, about a quarter. The average is 1.27 V, and at full speed the LED glows steadily, but dim.

    HIGH   counts 0 .. 64 = 65 ticks = 260 µs
    duty   65 / 256 = 25.4%
    avg    25.4% x 5 V = 1.27 V
    rate   976.5625 periods per second: no visible flicker
  9. A bigger number, a brighter LED

    analogWrite(6, 192) puts 192 in OCR0A. Now the match comes later, so the pin stays HIGH for 193 of 256 ticks: 75.4%. The average rises to 3.77 V and the LED is brighter. The period does not change.

    line 2   analogWrite(6, 192);
    OCR0A    64 -> 192
    HIGH     counts 0 .. 192 = 193 ticks
    duty     193 / 256 = 75.4%,  avg 3.77 V
    period   still 1024 µs
  10. Fading: change the number

    To fade, change the number step by step. This loop writes 0, 1, 2 ... 255, waiting 4 ms each time, so the LED brightens over about a second. At 0 and 255, analogWrite simply sets the pin LOW or HIGH.

    lines 3-6   v = 0 .. 255, one analogWrite each
    time        256 x 4 ms = 1,024 ms, about 1 s
    v = 0       digitalWrite(6, LOW): always off
    v = 255     digitalWrite(6, HIGH): always on
    
    // Arduino Uno R3: LED + resistor from pin 6 to GND
    void setup() {
      analogWrite(6, 64);    // about a quarter
      delay(2000);
      analogWrite(6, 192);   // about three quarters
      delay(2000);
    }
    
    void loop() {               // fade up, again and again
      for (int v = 0; v < 256; v++) {
        analogWrite(6, v);
        delay(4);
      }
    }

Quiz Unlocks after the last step.