Improve ADC configuration options

This commit is contained in:
chemicstry
2022-07-27 01:17:26 +03:00
parent 84cffc751a
commit 046778fc53
4 changed files with 68 additions and 34 deletions

View File

@ -7,7 +7,10 @@ use crate::adc::{AdcPin, Instance};
use crate::time::Hertz;
use crate::Peripheral;
pub const VDDA_CALIB_MV: u32 = 3000;
/// Default VREF voltage used for sample conversion to millivolts.
pub const VREF_DEFAULT_MV: u32 = 3300;
/// VREF voltage used for factory calibration of VREFINTCAL register.
pub const VREF_CALIB_MV: u32 = 3300;
#[cfg(not(any(rcc_f4, rcc_f7)))]
fn enable() {
@ -47,7 +50,7 @@ impl Resolution {
}
}
fn to_max_count(&self) -> u32 {
pub fn to_max_count(&self) -> u32 {
match self {
Resolution::TwelveBit => (1 << 12) - 1,
Resolution::TenBit => (1 << 10) - 1,
@ -57,9 +60,9 @@ impl Resolution {
}
}
pub struct Vref;
impl<T: Instance> AdcPin<T> for Vref {}
impl<T: Instance> super::sealed::AdcPin<T> for Vref {
pub struct VrefInt;
impl<T: Instance> AdcPin<T> for VrefInt {}
impl<T: Instance> super::sealed::AdcPin<T> for VrefInt {
fn channel(&self) -> u8 {
17
}
@ -150,7 +153,7 @@ impl Prescaler {
pub struct Adc<'d, T: Instance> {
sample_time: SampleTime,
calibrated_vdda: u32,
vref: u32,
resolution: Resolution,
phantom: PhantomData<&'d mut T>,
}
@ -180,7 +183,7 @@ where
Self {
sample_time: Default::default(),
resolution: Resolution::default(),
calibrated_vdda: VDDA_CALIB_MV,
vref: VREF_DEFAULT_MV,
phantom: PhantomData,
}
}
@ -193,9 +196,16 @@ where
self.resolution = resolution;
}
/// Set VREF, which is used for [to_millivolts()] conversion.
///
/// Use this if you have a known precise VREF (VDDA) pin reference voltage.
pub fn set_vref(&mut self, vref: u32) {
self.vref = vref;
}
/// Convert a measurement to millivolts
pub fn to_millivolts(&self, sample: u16) -> u16 {
((u32::from(sample) * self.calibrated_vdda) / self.resolution.to_max_count()) as u16
((u32::from(sample) * self.vref) / self.resolution.to_max_count()) as u16
}
/// Perform a single conversion.