Raspberry Pi PWM: Hardware vs Software PWM (Python, C++)

In this tutorial, we’ll discuss Raspberry Pi PWM on the Raspberry Pi 5: the hardware PWM pins, software PWM on any GPIO pin, and how the two compare. You’ll learn how to fade an LED with software PWM in Python (gpiozero) and C++ (lgpio), and how to enable and use the Raspberry Pi 5 hardware PWM with the device tree overlay and the sysfs interface, in Python and C++.

We’ll answer the question: which pins give you Raspberry Pi hardware PWM, and when is software PWM good enough? You’ll see my oscilloscope measurements of the jitter of each method with the CPU idle and fully loaded, the frequency range, the duty cycle accuracy, and the CPU use, plus the real error messages you’ll meet along the way. Without further ado, let’s get right into it!

Note: All examples in this tutorial are tested with: Raspberry Pi 5 (8GB) with Raspberry Pi OS (64-bit) Trixie.

This tutorial assumes your Raspberry Pi is set up with Raspberry Pi OS and reachable over SSH. If it isn’t, follow the Raspberry Pi Setup Guide first.

Raspberry Pi PWM Example (Raspberry Pi 5)

The Raspberry Pi 5 has 4 hardware PWM channels on the 40-pin header: GPIO12, GPIO13, GPIO18, and GPIO19 (RP1 PWM0 channels 0 to 3). Every other GPIO pin can still do software PWM. For an LED, software PWM with gpiozero needs no setup at all; for servos, motors, and anything timing-sensitive, use hardware PWM through the kernel’s sysfs interface after one line in config.txt.

Python Code example (software PWM, any GPIO pin, gpiozero)

For hardware PWM, add dtoverlay=pwm,pin=12,func=4 to /boot/firmware/config.txt and reboot once. Then:

C++ Code example (hardware PWM on GPIO12, sysfs)

Both set a 25% duty cycle: the Python one at gpiozero’s default 100Hz on GPIO17, the C++ one at 1kHz on GPIO12. Build the C++ one with g++ -std=c++17 quick_hw_pwm.cpp -o quick_hw_pwm. Neither needs sudo. The rest of this tutorial explains how PWM works, the overlay and the sysfs files, the complete examples in both languages, and the measurements that show the difference between software and hardware PWM.


Raspberry Pi PWM Explained

PWM (Pulse Width Modulation) switches a GPIO pin between 0v and 3.3v at a fixed frequency and changes how long the pin stays HIGH in each period. The Raspberry Pi has no analog output (no DAC) on its header, so PWM is how it dims an LED, sets a motor’s speed, or positions a servo. Two numbers describe a PWM signal:

  • Frequency (f = 1 / T): how many periods per second. 1kHz means one period every 1ms.
  • Duty cycle: the HIGH time divided by the period, in percent. 25% at 1kHz means 250µs HIGH, then 750µs LOW.

A load that is slower than the PWM frequency, like an LED seen by your eye or a motor’s inertia, responds to the average voltage: 3.3v × duty cycle. At 25% duty the average is 3.3v × 0.25 = 0.825v.

Raspberry Pi PWM explained: period, high time, duty cycle and average voltage at 25%, 50% and 75% duty on a 3.3v GPIO pin

This animation shows the same idea on an LED: as the duty cycle rises, the average voltage rises and the LED looks brighter. The LED is fully on or fully off at any instant; it just switches faster than your eye can follow.

PWM duty cycle vs LED brightness animation: the duty cycle sweeps from 5% to 95% and the average voltage and LED brightness follow

If PWM is new to you, my Arduino PWM tutorial covers the same concept on a microcontroller. The difference on the Raspberry Pi is that Linux, not your program alone, decides when code runs, and that is why the choice between software and hardware PWM matters.


Raspberry Pi 5 PWM Pins

The Raspberry Pi 5 routes its hardware PWM to four header pins, and each pin has its own channel of the RP1 chip’s PWM0 block. I read this table from my board with pinctrl funcs 12,13,18,19:

GPIOHeader PinRP1 PWM Channelpinctrl Functionsysfs Channel (pwmchip0)Other Functions on the Pin
GPIO1232PWM0_CHAN0a0pwm0UART4 TX, I2C2 SDA, SPI5
GPIO1333PWM0_CHAN1a0pwm1UART4 RX, I2C2 SCL, SPI5
GPIO1812PWM0_CHAN2a3pwm2I2S0 SCLK, SPI1 CE0
GPIO1935PWM0_CHAN3a3pwm3I2S0 WS, SPI1 MISO

So all four pins can run different frequencies and duty cycles at the same time. On the Raspberry Pi 4 and older, the Broadcom PWM block has only two channels: GPIO12 and GPIO18 share PWM0, and GPIO13 and GPIO19 share PWM1, per the overlay README. If you use an I2S audio HAT, keep GPIO18 and GPIO19 for it and use GPIO12 and GPIO13 for PWM. The positions of these pins on the header are in my Raspberry Pi 5 pinout guide.

Note: The Raspberry Pi 5 fan header is driven by a second PWM block, RP1 PWM1 (channel 3 on GPIO45, 24kHz, from the board’s device tree). It is not one of the four header channels, so using GPIO12, 13, 18, or 19 never affects the fan.

Any other GPIO (0 to 27) can output software PWM. The Raspberry Pi 5 also has a pwm-pio overlay that generates PWM on any of those pins with the RP1’s PIO blocks (up to four outputs); it’s beyond the scope of this tutorial.


Hardware PWM vs Software PWM on the Raspberry Pi

Software PWM toggles the pin from a program thread: a library sleeps until the next edge, wakes up, and writes the pin. Hardware PWM hands the period and duty cycle to a counter inside the RP1 chip, which then drives the pin without any help from the CPU. This diagram shows both paths on the Raspberry Pi 5:

Raspberry Pi 5 software PWM vs hardware PWM: lgpio thread and /dev/gpiochip0 versus sysfs, the pwm-rp1 kernel driver and the RP1 PWM0 block

With software PWM, every edge waits for Linux to schedule the lgpio thread, so the edges move when the CPU is busy. With hardware PWM, the edges come from the RP1’s 50MHz counter. Here is how the two compare on my Raspberry Pi 5:

PropertySoftware PWM (gpiozero, lgpio)Hardware PWM (RP1, sysfs)
PinsAny GPIO 0 to 27GPIO12, 13, 18, 19 only
SetupNoneOne dtoverlay line + reboot
Frequency range0.1Hz to 10kHz (lgpio limit)Up to several MHz (measured to 25MHz written)
Timing resolution1µs (lgpio rounds to whole µs); gpiozero rounds duty to whole %20ns (one RP1 clock)
Jitter at 1kHz, CPU idle (sd)2.8µs (lgpio C), 2.4µs (gpiozero)0.002µs
Jitter at 1kHz, all cores busy (sd)5.2µs (lgpio C), 118µs (gpiozero)0.002µs
CPU use at 1kHz1.5% of one core (14% at 10kHz)0%
Best forLED dimming, slow signals, any pinServos, motors, fans, anything timing-sensitive

The full measurements are in the jitter section below. The rest of this tutorial uses gpiozero and lgpio for software PWM, and the kernel’s sysfs PWM interface for hardware PWM. Note that libgpiod, the C++ GPIO library of my Raspberry Pi GPIO tutorial, has no PWM function, so the C++ examples use lgpio for software PWM and sysfs for hardware PWM.


Raspberry Pi PWM Wiring and Parts

All the examples use two LEDs: a yellow LED on GPIO17 for software PWM, and a green LED on GPIO12 for hardware PWM, each with a 330Ω resistor. A push button on GPIO27 is used in the brightness example.

QTY.Component NameAmazon.comAliExpress
1Raspberry Pi 5 (4GB or 8GB)AmazonAliExpress
1Raspberry Pi 27W USB-C Power SupplyAmazonAliExpress
25mm LED (Yellow, Green)AmazonAliExpress
2330Ω Resistor (kit)AmazonAliExpress
1Push Button (6mm, 4-Pin)AmazonAliExpress
1BreadboardAmazonAliExpress
1Jumper Wires (Female-Male)AmazonAliExpress
Raspberry Pi 5 PWM wiring diagram: green LED on GPIO12 (hardware PWM), yellow LED on GPIO17 (software PWM), push button on GPIO27

Breadboard Raspberry Pi 5 Green LED anode (via 330Ω) GPIO12 (pin 32) Yellow LED anode (via 330Ω) GPIO17 (pin 11) Button leg 1 GPIO27 (pin 13) LED cathodes, button leg 2 GND (pin 9)

Each LED goes from its GPIO pin through a 330Ω resistor to its anode, and its cathode goes to the GND rail. The button sits across the center channel between GPIO27 and GND, with the internal pull-up enabled in code. A 330Ω resistor keeps each LED near 3mA, well inside the GPIO current limits.

