Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท GPIO and Python

PWM: Dimming LEDs and Driving Servos

Understand pulse-width modulation on the Raspberry Pi: duty cycle, dimming an LED with PWMLED, driving a hobby servo with gpiozero, and hardware versus software PWM.

A GPIO pin is digital: it can be fully on or fully off, nothing in between. Yet you can dim an LED, set a motor speed or turn a servo to an exact angle from the same pin. The trick is pulse-width modulation, or PWM. The pin flips on and off so fast that the eye, or a motor, only notices the average. This lesson explains the idea and applies it to LEDs and servos.

How PWM works

A PWM signal repeats in cycles. In each cycle the pin is high for a fraction of the time and low for the rest. The fraction that is high is the duty cycle:

  • 0 percent duty: always low, LED off.
  • 50 percent duty: high half the time, LED at about half brightness.
  • 100 percent duty: always high, LED fully on.

The frequency is how many cycles happen per second. For LEDs a frequency of a few hundred hertz is enough to look steady. Humans see the average brightness, so a 25 percent duty cycle looks like a dim light.

Duty cycle

0 % Always low: off
50 % Half on: half bright
1 / 2

Dimming an LED

With gpiozero the PWMLED class takes the same wiring as LED and adds a value between 0.0 and 1.0 (read-only):

Python
from gpiozero import PWMLED
from time import sleep

led = PWMLED(17)
led.value = 0.25     # dim
sleep(1)
led.value = 1.0      # full brightness
sleep(1)
led.pulse()          # smooth fade in and out in the background
sleep(5)

led.pulse(fade_in_time=1, fade_out_time=1) breathes the LED. A simple manual fade is a loop that raises the value in small steps:

Python
for step in range(0, 101):
    led.value = step / 100
    sleep(0.02)

Human eyes judge brightness on a curve, not linearly, so a fade from 0 to 1 looks like it spends most of the time near full brightness. A gamma correction (raising the value to a power of about 2.2) makes the steps look even.

Simulating PWM

The stand-in draws a PWM waveform as text so you can see what duty cycle means, and computes the average voltage a pin delivers.

Python Stand-in: draw a PWM waveform

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 input()), it gets the next line from this box.

Fading with gamma

This stand-in shows the difference between a linear fade and a gamma-corrected one by printing both sequences.

Python Stand-in: linear versus gamma fade

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 input()), it gets the next line from this box.

With gamma correction the early steps change the real duty cycle only a little, which looks smoother to the eye.

Servo motors

A hobby servo is a small motor with a gear train and a position sensor. You tell it an angle and it moves there and holds. Its control signal is also PWM, but with specific timing: a pulse every 20 ms (50 Hz) whose width sets the angle. About 1.0 ms means one end of the range, 1.5 ms the middle and 2.0 ms the other end (many servos accept 0.5 to 2.5 ms for a wider sweep).

A servo has three wires: brown or black (ground), red (power, usually 5 V) and orange or yellow (signal). Power a small servo from a separate 5 V supply if it twitches, and connect that supply's ground to the Pi's ground. Never power several servos from the Pi's 5 V pin.

With gpiozero (read-only):

Python
from gpiozero import Servo
from time import sleep

servo = Servo(18)          # GPIO18, signal wire
servo.min()                # one end
sleep(1)
servo.mid()                # center
sleep(1)
servo.max()                # other end
servo.value = 0.5          # between -1 (min) and 1 (max)

For jitter-free servo control, the pigpio pin factory (or hardware PWM on GPIO12, 13, 18 and 19) is better than software timing, because Linux is not a real-time system and can delay a pulse by a fraction of a millisecond. The AngularServo class lets you ask for an angle directly:

Python
from gpiozero import AngularServo
servo = AngularServo(18, min_angle=-90, max_angle=90)
servo.angle = 45

Mapping an angle to a pulse width

The stand-in converts an angle to the pulse width and duty cycle for a 50 Hz servo signal.

Python Stand-in: servo angle to pulse width

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 input()), it gets the next line from this box.

Hardware versus software PWM

Hardware PWM is produced by dedicated circuits in the chip and is perfectly steady, but only a few pins (GPIO12, GPIO13, GPIO18, GPIO19) support it, and channels share timing. Software PWM works on any pin but is generated by the CPU, so heavy load can cause flicker or servo jitter. For LEDs software PWM is fine; for servos and motors prefer hardware PWM.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a 25 percent duty cycle mean?

    Duty cycle is the fraction of time the signal is high.
  2. 2. Which gpiozero class dims an LED?

    PWMLED accepts a value between 0 and 1 for brightness.
  3. 3. A standard hobby servo expects a pulse every how many milliseconds?

    The pulse width of 1 to 2 ms inside a 20 ms period sets the angle.
  4. 4. Why prefer hardware PWM for servos?

    Software PWM can jitter when Linux is busy.

Summary

  • PWM switches a pin fast; the duty cycle sets the average power.
  • PWMLED dims an LED; gamma correction makes fades look even.
  • Servos use a 50 Hz signal whose 0.5 to 2.5 ms pulse width sets the angle.
  • Use hardware PWM or the pigpio factory for steady servos, and power them separately.

Next: Buses: I2C, SPI and UART