From 71851dc327567710a6d1314bb227633c9820aef7 Mon Sep 17 00:00:00 2001 From: Richard Meadows <962920+richardeoin@users.noreply.github.com> Date: Tue, 29 Mar 2022 21:47:57 +0200 Subject: [PATCH] Add slope method to ADC and depreciate max_sample Closes #343 --- examples/adc.rs | 2 +- examples/adc12_parallel.rs | 4 ++-- src/adc.rs | 24 ++++++++++++++++++++++-- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/examples/adc.rs b/examples/adc.rs index 2a36fc6d..7722f743 100644 --- a/examples/adc.rs +++ b/examples/adc.rs @@ -76,7 +76,7 @@ fn main() -> ! { info!( "ADC reading: {}, voltage for nucleo: {}", data, - data as f32 * (3.3 / adc1.max_sample() as f32) + data as f32 * (3.3 / adc1.slope() as f32) ); } } diff --git a/examples/adc12_parallel.rs b/examples/adc12_parallel.rs index 97a34c91..ee51e330 100644 --- a/examples/adc12_parallel.rs +++ b/examples/adc12_parallel.rs @@ -87,12 +87,12 @@ fn main() -> ! { info!( "ADC1 reading: {}, voltage for Daisy pin X: {}", data1, - data1 as f32 * (3.3 / adc1.max_sample() as f32) + data1 as f32 * (3.3 / adc1.slope() as f32) ); info!( "ADC2 reading: {}, voltage for Daisy pin X: {}", data2, - data2 as f32 * (3.3 / adc2.max_sample() as f32) + data2 as f32 * (3.3 / adc2.slope() as f32) ); } } diff --git a/src/adc.rs b/src/adc.rs index 8b56f703..36b1dba2 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -787,12 +787,32 @@ macro_rules! adc_hal { self.lshift = lshift; } - /// Returns the largest possible sample value for the current settings + /// Returns the largest possible sample value for the current ADC configuration + /// + /// Using this value as the denominator when calculating + /// transfer functions results in a gain error, and thus should + /// be avoided. Use the [slope](#method.slope) method instead. + #[deprecated(since = "0.12.0", note = "See the slope() method instead")] pub fn max_sample(&self) -> u32 { ((1 << self.get_resolution().number_of_bits() as u32) - 1) << self.get_lshift().value() as u32 } - /// Returns the offset calibration value for single ended channel + /// Returns the slope for the current ADC configuration. 1 LSB = Vref / slope + /// + /// This value can be used in calcuations involving the transfer function of + /// the ADC. For example, to calculate an estimate for the + /// applied voltage of an ADC channel referenced to voltage + /// `vref` + /// + /// ``` + /// let v = adc.read(&ch).unwrap() as f32 * vref / adc.slope() as f32; + /// ``` + pub fn slope(&self) -> u32 { + 1 << (self.get_resolution().number_of_bits() as u32 + self.get_lshift().value() as u32) + } + + + /// Returns the offset calibration value for single ended channel pub fn read_offset_calibration_value(&self) -> AdcCalOffset { AdcCalOffset(self.rb.calfact.read().calfact_s().bits()) }