GPIO12 Green LED through 330Ω (pin 32), RP1 hardware PWM0 channel 0

GPIO17 Yellow LED through 330Ω (pin 11), software PWM

GPIO27 Push button (pin 13), internal pull-up

GND LED cathodes and button (pin 9)


Raspberry Pi Software PWM in Python (gpiozero)

gpiozero’s PWMLED class (and PWMOutputDevice for other loads) gives you software PWM on any GPIO pin. It is pre-installed on Raspberry Pi OS and uses the lgpio pin factory on the Raspberry Pi 5, so value from 0 to 1 sets the duty cycle and the frequency argument sets the PWM frequency (100Hz by default).

Raspberry Pi PWM LED Fade Example (Python)

In the following example project, we’ll fade the yellow LED on GPIO17 in and out with 1kHz software PWM, in 1% duty cycle steps every 10ms.

Wiring: yellow LED + 330Ω on GPIO17 (pin 11) to GND.

Here is The Application Code For This Example Project (sw_pwm_fade.py):

Raspberry Pi gpiozero PWM Code Explanation

PWMLED(17, frequency=1000) claims GPIO17 and starts lgpio’s PWM thread at 1kHz with 0% duty. Setting led.value changes the duty cycle; duty / 100 converts the loop counter to the 0-1 range. On Ctrl+C, led.off() stops the PWM and leaves the pin LOW.

Note: gpiozero passes the duty cycle to lgpio as a whole percent ( int(value * 100) in gpiozero/pins/lgpio.py), so led.value = 0.255 gives 25%, not 25.5%. For a smoother fade at low brightness, use hardware PWM.

Run it with python3 sw_pwm_fade.py. This is the output on my Raspberry Pi 5:

Raspberry Pi 5 gpiozero software PWM LED fade: python3 sw_pwm_fade.py output
Raspberry Pi 5 gpiozero software PWM LED fade: python3 sw_pwm_fade.py output

gpiozero also has led.pulse() for a background fade and led.blink(fade_in_time=1, fade_out_time=1); both run on the same lgpio PWM.


Raspberry Pi Software PWM in C++ (lgpio)

In C and C++, lgpio‘s lgTxPwm() does the same job: it queues a PWM setting for a pin, and lgpio’s transmit thread toggles the pin until you change it. Install the header and library once with sudo apt install liblgpio-dev (the Python lgpio module is already on the image).

Raspberry Pi PWM LED Fade Example (C++)

In the following example project, we’ll fade the same yellow LED on GPIO17 with lgpio software PWM at 1kHz.

Wiring: yellow LED + 330Ω on GPIO17 (pin 11) to GND.

Here is The Application Code For This Example Project (sw_pwm_fade.cpp):

Raspberry Pi lgpio PWM Code Explanation

lgGpiochipOpen(0) opens /dev/gpiochip0, the 40-pin header, and lgGpioClaimOutput() claims GPIO17 as an output. Each lgTxPwm(h, pin, 1000, duty, 0, 0) call replaces the running PWM at the end of the current period (0 cycles means “run until changed”). lgTxPwm() with a frequency of 0 stops the PWM. lgpio accepts 0.1Hz to 10kHz and rounds the period and the HIGH time to whole microseconds (lgpio source, lgGpio.c), so at 10kHz you have only 100 duty steps.

Build and run it:

Raspberry Pi 5 lgpio C++ software PWM: g++ build with -llgpio and sw_pwm_fade output
Raspberry Pi 5 lgpio C++ software PWM: g++ build with -llgpio and sw_pwm_fade output


Raspberry Pi 5 Hardware PWM Setup (dtoverlay)

Hardware PWM is off by default. On a fresh Raspberry Pi OS, GPIO12 is an unused pin and /sys/class/pwm/ is empty:

Raspberry Pi 5 before the PWM overlay: pinctrl get 12 shows GPIO12 = none and /sys/class/pwm is empty
Raspberry Pi 5 before the PWM overlay: pinctrl get 12 shows GPIO12 = none and /sys/class/pwm is empty

Step 1: Add the PWM Overlay to config.txt

Open /boot/firmware/config.txt with sudo nano /boot/firmware/config.txt and add this line at the end, under the [all] section:

The pwm overlay enables one channel on the pin you give it. func=4 is the BCM2835 “ALT0” function code; the Raspberry Pi 5’s RP1 GPIO driver maps it to the matching RP1 function, so the same line works on the Pi 4 and the Pi 5. The overlays and their pin/func pairs:

