Skip to content

fix(examples): Migrate buzzer tone() to hardware PWM Timer. #254

@nedseb

Description

@nedseb

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

  • Validate PWM tone on hardware with metal_detector.py
  • Migrate dpad_piano.py to use hardware PWM Timer
  • Check if other examples use software tone (future PRs)

Related

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions