use esp_hal::{
gpio::{AnyPin, DriveMode},
ledc::{
channel::{self, Channel, ChannelIFace},
timer::{self, Timer, TimerIFace},
LSGlobalClkSource, Ledc, LowSpeed,
},
time::Rate,
};
pub struct Buzzer<'t> {
timer: Timer<'t, LowSpeed>,
channel: Channel<'t, LowSpeed>,
}
impl<'t> Buzzer<'t> {
pub fn new(mut ledc: Ledc<'t>, pin: AnyPin<'t>) -> Self {
ledc.set_global_slow_clock(LSGlobalClkSource::APBClk);
let channel = ledc.channel(channel::Number::Channel0, pin);
let timer = ledc.timer::<LowSpeed>(timer::Number::Timer0);
Buzzer { timer, channel }
}
fn configure(&'t mut self, freq: Rate, duty: u8) {
self.timer
.configure(timer::config::Config {
duty: timer::config::Duty::Duty5Bit,
clock_source: timer::LSClockSource::APBClk,
frequency: freq,
})
.unwrap();
self.channel
.configure(channel::config::Config {
timer: &self.timer,
duty_pct: duty,
drive_mode: DriveMode::PushPull,
})
.unwrap();
}
pub fn set_frequency(&'t mut self, freq: Rate) {
self.configure(freq, 50);
}
pub fn off(&'t mut self) {
self.configure(Rate::from_hz(1000), 0);
}
}