PWM
This guide shows how to find a PWM pin on the board's 40-pin header and generate a signal from the Linux shell. You'll set the frequency and duty cycle, change the duty cycle while the output is running, and stop the signal.
Before You Start
Open a shell on the board as root.
Run the commands in the same shell so the variables stay available. You can
use an oscilloscope to view the waveform.
Check the header orientation, pinout, and PWM output voltage before using the header. Power off the board before attaching test equipment and avoid shorting adjacent pins.
See Hardware Resources for the board datasheet and schematic.Board Header Mapping
The diagram shows each pin's physical number and default function. This example uses physical pin 32 for PWM and pin 6 as ground for the oscilloscope.
Set an Output
| Header pin | PWM controller | Linux PWM channel |
|---|---|---|
| 32 | f7f20000.pwm | 0 |
| 33 | f7f20000.pwm | 1 |
List the pwmchip entries under /sys/class/pwm/.
Look for f7f20000.pwm in the target path
on the right.
ls -ld /sys/class/pwm/pwmchip*
Replace pwmchipN below with the matching entry's name. To use another pin
from the table, set CHANNEL to the corresponding value.
PWMCHIP=/sys/class/pwm/pwmchipN
CHANNEL=0
PWM="$PWMCHIP/pwm$CHANNEL"
Export the channel and generate a 1 kHz signal with a 50% duty cycle.
A period of 1000000 nanoseconds is 1 ms. A duty_cycle of 500000
nanoseconds makes the signal active for half that period.
echo "$CHANNEL" > "$PWMCHIP/export" &&
echo 1000000 > "$PWM/period" &&
echo 500000 > "$PWM/duty_cycle" &&
echo 1 > "$PWM/enable"
If export fails, stop and check the chip and channel. A channel in use is
unavailable for export. If a later write fails, run just the unexport command
under Stop the Output before trying again.
Change the Duty Cycle
Write 250000 to duty_cycle to set the duty cycle to 25%. The frequency
stays at 1 kHz. On an oscilloscope, each active pulse lasts about 250 µs.
echo 250000 > "$PWM/duty_cycle"
Stop the Output
Set the duty cycle to zero, disable PWM, and release the channel.
echo 0 > "$PWM/duty_cycle" &&
echo 0 > "$PWM/enable" &&
echo "$CHANNEL" > "$PWMCHIP/unexport"