From 52bd24499c0e164fd3525a02514af50e3fc35424 Mon Sep 17 00:00:00 2001
From: Dario Nieuwenhuis <dirbaio@dirbaio.net>
Date: Sat, 13 Apr 2024 03:30:30 +0200
Subject: [PATCH] stm32/adc: update g4 for new pac.

---
 embassy-stm32/src/adc/g4.rs     | 304 ++++++++++++++++++++++++++++++++
 embassy-stm32/src/adc/mod.rs    |  29 ++-
 examples/stm32g4/src/bin/adc.rs |   2 +-
 3 files changed, 332 insertions(+), 3 deletions(-)
 create mode 100644 embassy-stm32/src/adc/g4.rs

diff --git a/embassy-stm32/src/adc/g4.rs b/embassy-stm32/src/adc/g4.rs
new file mode 100644
index 000000000..f6741f019
--- /dev/null
+++ b/embassy-stm32/src/adc/g4.rs
@@ -0,0 +1,304 @@
+#[allow(unused)]
+use pac::adc::vals::{Adcaldif, Difsel, Exten};
+use pac::adccommon::vals::Presc;
+
+use super::{blocking_delay_us, Adc, AdcPin, Instance, InternalChannel, Resolution, SampleTime};
+use crate::time::Hertz;
+use crate::{pac, Peripheral};
+
+/// 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;
+
+/// Max single ADC operation clock frequency
+#[cfg(stm32g4)]
+const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(60);
+#[cfg(stm32h7)]
+const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(50);
+
+#[cfg(stm32g4)]
+const VREF_CHANNEL: u8 = 18;
+#[cfg(stm32g4)]
+const TEMP_CHANNEL: u8 = 16;
+
+#[cfg(stm32h7)]
+const VREF_CHANNEL: u8 = 19;
+#[cfg(stm32h7)]
+const TEMP_CHANNEL: u8 = 18;
+
+// TODO this should be 14 for H7a/b/35
+const VBAT_CHANNEL: u8 = 17;
+
+// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs
+/// Internal voltage reference channel.
+pub struct VrefInt;
+impl<T: Instance> InternalChannel<T> for VrefInt {}
+impl<T: Instance> super::SealedInternalChannel<T> for VrefInt {
+    fn channel(&self) -> u8 {
+        VREF_CHANNEL
+    }
+}
+
+/// Internal temperature channel.
+pub struct Temperature;
+impl<T: Instance> InternalChannel<T> for Temperature {}
+impl<T: Instance> super::SealedInternalChannel<T> for Temperature {
+    fn channel(&self) -> u8 {
+        TEMP_CHANNEL
+    }
+}
+
+/// Internal battery voltage channel.
+pub struct Vbat;
+impl<T: Instance> InternalChannel<T> for Vbat {}
+impl<T: Instance> super::SealedInternalChannel<T> for Vbat {
+    fn channel(&self) -> u8 {
+        VBAT_CHANNEL
+    }
+}
+
+// NOTE (unused): The prescaler enum closely copies the hardware capabilities,
+// but high prescaling doesn't make a lot of sense in the current implementation and is ommited.
+#[allow(unused)]
+enum Prescaler {
+    NotDivided,
+    DividedBy2,
+    DividedBy4,
+    DividedBy6,
+    DividedBy8,
+    DividedBy10,
+    DividedBy12,
+    DividedBy16,
+    DividedBy32,
+    DividedBy64,
+    DividedBy128,
+    DividedBy256,
+}
+
+impl Prescaler {
+    fn from_ker_ck(frequency: Hertz) -> Self {
+        let raw_prescaler = frequency.0 / MAX_ADC_CLK_FREQ.0;
+        match raw_prescaler {
+            0 => Self::NotDivided,
+            1 => Self::DividedBy2,
+            2..=3 => Self::DividedBy4,
+            4..=5 => Self::DividedBy6,
+            6..=7 => Self::DividedBy8,
+            8..=9 => Self::DividedBy10,
+            10..=11 => Self::DividedBy12,
+            _ => unimplemented!(),
+        }
+    }
+
+    fn divisor(&self) -> u32 {
+        match self {
+            Prescaler::NotDivided => 1,
+            Prescaler::DividedBy2 => 2,
+            Prescaler::DividedBy4 => 4,
+            Prescaler::DividedBy6 => 6,
+            Prescaler::DividedBy8 => 8,
+            Prescaler::DividedBy10 => 10,
+            Prescaler::DividedBy12 => 12,
+            Prescaler::DividedBy16 => 16,
+            Prescaler::DividedBy32 => 32,
+            Prescaler::DividedBy64 => 64,
+            Prescaler::DividedBy128 => 128,
+            Prescaler::DividedBy256 => 256,
+        }
+    }
+
+    fn presc(&self) -> Presc {
+        match self {
+            Prescaler::NotDivided => Presc::DIV1,
+            Prescaler::DividedBy2 => Presc::DIV2,
+            Prescaler::DividedBy4 => Presc::DIV4,
+            Prescaler::DividedBy6 => Presc::DIV6,
+            Prescaler::DividedBy8 => Presc::DIV8,
+            Prescaler::DividedBy10 => Presc::DIV10,
+            Prescaler::DividedBy12 => Presc::DIV12,
+            Prescaler::DividedBy16 => Presc::DIV16,
+            Prescaler::DividedBy32 => Presc::DIV32,
+            Prescaler::DividedBy64 => Presc::DIV64,
+            Prescaler::DividedBy128 => Presc::DIV128,
+            Prescaler::DividedBy256 => Presc::DIV256,
+        }
+    }
+}
+
+impl<'d, T: Instance> Adc<'d, T> {
+    /// Create a new ADC driver.
+    pub fn new(adc: impl Peripheral<P = T> + 'd) -> Self {
+        embassy_hal_internal::into_ref!(adc);
+        T::enable_and_reset();
+
+        let prescaler = Prescaler::from_ker_ck(T::frequency());
+
+        T::common_regs().ccr().modify(|w| w.set_presc(prescaler.presc()));
+
+        let frequency = Hertz(T::frequency().0 / prescaler.divisor());
+        info!("ADC frequency set to {} Hz", frequency.0);
+
+        if frequency > MAX_ADC_CLK_FREQ {
+            panic!("Maximal allowed frequency for the ADC is {} MHz and it varies with different packages, refer to ST docs for more information.", MAX_ADC_CLK_FREQ.0 /  1_000_000 );
+        }
+
+        let mut s = Self {
+            adc,
+            sample_time: SampleTime::from_bits(0),
+        };
+        s.power_up();
+        s.configure_differential_inputs();
+
+        s.calibrate();
+        blocking_delay_us(1);
+
+        s.enable();
+        s.configure();
+
+        s
+    }
+
+    fn power_up(&mut self) {
+        T::regs().cr().modify(|reg| {
+            reg.set_deeppwd(false);
+            reg.set_advregen(true);
+        });
+
+        blocking_delay_us(10);
+    }
+
+    fn configure_differential_inputs(&mut self) {
+        T::regs().difsel().modify(|w| {
+            for n in 0..20 {
+                w.set_difsel(n, Difsel::SINGLEENDED);
+            }
+        });
+    }
+
+    fn calibrate(&mut self) {
+        T::regs().cr().modify(|w| {
+            w.set_adcaldif(Adcaldif::SINGLEENDED);
+        });
+
+        T::regs().cr().modify(|w| w.set_adcal(true));
+
+        while T::regs().cr().read().adcal() {}
+    }
+
+    fn enable(&mut self) {
+        T::regs().isr().write(|w| w.set_adrdy(true));
+        T::regs().cr().modify(|w| w.set_aden(true));
+        while !T::regs().isr().read().adrdy() {}
+        T::regs().isr().write(|w| w.set_adrdy(true));
+    }
+
+    fn configure(&mut self) {
+        // single conversion mode, software trigger
+        T::regs().cfgr().modify(|w| {
+            w.set_cont(false);
+            w.set_exten(Exten::DISABLED);
+        });
+    }
+
+    /// Enable reading the voltage reference internal channel.
+    pub fn enable_vrefint(&self) -> VrefInt {
+        T::common_regs().ccr().modify(|reg| {
+            reg.set_vrefen(true);
+        });
+
+        VrefInt {}
+    }
+
+    /// Enable reading the temperature internal channel.
+    pub fn enable_temperature(&self) -> Temperature {
+        T::common_regs().ccr().modify(|reg| {
+            reg.set_vsenseen(true);
+        });
+
+        Temperature {}
+    }
+
+    /// Enable reading the vbat internal channel.
+    pub fn enable_vbat(&self) -> Vbat {
+        T::common_regs().ccr().modify(|reg| {
+            reg.set_vbaten(true);
+        });
+
+        Vbat {}
+    }
+
+    /// Set the ADC sample time.
+    pub fn set_sample_time(&mut self, sample_time: SampleTime) {
+        self.sample_time = sample_time;
+    }
+
+    /// Set the ADC resolution.
+    pub fn set_resolution(&mut self, resolution: Resolution) {
+        T::regs().cfgr().modify(|reg| reg.set_res(resolution.into()));
+    }
+
+    /// Perform a single conversion.
+    fn convert(&mut self) -> u16 {
+        T::regs().isr().modify(|reg| {
+            reg.set_eos(true);
+            reg.set_eoc(true);
+        });
+
+        // Start conversion
+        T::regs().cr().modify(|reg| {
+            reg.set_adstart(true);
+        });
+
+        while !T::regs().isr().read().eos() {
+            // spin
+        }
+
+        T::regs().dr().read().0 as u16
+    }
+
+    /// Read an ADC pin.
+    pub fn read<P>(&mut self, pin: &mut P) -> u16
+    where
+        P: AdcPin<T>,
+        P: crate::gpio::Pin,
+    {
+        pin.set_as_analog();
+
+        self.read_channel(pin.channel())
+    }
+
+    /// Read an ADC internal channel.
+    pub fn read_internal(&mut self, channel: &mut impl InternalChannel<T>) -> u16 {
+        self.read_channel(channel.channel())
+    }
+
+    fn read_channel(&mut self, channel: u8) -> u16 {
+        // Configure channel
+        Self::set_channel_sample_time(channel, self.sample_time);
+
+        #[cfg(stm32h7)]
+        {
+            T::regs().cfgr2().modify(|w| w.set_lshift(0));
+            T::regs()
+                .pcsel()
+                .write(|w| w.set_pcsel(channel as _, Pcsel::PRESELECTED));
+        }
+
+        T::regs().sqr1().write(|reg| {
+            reg.set_sq(0, channel);
+            reg.set_l(0);
+        });
+
+        self.convert()
+    }
+
+    fn set_channel_sample_time(ch: u8, sample_time: SampleTime) {
+        let sample_time = sample_time.into();
+        if ch <= 9 {
+            T::regs().smpr().modify(|reg| reg.set_smp(ch as _, sample_time));
+        } else {
+            T::regs().smpr2().modify(|reg| reg.set_smp((ch - 10) as _, sample_time));
+        }
+    }
+}
diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs
index 24dd7cc3c..12c5751bd 100644
--- a/embassy-stm32/src/adc/mod.rs
+++ b/embassy-stm32/src/adc/mod.rs
@@ -12,6 +12,7 @@
 #[cfg_attr(adc_v2, path = "v2.rs")]
 #[cfg_attr(any(adc_v3, adc_g0, adc_h5), path = "v3.rs")]
 #[cfg_attr(adc_v4, path = "v4.rs")]