Pinconfig.txt LineChannel (Pi 5)
GPIO12dtoverlay=pwm,pin=12,func=4pwm0
GPIO13dtoverlay=pwm,pin=13,func=4pwm1
GPIO18dtoverlay=pwm (default pin)pwm2
GPIO19dtoverlay=pwm,pin=19,func=2pwm3
GPIO12 + GPIO13dtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4pwm0, pwm1

I tested the GPIO12 line on the bench; the other rows follow the same func codes from the overlay README. Then reboot with sudo reboot.

Step 2: Check the Pin Function and Find the pwmchip

After the reboot, pinctrl shows GPIO12 switched to PWM0_CHAN0, and a pwmchip appears in sysfs:

Raspberry Pi 5 after dtoverlay=pwm: pinctrl shows GPIO12 = PWM0_CHAN0, pwmchip0 links to 1f00098000.pwm with 4 channels
Raspberry Pi 5 after dtoverlay=pwm: pinctrl shows GPIO12 = PWM0_CHAN0, pwmchip0 links to 1f00098000.pwm with 4 channels

Don’t guess the pwmchipN number: Pi 5 kernels before 6.12 numbered it pwmchip2 (per the rpi-hardware-pwm notes), and other PWM chips, such as the fan’s RP1 PWM1, can appear in the same folder. Look for the one whose link ends in 1f00098000.pwm: that is RP1 PWM0, the block behind the header pins. On my Pi 5 with kernel 6.18 it is pwmchip0 with npwm = 4. The examples below find it by that name automatically.

Note: dtoverlay -l prints “No overlays loaded” even when the overlay works: it lists only overlays loaded at runtime, not the ones from config.txt. Use pinctrl get 12 to check.

Step 3: Control the Hardware PWM From the Command Line

The kernel’s sysfs PWM interface uses four files. Export a channel, then set the period and duty_cycle in nanoseconds, then enable it:

Raspberry Pi 5 hardware PWM from sysfs: export channel 0, period 1000000 ns, duty_cycle 250000 ns, enable 1
Raspberry Pi 5 hardware PWM from sysfs: export channel 0, period 1000000 ns, duty_cycle 250000 ns, enable 1

That is 1kHz at 25% on GPIO12. My oscilloscope capture of it: CH1 (yellow) is on GPIO12 at the green LED, 200µs/div. The arrows mark one period and the HIGH time, and the footer shows the scope’s own measurements.

Raspberry Pi 5 hardware PWM on the oscilloscope: GPIO12 at 1 kHz, 25% duty cycle set from sysfs, 250 µs high time
Raspberry Pi 5 hardware PWM on the oscilloscope: GPIO12 at 1 kHz, 25% duty cycle set from sysfs, 250 µs high time

The scope reads a 250µs HIGH time and 25.00% duty. Its mean voltage reading was 0.857v with a 3.24v HIGH level, close to the 0.81v that 25% of 3.24v predicts. The user pi did all of this without sudo: the export file and the new pwm0 files belong to the gpio group.

To stop it, write to enable and then to unexport.


Raspberry Pi Hardware PWM in Python

Python can drive the same sysfs files with plain file writes, and there is also a small maintained PyPI package for it. Both examples fade the green LED on GPIO12 at 1kHz.

Raspberry Pi Hardware PWM Python Example (sysfs)

Wiring: green LED + 330Ω on GPIO12 (pin 32) to GND. Overlay: dtoverlay=pwm,pin=12,func=4.

Here is The Application Code For This Example Project (hw_pwm_sysfs.py):

find_pwmchip() looks up the pwmchip whose device ends in 1f00098000.pwm. The HardwarePWM class exports the channel if needed and waits until the files are writable (udev changes their group about 50ms after the export). It writes the duty cycle before the period, so the duty cycle is never larger than the period, which the kernel refuses. duty() converts a percentage to nanoseconds.

Raspberry Pi 5 hardware PWM Python sysfs example: python3 hw_pwm_sysfs.py output on pwmchip0/pwm0
Raspberry Pi 5 hardware PWM Python sysfs example: python3 hw_pwm_sysfs.py output on pwmchip0/pwm0

Raspberry Pi Hardware PWM With rpi-hardware-pwm (Python)

rpi-hardware-pwm (version 0.3.1, February 2026) wraps the same sysfs files in a HardwarePWM class. It isn’t packaged for Raspberry Pi OS, and pip refuses to install into the system Python (PEP 668), so install it into a virtual environment that still sees the system packages:

