use embedded_hal_02::adc::{Channel, OneShot};
use stm32h7xx_hal as hal;
#[derive(Debug, Copy, Clone)]
pub enum AdcError {
InUse,
}
pub struct AdcChannel<'a, Adc, PIN> {
pin: PIN,
slope: f32,
mutex: &'a spin::Mutex<hal::adc::Adc<Adc, hal::adc::Enabled>>,
}
impl<'a, Adc, PIN> AdcChannel<'a, Adc, PIN>
where
PIN: Channel<Adc, ID = u8>,
hal::adc::Adc<Adc, hal::adc::Enabled>: OneShot<Adc, u32, PIN>,
<hal::adc::Adc<Adc, hal::adc::Enabled> as OneShot<Adc, u32, PIN>>::Error:
core::fmt::Debug,
{
pub fn read_normalized(&mut self) -> Result<f32, AdcError> {
self.read_raw().map(|code| code as f32 / self.slope)
}
pub fn read_raw(&mut self) -> Result<u32, AdcError> {
let mut adc = self.mutex.try_lock().ok_or(AdcError::InUse)?;
Ok(adc.read(&mut self.pin).unwrap())
}
}
pub struct SharedAdc<Adc> {
mutex: spin::Mutex<hal::adc::Adc<Adc, hal::adc::Enabled>>,
slope: f32,
}
impl<Adc> SharedAdc<Adc> {
pub fn new(slope: f32, adc: hal::adc::Adc<Adc, hal::adc::Enabled>) -> Self {
Self {
slope,
mutex: spin::Mutex::new(adc),
}
}
pub fn create_channel<PIN: Channel<Adc, ID = u8>>(
&self,
pin: PIN,
) -> AdcChannel<'_, Adc, PIN> {
AdcChannel {
pin,
slope: self.slope,
mutex: &self.mutex,
}
}
}