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)
|
1 2 3 4 5 6 |
from gpiozero import PWMLED from time import sleep led = PWMLED(17) # software PWM on any GPIO (100Hz by default) led.value = 0.25 # 25% duty cycle = LED at quarter brightness sleep(5) |
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)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Needs "dtoverlay=pwm,pin=12,func=4" in /boot/firmware/config.txt (then reboot) #include <fstream> #include <string> #include <thread> #include <chrono> void put(const std::string& f, const std::string& v) { std::ofstream(f) << v; } int main() { const std::string chip = "/sys/class/pwm/pwmchip0"; // RP1 PWM0 (check: ls -l /sys/class/pwm/) put(chip + "/export", "0"); // channel 0 = GPIO12 (pin 32) std::this_thread::sleep_for(std::chrono::milliseconds(100)); // let udev set the permissions put(chip + "/pwm0/period", "1000000"); // 1kHz (period in ns) put(chip + "/pwm0/duty_cycle", "250000"); // 25% duty cycle put(chip + "/pwm0/enable", "1"); std::this_thread::sleep_for(std::chrono::seconds(5)); put(chip + "/pwm0/enable", "0"); put(chip + "/unexport", "0"); } |
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.

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.

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:
| GPIO | Header Pin | RP1 PWM Channel | pinctrl Function | sysfs Channel (pwmchip0) | Other Functions on the Pin |
|---|---|---|---|---|---|
| GPIO12 | 32 | PWM0_CHAN0 | a0 | pwm0 | UART4 TX, I2C2 SDA, SPI5 |
| GPIO13 | 33 | PWM0_CHAN1 | a0 | pwm1 | UART4 RX, I2C2 SCL, SPI5 |
| GPIO18 | 12 | PWM0_CHAN2 | a3 | pwm2 | I2S0 SCLK, SPI1 CE0 |
| GPIO19 | 35 | PWM0_CHAN3 | a3 | pwm3 | I2S0 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:

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:
| Property | Software PWM (gpiozero, lgpio) | Hardware PWM (RP1, sysfs) |
|---|---|---|
| Pins | Any GPIO 0 to 27 | GPIO12, 13, 18, 19 only |
| Setup | None | One dtoverlay line + reboot |
| Frequency range | 0.1Hz to 10kHz (lgpio limit) | Up to several MHz (measured to 25MHz written) |
| Timing resolution | 1µ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 1kHz | 1.5% of one core (14% at 10kHz) | 0% |
| Best for | LED dimming, slow signals, any pin | Servos, 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 Name | Amazon.com | AliExpress |
|---|---|---|---|
| 1 | Raspberry Pi 5 (4GB or 8GB) | Amazon | AliExpress |
| 1 | Raspberry Pi 27W USB-C Power Supply | Amazon | AliExpress |
| 2 | 5mm LED (Yellow, Green) | Amazon | AliExpress |
| 2 | 330Ω Resistor (kit) | Amazon | AliExpress |
| 1 | Push Button (6mm, 4-Pin) | Amazon | AliExpress |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | Jumper Wires (Female-Male) | Amazon | AliExpress |

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):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# LAB Name: Raspberry Pi Software PWM LED Fade With gpiozero (PWMLED) # Author: Khaled Magdy # For More Info Visit: www.DeepBlueMbedded.com from gpiozero import PWMLED from time import sleep # Software PWM works on any GPIO. GPIO17 = physical pin 11 (yellow LED). led = PWMLED(17, frequency=1000) # 1 kHz PWM, duty starts at 0 % print("Fading the LED on GPIO17 (software PWM, 1 kHz). Press Ctrl+C to stop.") try: while True: for duty in range(0, 101): # 0 % .. 100 % in 1 % steps led.value = duty / 100 sleep(0.01) for duty in range(100, -1, -1): # 100 % .. 0 % led.value = duty / 100 sleep(0.01) except KeyboardInterrupt: led.off() print("\nStopped. The LED is off.") |
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:
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):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
/* * LAB Name: Raspberry Pi Software PWM LED Fade With lgpio (C/C++) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com * * Build: g++ -std=c++17 -O2 sw_pwm_fade.cpp -o sw_pwm_fade -llgpio */ #include <lgpio.h> #include <atomic> #include <chrono> #include <csignal> #include <iostream> #include <thread> static std::atomic<bool> running{true}; static void on_sigint(int) { running = false; } int main() { const int chip = 0; // /dev/gpiochip0 = 40-pin header on the Raspberry Pi 5 (RP1) const int led_pin = 17; // BCM GPIO17 = physical pin 11 (yellow LED) const float freq_hz = 1000.0f; // lgTxPwm() accepts 0.1 .. 10000 Hz std::signal(SIGINT, on_sigint); int h = lgGpiochipOpen(chip); if (h < 0) { std::cerr << "lgGpiochipOpen: " << lguErrorText(h) << std::endl; return 1; } int rc = lgGpioClaimOutput(h, 0, led_pin, 0); // output, LOW if (rc < 0) { std::cerr << "lgGpioClaimOutput: " << lguErrorText(rc) << std::endl; return 1; } std::cout << "Fading the LED on GPIO17 (lgpio software PWM, 1 kHz). Press Ctrl+C to stop." << std::endl; while (running) { for (int duty = 0; duty <= 100 && running; duty++) { // fade in, 1 % steps lgTxPwm(h, led_pin, freq_hz, (float)duty, 0, 0); // 0 cycles = run until changed std::this_thread::sleep_for(std::chrono::milliseconds(10)); } for (int duty = 100; duty >= 0 && running; duty--) { // fade out lgTxPwm(h, led_pin, freq_hz, (float)duty, 0, 0); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } lgTxPwm(h, led_pin, 0, 0, 0, 0); // frequency 0 = stop the PWM lgGpioWrite(h, led_pin, 0); // LED off lgGpioFree(h, led_pin); lgGpiochipClose(h); std::cout << "\nStopped. The LED is off." << std::endl; return 0; } |
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 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:
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:
|
1 |
dtoverlay=pwm,pin=12,func=4 |
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:
| Pin | config.txt Line | Channel (Pi 5) |
|---|---|---|
| GPIO12 | dtoverlay=pwm,pin=12,func=4 | pwm0 |
| GPIO13 | dtoverlay=pwm,pin=13,func=4 | pwm1 |
| GPIO18 | dtoverlay=pwm (default pin) | pwm2 |
| GPIO19 | dtoverlay=pwm,pin=19,func=2 | pwm3 |
| GPIO12 + GPIO13 | dtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4 | pwm0, 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:
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:
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.
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):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# LAB Name: Raspberry Pi 5 Hardware PWM LED Fade (sysfs, Python) # Author: Khaled Magdy # For More Info Visit: www.DeepBlueMbedded.com # # Needs this line in /boot/firmware/config.txt (then reboot): dtoverlay=pwm,pin=12,func=4 # GPIO12 (pin 32) = RP1 PWM0 channel 0 (green LED). import glob, os, time def find_pwmchip(block="1f00098000.pwm"): """Return /sys/class/pwm/pwmchipN of the RP1 PWM0 block (the 40-pin header PWM).""" for chip in sorted(glob.glob("/sys/class/pwm/pwmchip*")): if os.path.realpath(chip + "/device").endswith(block): return chip raise SystemExit("RP1 PWM0 not found. Is dtoverlay=pwm in config.txt, and did you reboot?") def write(path, value): with open(path, "w") as f: f.write(str(value)) class HardwarePWM: def __init__(self, channel, freq_hz): self.chip = find_pwmchip() self.pwm = f"{self.chip}/pwm{channel}" if not os.path.isdir(self.pwm): write(f"{self.chip}/export", channel) for _ in range(100): # wait for udev to set the permissions if os.access(self.pwm + "/period", os.W_OK): break time.sleep(0.01) write(self.pwm + "/duty_cycle", 0) # duty first, so it never exceeds the period self.period_ns = round(1e9 / freq_hz) write(self.pwm + "/period", self.period_ns) write(self.pwm + "/enable", 1) def duty(self, percent): write(self.pwm + "/duty_cycle", round(self.period_ns * percent / 100)) def close(self): write(self.pwm + "/duty_cycle", 0) write(self.pwm + "/enable", 0) pwm = HardwarePWM(channel=0, freq_hz=1000) # GPIO12, 1 kHz print(f"Hardware PWM on {pwm.pwm} (GPIO12, 1 kHz). Press Ctrl+C to stop.") try: while True: for d in range(0, 101): pwm.duty(d) time.sleep(0.01) for d in range(100, -1, -1): pwm.duty(d) time.sleep(0.01) except KeyboardInterrupt: pwm.close() print("\nStopped. PWM disabled.") |
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 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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# LAB Name: Raspberry Pi 5 Hardware PWM LED Fade With rpi-hardware-pwm (Python) # Author: Khaled Magdy # For More Info Visit: www.DeepBlueMbedded.com # # Needs this line in /boot/firmware/config.txt (then reboot): dtoverlay=pwm,pin=12,func=4 # Install (venv): python3 -m venv --system-site-packages venv && venv/bin/pip install rpi-hardware-pwm # Run: venv/bin/python hw_pwm_rpi_hardware_pwm.py from rpi_hardware_pwm import HardwarePWM from time import sleep # GPIO12 (pin 32) = RP1 PWM0 channel 0 on /sys/class/pwm/pwmchip0 (kernel 6.12 and newer) pwm = HardwarePWM(pwm_channel=0, hz=1000, chip=0) pwm.start(0) # duty cycle 0 % print("Hardware PWM on GPIO12 (rpi-hardware-pwm, 1 kHz). Press Ctrl+C to stop.") try: while True: for duty in range(0, 101): pwm.change_duty_cycle(duty) sleep(0.01) for duty in range(100, -1, -1): pwm.change_duty_cycle(duty) sleep(0.01) except KeyboardInterrupt: pwm.stop() print("\nStopped. PWM disabled.") |
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 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):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
/* * LAB Name: Raspberry Pi 5 Hardware PWM LED Fade (sysfs, C++) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com * * Needs this line in /boot/firmware/config.txt (then reboot): dtoverlay=pwm,pin=12,func=4 * Build: g++ -std=c++17 -O2 hw_pwm_sysfs.cpp -o hw_pwm_sysfs */ #include <atomic> #include <chrono> #include <cmath> #include <csignal> #include <filesystem> #include <fstream> #include <iostream> #include <stdexcept> #include <string> #include <thread> #include <unistd.h> namespace fs = std::filesystem; static std::atomic<bool> running{true}; static void on_sigint(int) { running = false; } class HardwarePWM { public: HardwarePWM(int channel, double freq_hz) { chip_ = findChip("1f00098000.pwm"); // RP1 PWM0 = the 40-pin header PWM block pwm_ = chip_ + "/pwm" + std::to_string(channel); if (!fs::exists(pwm_)) { write(chip_ + "/export", channel); for (int i = 0; i < 100 && access((pwm_ + "/period").c_str(), W_OK) != 0; i++) std::this_thread::sleep_for(std::chrono::milliseconds(10)); // udev sets the permissions } write(pwm_ + "/duty_cycle", 0); // duty first: it must never exceed the period period_ns_ = std::llround(1e9 / freq_hz); write(pwm_ + "/period", period_ns_); write(pwm_ + "/enable", 1); } ~HardwarePWM() { write(pwm_ + "/duty_cycle", 0); write(pwm_ + "/enable", 0); } void duty(double percent) { write(pwm_ + "/duty_cycle", std::llround(period_ns_ * percent / 100.0)); } const std::string& path() const { return pwm_; } private: std::string chip_, pwm_; long long period_ns_ = 0; static std::string findChip(const std::string& block) { for (const auto& e : fs::directory_iterator("/sys/class/pwm")) { std::string dev = fs::canonical(e.path() / "device").string(); if (dev.size() >= block.size() && dev.compare(dev.size() - block.size(), block.size(), block) == 0) return e.path().string(); } throw std::runtime_error("RP1 PWM0 not found. Is dtoverlay=pwm in config.txt, and did you reboot?"); } template <typename T> static void write(const std::string& file, T value) { std::ofstream f(file); f << value; f.flush(); if (!f) throw std::runtime_error("write failed: " + file); } }; int main() { std::signal(SIGINT, on_sigint); try { HardwarePWM pwm(0, 1000.0); // channel 0 = GPIO12 (pin 32), 1 kHz std::cout << "Hardware PWM on " << pwm.path() << " (GPIO12, 1 kHz). Press Ctrl+C to stop." << std::endl; while (running) { for (int d = 0; d <= 100 && running; d++) { pwm.duty(d); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } for (int d = 100; d >= 0 && running; d--) { pwm.duty(d); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } std::cout << "\nStopped. PWM disabled." << std::endl; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } |
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.
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 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).
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.
This chart plots every measured period as one dot, as its deviation from the mean period:

