feat: 蜂鸣。

This commit is contained in:
Ivan Li 2022-04-21 21:39:26 +08:00
parent 64f88adf4b
commit 70ca1b1241
3 changed files with 74 additions and 15 deletions

57
src/beep.rs Normal file
View File

@ -0,0 +1,57 @@
use esp_idf_hal::gpio::OutputPin;
use esp_idf_hal::ledc;
use esp_idf_hal::ledc::{config::TimerConfig, Channel, Timer};
use esp_idf_hal::peripherals::Peripherals;
use esp_idf_hal::prelude::*;
use esp_idf_sys::EspError;
use std::thread;
use std::time::Duration;
type LedcChannel<P: OutputPin, T: ledc::HwTimer, C: ledc::HwChannel> = Channel<C, T, Timer<T>, P>;
pub struct Beep<P: OutputPin, T: ledc::HwTimer, C: ledc::HwChannel> {
state: bool,
stopped: bool,
channel: LedcChannel<P, T, C>,
}
impl<P: OutputPin, T: ledc::HwTimer, C: ledc::HwChannel> Beep<P, T, C> {
pub fn new(pin: P, timer: T, channel: C) -> Result<Self, EspError> {
return Ok(Beep {
state: false,
stopped: false,
channel: Self::init_channel(pin, timer, channel)?,
});
}
fn init_channel(pin: P, timer: T, channel: C) -> Result<LedcChannel<P, T, C>, EspError> {
let config = TimerConfig::default().frequency(1.kHz().into());
let timer = Timer::new(timer, &config)?;
let mut channel = Channel::new(channel, timer, pin)?;
let max_duty = channel.get_max_duty();
channel.set_duty(max_duty * 3 / 4)?;
return Ok(channel);
}
pub fn toggle(&mut self) -> Result<(), EspError> {
self.state = !self.state;
if self.state {
self.channel.set_duty(50)
} else {
self.channel.set_duty(0)
}
}
pub fn play(&mut self) {
loop {
if self.stopped {
break;
}
self.toggle().unwrap();
thread::sleep(Duration::from_millis(500));
self.toggle().unwrap();
thread::sleep(Duration::from_millis(1500));
}
}
}

View File

@ -1 +0,0 @@
pub mod blink;

View File

@ -1,8 +1,8 @@
use esp_idf_sys as _;
use std::thread;
use ups_esp32c3_rust::beep;
use ups_esp32c3_rust::blink;
mod beep;
mod blink;
fn main() {
// Temporary. Will disappear once ESP-IDF 4.4 is released, but for now it is necessary to call this function once,
// or else some patches to the runtime implemented by esp-idf-sys might not link properly.
@ -10,22 +10,25 @@ fn main() {
let peripherals = esp_idf_hal::peripherals::Peripherals::take().unwrap();
let gpio5 = peripherals.pins.gpio5;
let gpio6 = peripherals.pins.gpio6;
let ledc_timer0 = peripherals.ledc.timer0;
let ledc_channel0 = peripherals.ledc.channel0;
thread::spawn(move || {
let mut blink = blink::Blink::new(
peripherals
.pins
.gpio5
.into_output()
.expect("Failed to set GPIO5 as output"),
);
let mut blink =
blink::Blink::new(gpio5.into_output().expect("Failed to set GPIO5 as output"));
blink.play();
});
beep::Beep::new(peripherals
.pins
.gpio5
.into_output()
.expect("Failed to set GPIO6 as output"),);
thread::spawn(move || {
let mut beep = beep::Beep::new(
gpio6.into_output().expect("Failed to set GPIO6 as output"),
ledc_timer0,
ledc_channel0,
)
.expect("Failed to create beep");
beep.play();
});
println!("Hello, world!");
}