Installing rpi-hardware-pwm on the Raspberry Pi 5 in a Python venv with --system-site-packages
Installing rpi-hardware-pwm on the Raspberry Pi 5 in a Python venv with –system-site-packages

On the Raspberry Pi 5 use chip=0 with kernel 6.12 and newer (the package’s notes say chip=2 for older Pi 5 kernels) and pwm_channel 0 to 3 for GPIO12, 13, 18, and 19. Run it with the venv’s Python:

Raspberry Pi 5 rpi-hardware-pwm example output: hardware PWM on GPIO12 at 1 kHz
Raspberry Pi 5 rpi-hardware-pwm example output: hardware PWM on GPIO12 at 1 kHz


Raspberry Pi Hardware PWM in C++ (sysfs)

In C++, a small class over the sysfs files is all you need, with no library to install.

Raspberry Pi Hardware PWM C++ Example

Wiring: green LED + 330Ω on GPIO12 (pin 32) to GND. Overlay: dtoverlay=pwm,pin=12,func=4.

Here is The Application Code For This Example Project (hw_pwm_sysfs.cpp):

Raspberry Pi Hardware PWM C++ Code Explanation

The constructor finds RP1 PWM0 with std::filesystem::canonical() on each pwmchipN/device link, exports the channel, waits for write access, writes duty 0, then the period, then enables the output. duty() writes a new duty cycle in nanoseconds, and the destructor disables the channel when the program ends. Each write takes effect at once.

Raspberry Pi 5 hardware PWM C++ sysfs example: g++ build and hw_pwm_sysfs output
Raspberry Pi 5 hardware PWM C++ sysfs example: g++ build and hw_pwm_sysfs output

This is the real hardware testing result for the LED fade examples on my Raspberry Pi 5: the yellow LED fades with software PWM (GPIO17) and the green LED with hardware PWM (GPIO12). At this speed both look the same to the eye; the difference shows up on the oscilloscope.

Raspberry Pi 5 PWM LED fade: yellow LED with software PWM on GPIO17, green LED with hardware PWM on GPIO12


Raspberry Pi PWM Jitter Measured (Software vs Hardware)

Hardware PWM on the Raspberry Pi 5 has no measurable jitter; software PWM does, and it gets much worse when the CPU is busy. To show it, I ran each method at 1kHz, 50% duty, and recorded five long single-shot captures per case on my oscilloscope at 1GSa/s, about 1,400 periods each, then measured every period. I repeated all three with the CPU idle and with all four cores busy (four shell busy loops).

Raspberry Pi 5 hardware PWM at 1 kHz, 50% duty on the oscilloscope: GPIO12, RP1 PWM0 channel 0
Raspberry Pi 5 hardware PWM at 1 kHz, 50% duty on the oscilloscope: GPIO12, RP1 PWM0 channel 0

A single capture looks clean for all three methods; the capture above is CH1 (yellow) on GPIO12 with hardware PWM, and the two below are CH3 (cyan) on GPIO17 with lgpio and gpiozero software PWM, 200µs/div. The differences appear only across many periods.

Raspberry Pi 5 lgpio lgTxPwm software PWM at 1 kHz on the oscilloscope: GPIO17
Raspberry Pi 5 lgpio lgTxPwm software PWM at 1 kHz on the oscilloscope: GPIO17

Raspberry Pi 5 gpiozero software PWM at 1 kHz on the oscilloscope: GPIO17
Raspberry Pi 5 gpiozero software PWM at 1 kHz on the oscilloscope: GPIO17

This chart plots every measured period as one dot, as its deviation from the mean period:

Raspberry Pi 5 PWM jitter chart: every period of RP1 hardware PWM, lgpio and gpiozero software PWM at 1 kHz, CPU idle and busy

Method (1kHz, 50%)CPUPeriodsPeriod sdWorst Period ErrorShortest / Longest Period
RP1 hardware PWMIdle1,3900.002µs0.004µs1000.09 / 1000.09µs
RP1 hardware PWM4 cores busy1,3900.002µs0.004µs1000.09 / 1000.09µs
lgpio lgTxPwm (C)Idle1,3982.8µs47µs952.6 / 1047.4µs
lgpio lgTxPwm (C)4 cores busy1,3935.2µs133µs869.8 / 1132.9µs
gpiozero (Python)Idle1,3902.4µs49µs950.7 / 1049.3µs
gpiozero (Python)4 cores busy1,395118µs3,941µs12.7 / 4,941.0µs