| Method (1kHz, 50%) | CPU | Periods | Period sd | Worst Period Error | Shortest / Longest Period |
|---|---|---|---|---|---|
| RP1 hardware PWM | Idle | 1,390 | 0.002µs | 0.004µs | 1000.09 / 1000.09µs |
| RP1 hardware PWM | 4 cores busy | 1,390 | 0.002µs | 0.004µs | 1000.09 / 1000.09µs |
| lgpio lgTxPwm (C) | Idle | 1,398 | 2.8µs | 47µs | 952.6 / 1047.4µs |
| lgpio lgTxPwm (C) | 4 cores busy | 1,393 | 5.2µs | 133µs | 869.8 / 1132.9µs |
| gpiozero (Python) | Idle | 1,390 | 2.4µs | 49µs | 950.7 / 1049.3µs |
| gpiozero (Python) | 4 cores busy | 1,395 | 118µs | 3,941µs | 12.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 Frequency | Period Written (ns) | RP1 Clock Ticks per Period | Measured Period | Measured Frequency | Duty Step |
|---|---|---|---|---|---|
| 50Hz | 20,000,000 | 1,000,001 | 20,001.313µs | 50Hz | 0.0001% |
| 1kHz | 1,000,000 | 50,001 | 1,000.090µs | 999.91Hz | 0.002% |
| 25kHz | 40,000 | 2,001 | 40.023µs | 24.99kHz | 0.05% |
| 100kHz | 10,000 | 501 | 10.021µs | 99.8kHz | 0.2% |
| 1MHz | 1,000 | 51 | 1.020µs | 979.9kHz | 2% |
| 5MHz | 200 | 11 | 220.0ns | 4.55MHz | 10% |
| 10MHz | 100 | 6 | 120.0ns | 8.33MHz | 20% |
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):
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:
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:

