Description
Several examples use a software tone() function that generates a square wave by toggling a GPIO pin in a blocking loop. This blocks the CPU during the entire tone duration, preventing other operations (reading sensors, polling buttons) from running concurrently.
Affected examples
| File |
Current approach |
Impact |
lib/mcp23009e/examples/dpad_piano.py |
sleep_us() loop |
CPU blocked during notes — buttons unresponsive while playing |
lib/lis2mdl/examples/metal_detector.py |
Hardware PWM (Timer) |
Already fixed in PR #251 |
Solution
Replace the software tone() with hardware PWM using machine.Timer:
from machine import Pin, Timer
buzzer_tim = Timer(1, freq=1000)
buzzer_ch = buzzer_tim.channel(4, Timer.PWM, pin=Pin("SPEAKER"))
buzzer_ch.pulse_width_percent(0)
def tone(freq, duration_ms=0):
buzzer_tim.freq(freq)
buzzer_ch.pulse_width_percent(50)
if duration_ms:
sleep_ms(duration_ms)
buzzer_ch.pulse_width_percent(0)
def no_tone():
buzzer_ch.pulse_width_percent(0)
The SPEAKER pin is PA11 (TIM1_CH4 on STM32WB55).
Prerequisite
Validate that hardware PWM works on the STeaMi board (Timer 1, channel 4, PA11). This was implemented in metal_detector.py (PR #251) but needs hardware testing by @Charly-sketch.
Tasks
Related
Description
Several examples use a software
tone()function that generates a square wave by toggling a GPIO pin in a blocking loop. This blocks the CPU during the entire tone duration, preventing other operations (reading sensors, polling buttons) from running concurrently.Affected examples
lib/mcp23009e/examples/dpad_piano.pysleep_us()looplib/lis2mdl/examples/metal_detector.pySolution
Replace the software
tone()with hardware PWM usingmachine.Timer:The SPEAKER pin is PA11 (TIM1_CH4 on STM32WB55).
Prerequisite
Validate that hardware PWM works on the STeaMi board (Timer 1, channel 4, PA11). This was implemented in
metal_detector.py(PR #251) but needs hardware testing by @Charly-sketch.Tasks
metal_detector.pydpad_piano.pyto use hardware PWM TimerRelated