Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Analog and PWM

PWM and analogWrite

Understand pulse width modulation: duty cycle, analogWrite values 0-255, PWM pins and frequencies, fading an LED, motor speed, servo basics and why PWM is not true analog.

Arduino pins can only be HIGH or LOW, yet analogWrite() seems to dim LEDs and slow motors. The trick is pulse width modulation (PWM): switch the pin on and off so quickly that the load sees only the average. A pin that is HIGH for a quarter of the time looks like a quarter of full power. This lesson explains duty cycle, the numbers behind analogWrite() and the limits of the technique.

Duty cycle

A PWM signal repeats at a fixed frequency. In each period the pin is high for a fraction of the time called the duty cycle:

TEXT
duty cycle = time HIGH / period ร— 100%
average voltage = duty cycle ร— supply voltage

At 100% the pin is always high (5 V). At 50% it is high half the time, averaging 2.5 V. At 0% it is always low.

TEXT
 25%:  |โ€พโ€พ|______|โ€พโ€พ|______|โ€พโ€พ|______
 50%:  |โ€พโ€พโ€พโ€พ|____|โ€พโ€พโ€พโ€พ|____|โ€พโ€พโ€พโ€พ|____
 75%:  |โ€พโ€พโ€พโ€พโ€พโ€พ|__|โ€พโ€พโ€พโ€พโ€พโ€พ|__|โ€พโ€พโ€พโ€พโ€พโ€พ|__

An LED responds fast, but your eye averages the flicker above about 100 Hz, so it simply looks dimmer. A motor's inertia and coil inductance smooth the pulses into a lower speed.

analogWrite

C++
analogWrite(pin, value);   // value is 0..255

value 0 is always low, 255 is always high, and 127 is about 50%. The duty cycle is value / 255. Only the pins marked with ~ on the Uno (3, 5, 6, 9, 10, 11) have PWM hardware; a call on another pin just writes HIGH for values of 128 or more and LOW below. No pinMode() call is strictly needed, but it is good style to set OUTPUT.

The default frequencies on an Uno are about 490 Hz (pins 3, 9, 10, 11) and about 980 Hz (pins 5 and 6, which share Timer0 with millis()). Other boards differ: ESP32 lets you choose frequency and resolution with its LEDC functions.

C Stand-in: duty cycle and average voltage for analogWrite values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Fading an LED

Read-only sketch with a smooth fade up and down:

C++
const int ledPin = 9;
int brightness = 0;
int step = 5;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  analogWrite(ledPin, brightness);
  brightness += step;
  if (brightness <= 0 || brightness >= 255) {
    step = -step;            // reverse direction at the ends
  }
  delay(30);
}

The stand-in draws the same fade as a bar chart so you can see the turn-around at both ends:

C Stand-in: a fade up and down

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Perceived brightness is not linear

Your eye perceives brightness roughly logarithmically, so a duty cycle of 50% looks much brighter than "half". A fade with equal steps looks fast at the dim end and slow at the bright end. A gamma correction table (a curve around x^2.2) makes fades look even. A cheap approximation squares the value (shown below):

C Stand-in: linear versus gamma-corrected brightness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

We used x * x as a cheap gamma of 2. A real gamma curve of about 2.2 is usually precomputed into a 256-entry table stored in flash, because pow() is slow on an 8-bit chip.

Motors, servos and other uses

  • DC motor speed: connect the motor through a transistor or motor driver (pin current limits), and send PWM to its input. Add a flyback diode. Speeds below about 20% may not start the motor.
  • RGB LED color: three PWM pins mix any color; see the LED practice items later.
  • Servos use a different PWM: a pulse of 1 to 2 ms repeated every 20 ms sets the angle. Use the Servo library, not analogWrite().
  • Buzzers: tone(pin, frequency) makes a square wave of the pitch you want.
  • Fake analog output: passing PWM through a resistor and capacitor (an RC filter) gives a smooth DC voltage, a poor man's DAC.

Limits and gotchas

  • PWM is not true analog: the pin still only switches between 0 V and 5 V. A voltmeter shows the average, but a circuit that reacts to the instant voltage will not.
  • On pins 5 and 6, very small duty values come out slightly longer than expected, because Timer0 is also used for millis() and delay().
  • Changing timer frequency (to remove motor whine) affects millis()/delay() if you change Timer0. Use Timer1 or Timer2 pins instead (9, 10, 3, 11).
  • Using the tone() or Servo library can disable PWM on certain pins (on the Uno, tone() interferes with PWM on pins 3 and 11).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does analogWrite(9, 64) produce on an Uno?

    64 / 255 is about 25%; the pin still only switches between 0 and 5 V.
  2. 2. Which pins support analogWrite on the Uno?

    Only the pins connected to timer outputs (marked ~) generate PWM.
  3. 3. Why does an LED fade look uneven with equal PWM steps?

    Perception is roughly logarithmic, so gamma correction gives smoother-looking fades.
  4. 4. What is the average voltage of a 5 V pin at 40% duty cycle?

    0.4 x 5 V = 2 V.

Summary

  • PWM switches a pin quickly; the duty cycle sets the average power.
  • analogWrite(pin, 0..255) works on the ~ pins; about 490 Hz or 980 Hz on an Uno.
  • Fade LEDs, set motor speed (through a driver) and mix RGB colors with it.
  • Use gamma correction for visually even fades.
  • PWM is still digital; servos need their own library, and timers are shared with other functions.

Next: map(), constrain() and Scaling Values