Module rppal::pwm

source ·
Expand description

Interface for the PWM peripheral.

RPPAL controls the Raspberry Pi’s PWM peripheral through the pwm sysfs interface.

PWM channels

The BCM283x SoC supports two hardware PWM channels. By default, both channels are disabled. To enable only PWM0 on its default pin (BCM GPIO 18, physical pin 12), add dtoverlay=pwm to /boot/config.txt on Raspberry Pi OS or boot/firmware/usercfg.txt on Ubuntu. If you need both PWM channels, replace pwm with pwm-2chan, which enables PWM0 on BCM GPIO 18 (physical pin 12), and PWM1 on BCM GPIO 19 (physical pin 35). More details on enabling and configuring PWM on other GPIO pins than the default ones can be found in /boot/overlays/README.

The Raspberry Pi’s analog audio output uses both PWM channels. Playing audio and simultaneously accessing a PWM channel may cause issues.

Some of the GPIO pins capable of supporting hardware PWM can also be configured for use with other peripherals. Be careful not to enable two peripherals on the same pin at the same time.

Using PWM without superuser privileges (sudo)

As of kernel version 4.14.34, released on April 16 2018, it’s possible to configure your Raspberry Pi to allow non-root access to PWM. 4.14.34 includes a patch that allows udev to change file permissions when a PWM channel is exported. This will let any user that’s a member of the gpio group configure PWM without having to use sudo.

The udev rules needed to make this work haven’t been patched in yet as of June 2018, but you can easily add them yourself. Make sure you’re running 4.14.34 or later, and append the following snippet to /etc/udev/rules.d/99-com.rules. Reboot the Raspberry Pi afterwards.

SUBSYSTEM=="pwm*", PROGRAM="/bin/sh -c '\
    chown -R root:gpio /sys/class/pwm && chmod -R 770 /sys/class/pwm;\
    chown -R root:gpio /sys/devices/platform/soc/*.pwm/pwm/pwmchip* &&\
    chmod -R 770 /sys/devices/platform/soc/*.pwm/pwm/pwmchip*\
'"

Troubleshooting

Permission denied

If new returns an io::ErrorKind::PermissionDenied error, make sure /sys/class/pwm and all of its subdirectories are owned by root:gpio, the current user is a member of the gpio group and udev is properly configured as mentioned above. Alternatively, you can launch your application using sudo.

Not found

If new returns an io::ErrorKind::NotFound error, you may have forgotten to enable the selected PWM channel. The configuration options to enable either of the two PWM channels are listed above.

Structs

  • Provides access to the Raspberry Pi’s PWM peripheral.

Enums

  • PWM channels.
  • Errors that can occur when accessing the PWM peripheral.
  • Output polarities.

Type Definitions

  • Result type returned from methods that can have pwm::Errors.