What the numbers show:

  • Hardware PWM: every one of the 1,390 periods was within a few nanoseconds of the mean, idle or loaded. The CPU load has no effect at all.
  • lgpio software PWM: most periods sit within ±1µs (lgpio’s whole-microsecond timing), with a few periods about 50µs off even when idle. Under load the spread grows to a worst case of 133µs.
  • gpiozero software PWM: the same lgpio thread underneath, so it behaves like lgpio when idle. Under load it missed pulses: the longest “period” was 4.94ms (about 4 pulses missing) and the shortest 12.7µs, and the average duty drifted to 54.8%.

For an LED, none of this is visible. For a servo, a 50µs error on a 1.5ms pulse is a few degrees of position error, and a missing pulse makes it twitch. That is why servo and motor control belong on the hardware PWM pins.


Raspberry Pi PWM Frequency Range and Resolution

Software PWM tops out at 10kHz, because lgpio refuses anything higher; hardware PWM runs into the MHz range with 20ns steps. I measured both on the oscilloscope.

Raspberry Pi Software PWM Frequency Limit

lgpio’s documented range is 0.1Hz to 10kHz, and both lgpio and gpiozero ran cleanly up to 10kHz on my Pi 5 (period sd 0.087µs with lgpio at 10kHz, idle). Above that, the call fails with “bad PWM frequency” (shown in the troubleshooting section). At high frequencies, the limit is resolution: lgpio works in whole microseconds, so at 10kHz (100µs period) the duty cycle moves in 1% steps. CPU use also rises with frequency: lgpio’s thread took 1.5% of one core at 1kHz and 14% at 10kHz.

Raspberry Pi 5 Hardware PWM Frequency Range

The RP1 PWM counter runs from a 50MHz clock, so the period and the HIGH time are counted in 20ns steps. The table shows what my oscilloscope measured for each period written to sysfs:

Target FrequencyPeriod Written (ns)RP1 Clock Ticks per PeriodMeasured PeriodMeasured FrequencyDuty Step
50Hz20,000,0001,000,00120,001.313µs50Hz0.0001%
1kHz1,000,00050,0011,000.090µs999.91Hz0.002%
25kHz40,0002,00140.023µs24.99kHz0.05%
100kHz10,00050110.021µs99.8kHz0.2%
1MHz1,000511.020µs979.9kHz2%
5MHz20011220.0ns4.55MHz10%
10MHz1006120.0ns8.33MHz20%

The table shows two things. First, the duty resolution is excellent at the frequencies you’ll use: 2,000 steps at a 25kHz fan frequency, 1,000,000 steps at a 50Hz servo frequency. Second, every period comes out one 20ns clock longer than the value you write: 1,000ns gives 1,020ns (980kHz) and 100ns gives 120ns (8.33MHz). The kernel driver writes period / 20ns into the RP1 range register (pwm-rp1.c), and the counter counts one tick more. At 1kHz the extra 20ns is 0.002% and doesn’t matter; above about 100kHz, subtract 20ns from the period you write if you need the exact frequency. Here is the 1MHz case on my oscilloscope (CH1 on GPIO12, 500ns/div):

Raspberry Pi 5 hardware PWM at 1 MHz on the oscilloscope: period written 1000 ns measures 1.02 µs (980.2 kHz), high time 500 ns
Raspberry Pi 5 hardware PWM at 1 MHz on the oscilloscope: period written 1000 ns measures 1.02 µs (980.2 kHz), high time 500 ns

The HIGH time is exactly the 500ns written, and the period is 1.02µs. At 1MHz and above, my 1X probe also rounds the edges, so the scope’s duty readings above 5MHz are limited by the probe, not the Pi.

To confirm it with an independent instrument, I measured the same 1MHz output (period 1,000ns, duty 500ns written to sysfs) on GPIO12 with my Agilent 53131A frequency counter, which runs from a rubidium frequency standard as its reference clock. It reads 980,331.741Hz:

Raspberry Pi 5 hardware PWM set to 1 MHz measured with an Agilent 53131A frequency counter (rubidium reference): 980,331.741 Hz
Raspberry Pi 5 hardware PWM set to 1 MHz measured with an Agilent 53131A frequency counter (rubidium reference): 980,331.741 Hz

A 50MHz clock divided by 51 ticks gives 980,392Hz, so the counter confirms the extra 20ns tick: a period written as 1,000ns is 51 clocks long. The remaining 0.006% (−62ppm) is the RP1 PWM clock on my board itself, which works out to 49.997MHz instead of exactly 50MHz. For a servo or a fan, an error that small doesn’t matter; for a precise frequency, measure your own board once and correct the period.

Raspberry Pi PWM Duty Cycle Accuracy

I also set seven duty cycles from 1% to 99% at 1kHz with each method and measured about 280 periods per point:

Raspberry Pi 5 PWM duty cycle accuracy chart at 1 kHz: measured minus set duty for hardware PWM, lgpio and gpiozero software PWM from 1% to 99%

Duty SetRP1 Hardware (Mean)lgpio C (Mean, Min to Max)gpiozero (Mean, Min to Max)
1%1.00%1.84% (0.5 to 5.7%)0.55% (0.5 to 0.6%)
10%10.00%9.99% (9.7 to 14.2%)11.13% (9.8 to 14.2%)
25%25.00%26.17% (25.0 to 28.5%)26.18% (24.7 to 28.6%)
50%50.00%49.98% (49.9 to 50.0%)49.99% (49.8 to 52.0%)
75%75.00%76.26% (75.0 to 79.2%)76.27% (74.9 to 78.9%)
90%90.00%91.28% (90.0 to 94.7%)90.01% (89.9 to 93.1%)
99%99.00%98.36% (95.0 to 99.5%)98.35% (95.0 to 99.4%)

Hardware PWM hit every value to within 0.01%. The software methods are right on average at 50% but can be off by more than a percentage point at other duty cycles, and single periods vary by several percent, with the largest relative error at 1% and 99%, where a few microseconds of timing error is a large part of a very short pulse.


Raspberry Pi PWM Example: LED Brightness With a Button

In the following example project, we’ll step the brightness of the green LED (hardware PWM on GPIO12) with the push button on GPIO27:

  • Each press moves to the next brightness level: 0, 5, 15, 35, 65, and 100%, then back to 0.
  • The levels are spaced for the eye, which is far more sensitive to changes at low brightness.
  • In other words, the button is an input, the hardware PWM is the output, and the program only acts when the button is pressed.

Wiring: green LED + 330Ω on GPIO12, button between GPIO27 and GND.

Here is The Application Code For This Example Project in Python (button_brightness.py):

And in C++, with libgpiod v2 edge events for the button (button_brightness.cpp):

Both use the button’s internal pull-up and a short debounce (gpiozero bounce_time=0.02, libgpiod debounce_period 10ms), as explained in my Raspberry Pi button tutorial, which also covers why gpiozero’s bounce_time delays every press by its own value. Build the C++ version with g++ -std=c++17 -O2 button_brightness.cpp -o button_brightness $(pkg-config --cflags --libs libgpiodcxx).

The C++ version catches the std::system_error that wait_edge_events() throws when Ctrl+C interrupts the wait (“Interrupted system call”), so the program still disables the PWM on exit. I pressed the button with the Python version; the C++ version builds, runs, and exits cleanly on my Pi 5.

This is the real hardware testing result for this example project on my Raspberry Pi 5, six presses with the Python version:

Raspberry Pi 5 button LED brightness example: six button presses step the hardware PWM duty cycle 5, 15, 35, 65, 100, 0 %
Raspberry Pi 5 button LED brightness example: six button presses step the hardware PWM duty cycle 5, 15, 35, 65, 100, 0 %

Raspberry Pi 5 LED brightness control with a push button and hardware PWM on GPIO12


RPi.GPIO PWM on the Raspberry Pi 5

If you have older code with GPIO.PWM(), it still runs on the Raspberry Pi 5: Raspberry Pi OS replaces the original RPi.GPIO with rpi-lgpio, a compatible library built on lgpio. I tested GPIO.PWM, ChangeDutyCycle(), and ChangeFrequency() in my Raspberry Pi GPIO tutorial; the duty cycle was within 0.2%. It is software PWM through the same lgpio thread, so the jitter numbers above apply to it too.

Note: Like the original RPi.GPIO, creating a second GPIO.PWM() object on the same pin after stop() fails with “A PWM object already exists for this GPIO channel”: delete the old object first ( del p). For new code use gpiozero, and see my Raspberry Pi GPIO library comparison for the other libraries.


Raspberry Pi PWM Troubleshooting

These are the real errors I hit on the Raspberry Pi 5, with their causes and fixes.

Raspberry Pi 5 PWM sysfs errors: pwmchip2 No such file or directory, export Device or resource busy, period write Invalid argument
Raspberry Pi 5 PWM sysfs errors: pwmchip2 No such file or directory, export Device or resource busy, period write Invalid argument

