Skip to content

Commit

Permalink
feat: ADC v2 calibrate
Browse files Browse the repository at this point in the history
  • Loading branch information
decaday committed Nov 23, 2024
1 parent 7728acd commit 9d9e274
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/adc/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl<'d, T: Instance> Adc<'d, T> {
// tstab = 14 * 1/fadc
blocking_delay_us(1);

Self::calibration();
Self::calibrate();

// A.7.2 ADC enable sequence code example
// if T::regs().isr().read().adrdy() {
Expand All @@ -97,7 +97,7 @@ impl<'d, T: Instance> Adc<'d, T> {
}
}

pub fn calibration() {
pub fn calibrate() {
// Precautions
// When the working conditions of the ADC change (VCC changes are the main factor affecting ADC offset shifts, followed by temperature changes), it is recommended to recalibrate the ADC.
// A software calibration process must be added before using the ADC module for the first time.
Expand Down
44 changes: 44 additions & 0 deletions src/adc/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ where
reg.set_extsel(Extsel::SWSTART);
});

Self::calibrate();

T::regs().cr2().modify(|reg| {
reg.set_adon(true);
});
Expand Down Expand Up @@ -206,6 +208,48 @@ where
_ => T::regs().smpr3().modify(|reg| reg.set_smp((ch - 20) as _, sample_time)),
}
}


/// Perform ADC automatic self-calibration
pub fn calibrate() {
T::regs().cr2().modify(|reg| {
reg.set_adon(false);
});

while T::regs().cr2().read().adon() { }

// Wait for ADC to be fully disabled
// Compute and wait for required ADC clock cycles

let adc_clock_mhz = 72_u32; // MAX
let cpu_clock_mhz = unsafe { rcc::get_freqs() }.sys.to_hertz().unwrap().0 / 1_000_000;
#[cfg(py32f072)]
let precalibration_cycles = 2_u32;

let delay_us = (precalibration_cycles * adc_clock_mhz) / cpu_clock_mhz;
blocking_delay_us(delay_us);

// Check if ADC is enabled
if T::regs().cr2().read().adon() {
panic!();
}

// Reset calibration
T::regs().cr2().modify(|reg| {
reg.set_rstcal(true);
});

// Wait for calibration reset to complete
while T::regs().cr2().read().rstcal() { }

// Start calibration
T::regs().cr2().modify(|reg| {
reg.set_cal(true);
});

// Wait for calibration to complete
while T::regs().cr2().read().cal() { }
}
}

impl<'d, T: Instance> Drop for Adc<'d, T> {
Expand Down

0 comments on commit 9d9e274

Please sign in to comment.