Skip to content

Commit 7e39da5

Browse files
authored
Merge pull request #9398 from timchinowsky/main
fix off-by-one in PWM frequency setting
2 parents 882fa27 + 6c1227e commit 7e39da5

File tree

5 files changed

+101
-3
lines changed

5 files changed

+101
-3
lines changed

ports/raspberrypi/common-hal/pwmio/PWMOut.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,10 @@ extern void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uin
176176
} else {
177177
compare_count = ((uint32_t)duty * self->top + MAX_TOP / 2) / MAX_TOP;
178178
}
179+
// do not allow count to be 0 (due to rounding) unless duty 0 was requested
180+
if (compare_count == 0 && duty != 0) {
181+
compare_count = 1;
182+
}
179183
// compare_count is the CC register value, which should be TOP+1 for 100% duty cycle.
180184
pwm_set_chan_level(self->slice, self->ab_channel, compare_count);
181185
}
@@ -218,8 +222,8 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, uint32_t fr
218222
pwm_set_clkdiv_int_frac(self->slice, div16 / 16, div16 % 16);
219223
pwm_set_wrap(self->slice, self->top);
220224
} else {
221-
uint32_t top = common_hal_mcu_processor_get_frequency() / frequency;
222-
self->actual_frequency = common_hal_mcu_processor_get_frequency() / top;
225+
uint32_t top = common_hal_mcu_processor_get_frequency() / frequency - 1;
226+
self->actual_frequency = common_hal_mcu_processor_get_frequency() / (top + 1);
223227
self->top = MIN(MAX_TOP, top);
224228
pwm_set_clkdiv_int_frac(self->slice, 1, 0);
225229
// Set TOP register. For 100% duty cycle, CC must be set to TOP+1.

tests/circuitpython-manual/pwmio/README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
This directory contains tools for testing CircuitPython's PWM API. Running the tests involves three steps:
44

5-
1. [CircuitPython PWM test code `code.py`](code.py) is run on the board to be tested.
5+
1. [CircuitPython PWM test code `code_ramps.py`](code_ramps.py) is run on the board to be tested.
66
2. As the code runs, the state of the PWM signal is logged by a logic analyzer (I used a Saleae Logic Pro 8).
77
3. Data collected by the logic analyzer is analyzed and plotted into a PNG image by [CPython code `duty.py`](duty.py).
88

@@ -37,3 +37,9 @@ These tests can be used to assess how well the PWM API delivers expected behavio
3737
The plot at the top of this page depicts data PWM gathered from a device with an API that displays all of the expected behavior listed above. The plots below show how the tools reveal flaws in the behavior of PWM APIs that are not as complete.
3838

3939
<img src="pwm_flaw_explainer.png">
40+
41+
## Testing always-off and always-on PWM extremes
42+
43+
The procedure described above does not test item 2 above, i.e. the ability of the API to support duty cycles of 0% and 100%. A different code file, (code_extremes.py) provides for this. This code cycles through PWM duty cycles of 32767, 65535, 1, 65534, and 0, repeating the sequence at six frequencies from 100 Hz to 10MHz. When viewed on a logic analyzer, the PWM output should look like the figure below. 100% and 0% PWM result from duty cycle settings of 65535 and 0, (and only from those settings, in accordance with item 3 above.)
44+
45+
<img src="pwm_extremes_explainer.png">
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import board
2+
import pwmio
3+
import random
4+
import time
5+
import microcontroller
6+
import os
7+
import sys
8+
import random
9+
10+
exponents = [
11+
2,
12+
3,
13+
4,
14+
5,
15+
6,
16+
7,
17+
]
18+
19+
freqs = [int(10**f) for f in exponents]
20+
21+
top = 65536
22+
den = 10
23+
duties = [32767, 65535, 1, 65534, 0, 0]
24+
freq_duration = 1.2
25+
duty_duration = 0.2
26+
27+
print("\n\n")
28+
board_name = sys.implementation[2]
29+
30+
pins = {
31+
"Feather RP2040": (("D4", ""),),
32+
"RP2040-Zero": (("GP15", ""),),
33+
"Grand Central": (("D51", "TCC"), ("A15", "TC")),
34+
"Metro M0": (("A2", "TC"), ("A3", "TCC")),
35+
"ESP32-S3-DevKit": (("IO6", ""),), # marked D5 on board for XIAO-ESP32-s3
36+
"Feather ESP32-S2": (("D9", ""),),
37+
"XIAO nRF52840": (("D9", ""),),
38+
}
39+
40+
for board_key in pins:
41+
if board_key in board_name:
42+
pins_to_use = pins[board_key]
43+
break
44+
45+
while True:
46+
for pin_name, pin_type in pins_to_use:
47+
pin = getattr(board, pin_name)
48+
print('title="', end="")
49+
print(f"{board_name} at {microcontroller.cpu.frequency} Hz, pin {pin_name}", end="")
50+
if len(pin_type) > 0:
51+
print(f" ({pin_type})", end="")
52+
print('",')
53+
print(f'subtitle="{freq_duration:0.1f}s per frequency",')
54+
print(f'version="{sys.version}",')
55+
print("freq_calls=", end="")
56+
pwm = pwmio.PWMOut(pin, variable_frequency=True)
57+
t0 = time.monotonic()
58+
duty_time = t0 + duty_duration
59+
print("(", end="")
60+
offset = 0
61+
increment = 1
62+
for freq in freqs:
63+
i = 0
64+
try:
65+
pwm.frequency = freq
66+
except ValueError:
67+
break
68+
freq_time = t0 + freq_duration
69+
duty_time = t0 + duty_duration
70+
j = 0
71+
while time.monotonic() < freq_time:
72+
duty = duties[j]
73+
pwm.duty_cycle = duty
74+
while time.monotonic() < duty_time and time.monotonic() < freq_time:
75+
pass
76+
j += 1
77+
j = min(j, len(duties) - 1)
78+
duty_time += duty_duration
79+
i += 1
80+
if time.monotonic() > freq_time:
81+
break
82+
t0 = freq_time
83+
print(f"({freq}, {i/freq_duration:.0f}), ", end="")
84+
print(")")
85+
print("done.")
86+
pwm.deinit()
87+
time.sleep(5)

tests/circuitpython-manual/pwmio/code.py renamed to tests/circuitpython-manual/pwmio/code_ramps.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
board_name = sys.implementation[2]
4040

4141
pins = {
42+
"Feather RP2040": (("D4", ""),),
4243
"RP2040-Zero": (("GP15", ""),),
4344
"Grand Central": (("D51", "TCC"), ("A15", "TC")),
4445
"Metro M0": (("A2", "TC"), ("A3", "TCC")),
Loading

0 commit comments

Comments
 (0)