pybadge_high/
sound.rs

1use cortex_m::peripheral::NVIC;
2use edgebadge::{
3	gpio::{
4		v2::{PA02, PA27},
5		*
6	},
7	pac,
8	pac::TC4 as TC,
9	prelude::*,
10	thumbv7em::timer::TimerCounter,
11	time::Nanoseconds
12};
13use pac::interrupt;
14
15static mut SPAKER_PIN: Option<Pin<PA02, Output<PushPull>>> = None;
16
17pub struct PwmSound {
18	enable: Pin<PA27, Output<PushPull>>,
19	counter: TimerCounter<TC>
20}
21
22impl PwmSound {
23	pub(crate) fn init(
24		enable_pin: Pin<PA27, Output<PushPull>>,
25		speaker_pin: Pin<PA02, Output<PushPull>>,
26		counter: TimerCounter<TC>
27	) -> Self {
28		let mut enable_pin = enable_pin;
29		enable_pin.set_low().unwrap();
30		unsafe { SPAKER_PIN = Some(speaker_pin) };
31		PwmSound {
32			enable: enable_pin,
33			counter
34		}
35	}
36
37	pub fn set_freq<T>(&mut self, freq: T)
38	where
39		T: Into<Nanoseconds>
40	{
41		let mut time: Nanoseconds = freq.into();
42		time.0 = time.0 / 2;
43		self.counter.start(time);
44		self.counter.enable_interrupt();
45	}
46
47	pub fn enable(&mut self) {
48		self.enable.set_high().unwrap();
49		unsafe {
50			NVIC::unmask(interrupt::TC4);
51		}
52	}
53
54	pub fn disable(&mut self) {
55		self.enable.set_low().unwrap();
56		NVIC::mask(interrupt::TC4);
57	}
58}
59
60#[interrupt]
61fn TC4() {
62	//clear intfalg, oterwise interrup is fired again at the next cycle
63	unsafe {
64		TC::ptr()
65			.as_ref()
66			.unwrap()
67			.count16()
68			.intflag
69			.modify(|_, w| w.ovf().set_bit());
70	}
71	unsafe {
72		SPAKER_PIN.as_mut().unwrap().toggle();
73	}
74}