Pulse Width Modulation (PWM)¶
PWM (Pulse Width Modulation) is a method of controlling the power delivered to a device—such as a fan or a dew heater—by rapidly switching the power on and off instead of reducing the voltage.
For a fan, PWM allows you to control the speed. The controller sends a square-wave signal (often at a fixed frequency), and by changing the duty cycle (the percentage of time the signal is “on” during each cycle), the fan receives more or less average power:
- Low duty cycle → fan spins slowly
- High duty cycle → fan spins faster
- 100% duty cycle → full speed
For a dew heater, PWM controls the amount of heat produced. Rather than running continuously, the heater is turned on and off many times per second:
- Low duty cycle → gentle warming (prevents dew with minimal power)
- Higher duty cycle → more heat
- 100% duty cycle → maximum heating
Why PWM is used instead of lowering voltage
- More efficient: Less energy wasted as heat in the controller
- Better control: Fine-grained adjustment of speed/temperature
- Consistent performance: Devices still receive full voltage during “on” pulses
- Reduced stress: Especially important for fans that may stall at low voltages
In short, PWM lets you precisely and efficiently control output power without sacrificing performance or wasting energy.
Which pins should you use¶
The best are pins 18 and 19
Setting up PWM on Raspberry Pi 4 and Raspberry Pi 5¶
The Raspberry Pi provides hardware PWM (preferred for fans, heaters, and LEDs) and software PWM (less accurate, higher CPU usage). For driving a fan or dew heater, always use hardware PWM.
Hardware PWM vs Software PWM¶
-
Hardware PWM
Generated by dedicated hardware. Stable frequency, low CPU usage, ideal for power control. -
Software PWM
Generated by the CPU. Timing can jitter under load, not recommended for heaters or fans.
Raspberry Pi 4 – Hardware PWM Setup¶
The Raspberry Pi 4 uses the BCM2711 SoC, which provides two hardware PWM channels via the bcm2835-pwm driver.
PWM-capable GPIOs (Pi 4)¶
| GPIO | Pin | Channel |
|---|---|---|
| GPIO12 | Pin 32 | PWM0 |
| GPIO13 | Pin 33 | PWM1 |
| GPIO18 | Pin 12 | PWM0 |
| GPIO19 | Pin 35 | PWM1 |
Enable PWM (Pi 4)¶
Edit the boot configuration file:
sudo nano /boot/config.txt
Add:
dtoverlay=pwm-2chan
Reboot:
sudo reboot
Raspberry Pi 5 – Hardware PWM Setup¶
Raspberry Pi 5 introduces a new I/O controller (RP1), so PWM is provided by a different driver.
Enable PWM (Pi 5)¶
Edit:
sudo nano /boot/firmware/config.txt
Add:
dtoverlay=rp1-pwm
Reboot:
sudo reboot
Hardware Warning¶
Never connect a fan or heater directly to a GPIO pin.
Always use:
- A logic-level N-channel MOSFET (for heaters)
- A suitable fan driver or transistor
- A flyback diode (for inductive loads such as motors)