Access the hardware PWM of a Raspberry Pi with Python. More lightweight than alternatives.
- On the Raspberry Pi, add
dtoverlay=pwm-2chan
to/boot/config.txt
. This defaults toGPIO_18
as the pin forPWM0
andGPIO_19
as the pin forPWM1
.- Alternatively, you can change
GPIO_18
toGPIO_12
andGPIO_19
toGPIO_13
usingdtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4
.
- Alternatively, you can change
- Reboot your Raspberry Pi.
- You can check everything is working on running
lsmod | grep pwm
and looking forpwm_bcm2835
- You can check everything is working on running
- Install this library:
sudo pip3 install rpi-hardware-pwm
from rpi_hardware_pwm import HardwarePWM
pwm = HardwarePWM(pwm_channel=0, hz=60)
pwm.start(100) # full duty cycle
pwm.change_duty_cycle(50)
pwm.change_frequency(25_000)
pwm.stop()
The original code is from jdimpson/syspwm, We've updated it to Python3 and
made it look like the RPi.GPIO
library's API (but more Pythonic than that.), and we use it in Pioreactor bioreactor system.