Before going into further detail, let’s first define what base signal should be generated and repeated by the PWM peripheral. Consider the signal shown in the figure below.
Following variables define the base signal,
HIGH
.LOW
.Most of the PWM peripheral implementations allow the configuration of the base signal through 3 values. For the RP2040 μC, the three values are called
DIV
TOP
CC
The terminology might be slightly different in each μC’s datasheet although the operation is pretty similar.
DIV
As discussed previously, every μC relies on a clock signal, referred to as system clock in this section, to function correctly. The clock signal frequency for RP2040 is set to 125MHz by default. The Clock Divider in PWM peripheral takes in this high frequency signal and divides it with a certain number to generate a lower frequency signal, referred to as frequency divided clock in this section. This number is the DIV
value that can be specified through software. For RP2040, this value is split into an 8-bit integer part, $1 \leq$DIV
i
$\leq 255$, and a 4-bit fractional part, $0 \leq$DIV
f
$\leq 15$. Thus, the DIV
value is defined as
And, the frequency of the output clock is
\[\begin{equation*} f_{div} = \frac{f_{sys}}{\mathtt{DIV}_{\mathtt{i}} + \frac{\mathtt{DIV}_{\mathtt{f}}}{16}} \end{equation*}\]Let’s take an example. Following animation show the output signal from the clock divider if the integer part is set to 7 and the fractional part is set to 9. Basically, 7.5625 cycles of the system clock make one cycle of the frequency divided clock.
Clock
Divider
79⁄16
TOP
The number of cycles, of the frequency divided clock, generated by the clock divider is counted and stored as a CTR
value. However, this value can only reach TOP
value, after which the CTR
value falls back to 0 and starts increasing again.
≤
It takes one clock cycle for the `CTR` value to fall back to 0.
The time it takes for the CTR
value to start from 0, reach the TOP
value, and then fall back to 0, is the time period $p$ of the PWM base signal. It can be defined as
The TOP
value is a 16-bit number, i.e. 0 $\leq$ TOP
$\leq$ 65535.
CC
Now that the time period of the base signal is defined, all that is remaining is to define for how long the signal will be HIGH
or LOW
. This is done using the counter compare value. The GPIO, that is being controlled by the PWM peripheral, is set to HIGH
when the CTR
value starts increasing from 0. This HIGH
state is maintained until the CTR
value becomes equal to the CC
value. The GPIO is set to LOW
when this happens.
This defines both the duty cycle, $D$, and the HIGH
time, $t_H$, of the base signal as given below
The CC
value is also a 16-bit number, i.e. $0 \leq$ CC
$\leq 65535$. Also note that if CC
is 0 then the PWM output is always LOW
and if CC
> TOP
then the PWM output is always HIGH
.
hardware_pwm
Library Functions