Buzzer (beep)
This module controls the buzzer to produce sound, using ESP32 hardware PWM (LEDC) for frequency-controlled sound. It supports timed stop, stop, and release functions.
- The buzzer is fixedly connected to GPIO12
Methods
1. beep.init()
Function: Initialize the buzzer module. It must be initialized before first use. If you don't call it manually, beep.tone() will also initialize it automatically.
Example:
import beep
beep.init()
2. beep.tone(freq, duration_ms)
Function: Make the buzzer sound. It emits a sound at the specified frequency (Hz) and stops automatically after the specified duration (ms).
Arguments:
| Argument | Type | Description |
|---|---|---|
| freq | int | Sound frequency (in Hz) |
| duration_ms | int | Duration (in milliseconds) |
Example:
import beep
beep.tone(1000, 500) # emit a 1000Hz sound for 500ms
3. beep.stop()
Function: Immediately stop the buzzer (manual stop, regardless of whether the timer is still counting down).
Example:
beep.stop()
4. beep.deinit()
Function: Release buzzer resources, stop PWM, and delete the timer. You must re-initialize before using it again.
Example:
beep.deinit()
Simple Usage Example
import beep
# Initialize the buzzer
beep.init()
# Emit a 2kHz sound for 300ms
beep.tone(2000, 300)
# Manually stop early
beep.stop()
# Release resources
beep.deinit()
⚠ Notes
- The buzzer pin is fixed to GPIO12.
- Each sound call updates the frequency and timer.
- If
init()is not called beforetone(), the module initializes itself automatically. - Not reentrant: wait for the previous
tone()to finish before emitting a new tone, otherwise it may be overwritten. - Uses hardware PWM for high precision and a wide frequency range.
Module Hardware Parameters
| Parameter | Value |
|---|---|
| GPIO | 12 |
| PWM Timer | LEDC_TIMER_1 |
| PWM Channel | LEDC_CHANNEL_1 |
| Duty | 50% (internal fixed 512 / 1024) |