bash: /sys/class/pwm/pwmchip2/export: No such file or directory

The pwmchip doesn’t exist: either the overlay isn’t loaded or the number is wrong. Check ls -l /sys/class/pwm/ and use the chip that links to 1f00098000.pwm. If the folder is empty, the overlay line is missing, misspelled, or inside a [cm4]/ [cm5] section of config.txt, or you haven’t rebooted.

bash: echo: write error: Device or resource busy

The channel is already exported (by you, another program, or an earlier run). Use the existing pwm0 folder, or write the channel number to unexport first.

bash: echo: write error: Invalid argument

The kernel refuses a period shorter than the current duty cycle while the channel is enabled. Lower duty_cycle first, then change period. On kernel 6.18 the same mistake on a disabled channel is accepted, and the error appears when you write 1 to enable.

Permission denied right after export

Raspberry Pi 5 PWM Permission denied when writing period right after export, before udev sets the gpio group
Raspberry Pi 5 PWM Permission denied when writing period right after export, before udev sets the gpio group

A script that writes period in the same instant it exports the channel gets “Permission denied”: the new files belong to root until udev gives them to the gpio group, about 50ms later on my Pi 5. Wait for write access before the first write, as the examples do. It isn’t a reason to use sudo.

lgpio: bad PWM frequency

Raspberry Pi 5 lgpio and gpiozero PWM errors: xGpioHandleRequest Invalid argument on an overlay pin, bad PWM frequency above 10 kHz
Raspberry Pi 5 lgpio and gpiozero PWM errors: xGpioHandleRequest Invalid argument on an overlay pin, bad PWM frequency above 10 kHz

lgpio (and gpiozero with the lgpio pin factory) accepts only 0.1Hz to 10kHz. For a higher frequency, use hardware PWM.

xGpioHandleRequest: Invalid argument / lgGpioClaimOutput: unexpected error

You tried to use a pin as a normal GPIO while the PWM overlay owns it. A pin can’t be both: use a different pin for lgpio, gpiozero, or libgpiod, or remove the overlay line and reboot.

The LED doesn’t change after the sysfs commands

Check pinctrl get 12: it must say PWM0_CHAN0. Also make sure enable reads 1, the LED is on the pin that matches your channel (GPIO12 = pwm0, GPIO18 = pwm2), and the LED’s polarity is correct.


Raspberry Pi PWM FAQ

How many PWM pins does the Raspberry Pi 5 have?

Four hardware PWM pins on the 40-pin header: GPIO12, GPIO13, GPIO18, and GPIO19, each an independent channel of RP1 PWM0. Any other GPIO from 0 to 27 can do software PWM.

Does Raspberry Pi hardware PWM need sudo?

Only for the one-time config.txt change. On Raspberry Pi OS the sysfs PWM files belong to the gpio group, so the default user exports and controls the channels without sudo.

Can I use all four hardware PWM channels at once?

Yes. Each pin has its own channel with its own period and duty cycle. Enable two with pwm-2chan; for three or four, add more dtoverlay=pwm,... lines, one per pin.

Does pigpio work for PWM on the Raspberry Pi 5?

No. pigpio’s DMA-timed PWM worked on all GPIOs of the Raspberry Pi 4 and older, but pigpio doesn’t support the Pi 5’s RP1 (pigpio issue #589). Use lgpio for software PWM and sysfs for hardware PWM.


Download Raspberry Pi PWM Examples

The download contains every example from this tutorial in Python and C++: the software PWM fades (gpiozero, lgpio), the hardware PWM fades (sysfs in Python and C++, rpi-hardware-pwm), and the button brightness example, plus the bench programs behind the measurements, with a README that lists each command.

Download Raspberry Pi PWM Examples (Python, C++)

Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.


Wrap Up

To conclude this tutorial, we’ve used Raspberry Pi PWM both ways on the Raspberry Pi 5: software PWM on any pin with gpiozero and lgpio, and hardware PWM on GPIO12, 13, 18, and 19 with one dtoverlay line and the sysfs interface, in Python and C++. The measurements make the choice simple: software PWM is fine for LEDs, while hardware PWM keeps its timing to the nanosecond even with every core busy, so use it for servos, motors, and fans.

For the GPIO basics, see my Raspberry Pi GPIO tutorial; for the button input used above, my Raspberry Pi button tutorial; and for choosing a library, the Raspberry Pi GPIO library comparison. The next tutorials in this Raspberry Pi series use hardware PWM to drive servo motors and a PWM fan.

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

Leave a Comment