+#[cfg_attr(adc_g4, path = "g4.rs")]
 mod _version;
 
 #[allow(unused)]
@@ -79,13 +80,37 @@ pub(crate) fn blocking_delay_us(us: u32) {
 }
 
 /// ADC instance.
-#[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0, adc_h5)))]
+#[cfg(not(any(
+    adc_f1,
+    adc_v1,
+    adc_l0,
+    adc_v2,
+    adc_v3,
+    adc_v4,
+    adc_g4,
+    adc_f3,
+    adc_f3_v1_1,
+    adc_g0,
+    adc_h5
+)))]
 #[allow(private_bounds)]
 pub trait Instance: SealedInstance + crate::Peripheral<P = Self> {
     type Interrupt: crate::interrupt::typelevel::Interrupt;
 }
 /// ADC instance.
-#[cfg(any(adc_f1, adc_v1, adc_l0, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0, adc_h5))]
+#[cfg(any(
+    adc_f1,
+    adc_v1,
+    adc_l0,
+    adc_v2,
+    adc_v3,
+    adc_v4,
+    adc_g4,
+    adc_f3,
+    adc_f3_v1_1,
+    adc_g0,
+    adc_h5
+))]
 #[allow(private_bounds)]
 pub trait Instance: SealedInstance + crate::Peripheral<P = Self> + crate::rcc::RccPeripheral {
     type Interrupt: crate::interrupt::typelevel::Interrupt;
diff --git a/examples/stm32g4/src/bin/adc.rs b/examples/stm32g4/src/bin/adc.rs
index 68b54e406..3de38cbd6 100644
--- a/examples/stm32g4/src/bin/adc.rs
+++ b/examples/stm32g4/src/bin/adc.rs
@@ -29,7 +29,7 @@ async fn main(_spawner: Spawner) {
     info!("Hello World!");
 
     let mut adc = Adc::new(p.ADC2);
-    adc.set_sample_time(SampleTime::CYCLES32_5);
+    adc.set_sample_time(SampleTime::CYCLES24_5);
 
     loop {
         let measured = adc.read(&mut p.PA7);