| Duty Set | RP1 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):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# LAB Name: Raspberry Pi 5 LED Brightness Control With a Button (Hardware PWM + gpiozero Button) # Author: Khaled Magdy # For More Info Visit: www.DeepBlueMbedded.com # # Needs this line in /boot/firmware/config.txt (then reboot): dtoverlay=pwm,pin=12,func=4 # Green LED on GPIO12 (pin 32, hardware PWM), push button on GPIO27 (pin 13) to GND (internal pull-up). import glob, os, time from gpiozero import Button from signal import pause def find_pwmchip(block="1f00098000.pwm"): for chip in sorted(glob.glob("/sys/class/pwm/pwmchip*")): if os.path.realpath(chip + "/device").endswith(block): return chip raise SystemExit("RP1 PWM0 not found. Is dtoverlay=pwm in config.txt, and did you reboot?") def write(path, value): with open(path, "w") as f: f.write(str(value)) CHIP = find_pwmchip() PWM = CHIP + "/pwm0" # channel 0 = GPIO12 PERIOD_NS = 1_000_000 # 1 kHz if not os.path.isdir(PWM): write(CHIP + "/export", 0) while not os.access(PWM + "/period", os.W_OK): time.sleep(0.01) # udev gives the files to the gpio group write(PWM + "/duty_cycle", 0) write(PWM + "/period", PERIOD_NS) write(PWM + "/enable", 1) levels = [0, 5, 15, 35, 65, 100] # brightness steps in % (roughly even steps for the eye) step = 0 def next_level(): global step step = (step + 1) % len(levels) write(PWM + "/duty_cycle", PERIOD_NS * levels[step] // 100) print(f"Button pressed: brightness {levels[step]} %") button = Button(27, bounce_time=0.02) # GPIO27, pull-up on, 20 ms debounce button.when_pressed = next_level print("Press the button on GPIO27 to step the LED brightness on GPIO12. Press Ctrl+C to stop.") try: pause() except KeyboardInterrupt: write(PWM + "/duty_cycle", 0) write(PWM + "/enable", 0) print("\nStopped. PWM disabled.") |
And in C++, with libgpiod v2 edge events for the button (button_brightness.cpp):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
/* * LAB Name: Raspberry Pi 5 LED Brightness Control With a Button (Hardware PWM + libgpiod v2, C++) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com * * Needs this line in /boot/firmware/config.txt (then reboot): dtoverlay=pwm,pin=12,func=4 * Green LED on GPIO12 (pin 32, hardware PWM), push button on GPIO27 (pin 13) to GND (internal pull-up). * Build: g++ -std=c++17 -O2 button_brightness.cpp -o button_brightness $(pkg-config --cflags --libs libgpiodcxx) */ #include <gpiod.hpp> #include <atomic> #include <chrono> #include <csignal> #include <filesystem> #include <fstream> #include <iostream> #include <string> #include <system_error> #include <thread> #include <unistd.h> namespace fs = std::filesystem; static std::atomic<bool> running{true}; static void on_sigint(int) { running = false; } static void write(const std::string& file, long long value) { std::ofstream(file) << value; } static std::string find_pwmchip(const std::string& block = "1f00098000.pwm") { for (const auto& e : fs::directory_iterator("/sys/class/pwm")) { std::string dev = fs::canonical(e.path() / "device").string(); if (dev.size() >= block.size() && dev.compare(dev.size() - block.size(), block.size(), block) == 0) return e.path().string(); } return ""; } int main() { std::signal(SIGINT, on_sigint); const std::string chip = find_pwmchip(); if (chip.empty()) { std::cerr << "RP1 PWM0 not found. Is dtoverlay=pwm in config.txt, and did you reboot?" << std::endl; return 1; } const std::string pwm = chip + "/pwm0"; // channel 0 = GPIO12 const long long period_ns = 1000000; // 1 kHz if (!fs::exists(pwm)) { write(chip + "/export", 0); while (access((pwm + "/period").c_str(), W_OK) != 0) std::this_thread::sleep_for(std::chrono::milliseconds(10)); // udev gives the files to the gpio group } write(pwm + "/duty_cycle", 0); write(pwm + "/period", period_ns); write(pwm + "/enable", 1); // GPIO27 as input with pull-up, falling-edge events (press = HIGH -> LOW), 10 ms kernel debounce const gpiod::line::offset button = 27; auto request = gpiod::chip("/dev/gpiochip0") .prepare_request() .set_consumer("button_brightness") .add_line_settings(button, gpiod::line_settings() .set_direction(gpiod::line::direction::INPUT) .set_bias(gpiod::line::bias::PULL_UP) .set_edge_detection(gpiod::line::edge::FALLING) .set_debounce_period(std::chrono::milliseconds(10))) .do_request(); const int levels[] = {0, 5, 15, 35, 65, 100}; // brightness steps in % const int n_levels = sizeof(levels) / sizeof(levels[0]); int step = 0; gpiod::edge_event_buffer events; std::cout << "Press the button on GPIO27 to step the LED brightness on GPIO12. Press Ctrl+C to stop." << std::endl; while (running) { try { if (!request.wait_edge_events(std::chrono::milliseconds(200))) continue; // timeout: check Ctrl+C, then wait again } catch (const std::system_error&) { continue; // Ctrl+C interrupts the wait ("Interrupted system call") } request.read_edge_events(events); for (std::size_t i = 0; i < events.num_events(); i++) { step = (step + 1) % n_levels; write(pwm + "/duty_cycle", period_ns * levels[step] / 100); std::cout << "Button pressed: brightness " << levels[step] << " %" << std::endl; } } write(pwm + "/duty_cycle", 0); write(pwm + "/enable", 0); std::cout << "\nStopped. PWM disabled." << std::endl; return 0; } |
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:
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.
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
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
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.
