Skip to main content

ch32_hal/
adc.rs

1//! ADC, Analog to Digital Converter
2
3#![macro_use]
4
5use core::marker::PhantomData;
6
7use embassy_sync::waitqueue::AtomicWaker;
8
9use crate::pac::adc::vals;
10#[cfg(adc_v3)]
11pub use crate::pac::adc::vals::Pga;
12pub use crate::pac::adc::vals::SampleTime;
13use crate::{peripherals, Peri};
14
15/// ADC bit resolution
16#[cfg(any(adc_v003, adc_ch641))]
17pub const ADC_MAX: u32 = (1 << 10) - 1;
18#[cfg(not(any(adc_v003, adc_ch641)))]
19pub const ADC_MAX: u32 = (1 << 12) - 1;
20
21// No calibration data, voltage should be 1.2V (1.16 to 1.24)
22pub const VREF_INT: u32 = 1200;
23
24pub struct Config {
25    /// Div1 to Div16
26    // raw values are 0 to 0b111
27    pub clkdiv: u8,
28    // TODO: handle "-1"
29    pub channel_count: u8,
30}
31
32impl Default for Config {
33    fn default() -> Self {
34        Self {
35            // Use Divide by 8 as default, maximum is 14 MHz
36            // Up to 144 MHz system clock can be reached
37            // Power on default is Divide by 2,
38            clkdiv: 0b11,
39            channel_count: 1,
40        }
41    }
42}
43
44pub struct State {
45    pub waker: AtomicWaker,
46}
47impl State {
48    pub const fn new() -> Self {
49        Self {
50            waker: AtomicWaker::new(),
51        }
52    }
53}
54
55/// Analog to Digital driver.
56pub struct Adc<'d, T: Instance> {
57    #[allow(unused)]
58    adc: Peri<'d, T>,
59}
60
61impl<'d, T: Instance> Adc<'d, T> {
62    #[allow(unused)]
63    pub fn new(adc: Peri<'d, T>, config: Config) -> Self {
64        T::enable_and_reset();
65
66        // TODO: ADCPRE
67        // CTLR3 not avaiable to CH3V0, CH32V1
68        #[cfg(any(adc_v3, adc_x0))]
69        T::regs().ctlr3().modify(|w| w.set_clk_div(config.clkdiv));
70
71        // clear, only independent mode is supported
72        T::regs().ctlr1().modify(|w| {
73            w.0 = 0;
74        });
75
76        // no external trigger
77        // no continuous mode
78        T::regs().ctlr2().modify(|w| {
79            w.set_align(false); // right aligned
80            w.set_exttrig(true); // external trigger
81            w.set_extsel(vals::Extsel::SWSTART); //  SWSTART Software trigger
82            w.set_cont(false); // single conversion
83        });
84
85        const CHANNEL_COUNT: u8 = 1;
86        T::regs().rsqr1().modify(|w| w.set_l(CHANNEL_COUNT - 1));
87
88        // ADC ON
89        T::regs().ctlr2().modify(|w| w.set_adon(true));
90
91        // start self-calibration
92        #[cfg(any(adc_v1, adc_v3))]
93        {
94            T::regs().ctlr2().modify(|w| w.set_rstcal(true)); // reset calibration
95            while T::regs().ctlr2().read().rstcal() {}
96            T::regs().ctlr2().modify(|w| w.set_cal(true)); // start calibration
97            while T::regs().ctlr2().read().cal() {} // wait for calibration to be done
98        }
99
100        Self { adc }
101    }
102
103    // regular conversion
104    #[cfg(adc_v3)]
105    pub fn configure_channel(&mut self, channel: &mut impl AdcChannel<T>, rank: u8, sample_time: SampleTime, pga: Pga) {
106        channel.set_as_analog();
107
108        let channel = channel.channel();
109
110        // sample time config
111        if channel < 10 {
112            T::regs().samptr2().modify(|w| w.set_smp(channel as usize, sample_time));
113        } else {
114            T::regs()
115                .samptr1()
116                .modify(|w| w.set_smp((channel - 10) as usize, sample_time));
117        }
118
119        // PGA config
120        T::regs().ctlr1().modify(|w| {
121            w.set_pga(pga);
122            if pga != Pga::X1 {
123                w.set_bufen(true);
124            }
125        });
126
127        // regular sequence config
128        debug_assert!(rank > 0 && rank <= 16);
129        if rank < 7 {
130            T::regs()
131                .rsqr3()
132                .modify(|w| w.set_sq((rank - 1) as usize, channel & 0b11111));
133        } else if rank < 13 {
134            T::regs()
135                .rsqr2()
136                .modify(|w| w.set_sq((rank - 7) as usize, channel & 0b11111));
137        } else {
138            T::regs()
139                .rsqr1()
140                .modify(|w| w.set_sq((rank - 13) as usize, channel & 0b11111));
141        }
142    }
143
144    #[cfg(not(adc_v3))]
145    pub fn configure_channel(&mut self, channel: &mut impl AdcChannel<T>, rank: u8, sample_time: SampleTime) {
146        channel.set_as_analog();
147
148        let channel = channel.channel();
149
150        // sample time config
151        if channel < 10 {
152            T::regs().samptr2().modify(|w| w.set_smp(channel as usize, sample_time));
153        } else {
154            // V00x has no SAMPTR1: channels >= 10 (e.g. Vcal on ch 10) use a
155            // hardware-fixed sample time and `sample_time` is silently ignored.
156            #[cfg(not(adc_v00x))]
157            T::regs()
158                .samptr1()
159                .modify(|w| w.set_smp((channel - 10) as usize, sample_time));
160        }
161
162        // regular sequence config
163        debug_assert!(rank > 0 && rank <= 16);
164        if rank < 7 {
165            T::regs()
166                .rsqr3()
167                .modify(|w| w.set_sq((rank - 1) as usize, channel & 0b11111));
168        } else if rank < 13 {
169            T::regs()
170                .rsqr2()
171                .modify(|w| w.set_sq((rank - 7) as usize, channel & 0b11111));
172        } else {
173            T::regs()
174                .rsqr1()
175                .modify(|w| w.set_sq((rank - 13) as usize, channel & 0b11111));
176        }
177    }
178
179    // Get_ADC_Val
180    #[cfg(adc_v3)]
181    pub fn convert(&mut self, channel: &mut impl AdcChannel<T>, sample_time: SampleTime, pga: Pga) -> u16 {
182        self.configure_channel(channel, 1, sample_time, pga);
183
184        T::regs().ctlr2().modify(|w| w.set_swstart(true));
185
186        // while not end of conversion
187        while !T::regs().statr().read().eoc() {}
188
189        T::regs().rdatar().read().data()
190    }
191
192    #[cfg(not(adc_v3))]
193    pub fn convert(&mut self, channel: &mut impl AdcChannel<T>, sample_time: SampleTime) -> u16 {
194        self.configure_channel(channel, 1, sample_time);
195
196        T::regs().ctlr2().modify(|w| w.set_swstart(true));
197
198        // while not end of conversion
199        while !T::regs().statr().read().eoc() {}
200
201        T::regs().rdatar().read().data()
202    }
203}
204
205#[allow(unused)]
206pub(crate) trait SealedInstance {
207    fn regs() -> crate::pac::adc::Adc;
208    fn state() -> &'static State;
209}
210
211pub(crate) trait SealedAdcChannel<T: Instance> {
212    fn set_as_analog(&mut self) {}
213
214    #[allow(unused)]
215    fn channel(&self) -> u8;
216}
217
218#[allow(private_bounds)]
219pub trait Instance: SealedInstance + embassy_hal_internal::PeripheralType + crate::peripheral::RccPeripheral {
220    type Interrupt: crate::interrupt::typelevel::Interrupt;
221}
222
223/// ADC pin.
224#[allow(private_bounds)]
225pub trait AdcChannel<T: Instance>: SealedAdcChannel<T> + Sized {
226    fn degrade_adc(mut self) -> AnyAdcChannel<T> {
227        self.set_as_analog();
228
229        AnyAdcChannel {
230            channel: self.channel(),
231            _phantom: PhantomData,
232        }
233    }
234}
235
236/// A type-erased channel for a given ADC instance.
237///
238/// This is useful in scenarios where you need the ADC channels to have the same type, such as
239/// storing them in an array.
240pub struct AnyAdcChannel<T> {
241    channel: u8,
242    _phantom: PhantomData<T>,
243}
244
245impl<T: Instance> AdcChannel<T> for AnyAdcChannel<T> {}
246impl<T: Instance> SealedAdcChannel<T> for AnyAdcChannel<T> {
247    fn channel(&self) -> u8 {
248        self.channel
249    }
250}
251
252foreach_peripheral!(
253    (adc, $inst:ident) => {
254        impl crate::adc::SealedInstance for peripherals::$inst {
255            fn regs() -> crate::pac::adc::Adc {
256                crate::pac::$inst
257            }
258
259            fn state() -> &'static State {
260                static STATE: State = State::new();
261                &STATE
262            }
263        }
264
265        impl crate::adc::Instance for peripherals::$inst {
266            type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
267        }
268    };
269);
270
271macro_rules! impl_adc_pin {
272    ($inst:ident, $pin:ident, $ch:expr) => {
273        impl crate::adc::AdcChannel<peripherals::$inst> for crate::peripherals::$pin {}
274
275        impl crate::adc::SealedAdcChannel<peripherals::$inst> for crate::peripherals::$pin {
276            fn set_as_analog(&mut self) {
277                <Self as crate::gpio::SealedPin>::set_as_analog(self);
278            }
279
280            fn channel(&self) -> u8 {
281                $ch
282            }
283        }
284
285        impl crate::adc::AdcChannel<peripherals::$inst> for crate::Peri<'_, crate::peripherals::$pin> {}
286
287        impl crate::adc::SealedAdcChannel<peripherals::$inst> for crate::Peri<'_, crate::peripherals::$pin> {
288            fn set_as_analog(&mut self) {
289                <crate::peripherals::$pin as crate::gpio::SealedPin>::set_as_analog(self);
290            }
291
292            fn channel(&self) -> u8 {
293                $ch
294            }
295        }
296    };
297}
298
299#[cfg(adc_l1)]
300mod ch_internal {
301    use super::*;
302
303    pub struct VddaDiv2;
304    impl<T: Instance> AdcChannel<T> for VddaDiv2 {}
305    impl<T: Instance> SealedAdcChannel<T> for VddaDiv2 {
306        fn channel(&self) -> u8 {
307            18
308        }
309    }
310
311    pub struct VrefInt;
312    impl<T: Instance> AdcChannel<T> for VrefInt {}
313    impl<T: Instance> SealedAdcChannel<T> for VrefInt {
314        fn set_as_analog(&mut self) {
315            T::regs().ctlr2().modify(|w| w.set_tsvrefe(true));
316        }
317        fn channel(&self) -> u8 {
318            17
319        }
320    }
321
322    pub struct Temperature;
323    impl<T: Instance> AdcChannel<T> for Temperature {}
324    impl<T: Instance> SealedAdcChannel<T> for Temperature {
325        fn set_as_analog(&mut self) {
326            T::regs().ctlr2().modify(|w| w.set_tsvrefe(true));
327        }
328        fn channel(&self) -> u8 {
329            16
330        }
331    }
332}
333#[cfg(adc_x0)]
334mod ch_internal {
335    use super::*;
336
337    pub struct VrefInt;
338    impl<T: Instance> AdcChannel<T> for VrefInt {}
339    impl<T: Instance> SealedAdcChannel<T> for VrefInt {
340        fn channel(&self) -> u8 {
341            15
342        }
343    }
344}
345#[cfg(any(adc_v1, adc_v3))]
346mod ch_internal {
347    use super::*;
348
349    pub struct VrefInt;
350    impl<T: Instance> AdcChannel<T> for VrefInt {}
351    impl<T: Instance> SealedAdcChannel<T> for VrefInt {
352        fn set_as_analog(&mut self) {
353            T::regs().ctlr2().modify(|w| w.set_tsvrefe(true));
354        }
355        fn channel(&self) -> u8 {
356            17
357        }
358    }
359
360    pub struct Temperature;
361    impl<T: Instance> AdcChannel<T> for Temperature {}
362    impl<T: Instance> SealedAdcChannel<T> for Temperature {
363        fn set_as_analog(&mut self) {
364            T::regs().ctlr2().modify(|w| w.set_tsvrefe(true));
365        }
366        fn channel(&self) -> u8 {
367            16
368        }
369    }
370}
371
372#[cfg(any(adc_v003, adc_v00x))]
373mod ch_internal {
374    use super::*;
375
376    pub struct Vref;
377    impl<T: Instance> AdcChannel<T> for Vref {}
378    impl<T: Instance> SealedAdcChannel<T> for Vref {
379        fn channel(&self) -> u8 {
380            8
381        }
382    }
383
384    /// Internal calibration voltage channel.
385    ///
386    /// Note: on V00x, Vcal is on ADC channel 10. V00x has no `SAMPTR1`
387    /// register, so the `sample_time` argument to `configure_channel`/
388    /// `convert` is silently ignored for this channel — Vcal uses a
389    /// hardware-fixed sample time.
390    pub struct Vcal;
391    impl<T: Instance> AdcChannel<T> for Vcal {}
392    impl<T: Instance> SealedAdcChannel<T> for Vcal {
393        fn channel(&self) -> u8 {
394            #[cfg(adc_v003)]
395            {
396                9
397            }
398            #[cfg(adc_v00x)]
399            {
400                10
401            }
402        }
403    }
404}
405
406#[cfg(adc_ch641)]
407mod ch_internal {
408    use super::*;
409    use crate::pac::EXTEND;
410
411    // FIXME: move peripherals and pins
412
413    /// Differential input current sampling
414    pub struct Isp {
415        _marker: core::marker::PhantomData<()>,
416    }
417
418    #[derive(Default)]
419    pub struct IspConfig {
420        /// DC bias is about 400 in raw ADC sample value.
421        pub dc_bias: bool,
422    }
423
424    impl Isp {
425        pub fn new_non_inverting(in_positive: impl NonInvertingPin, config: IspConfig) -> Self {
426            in_positive.set_as_isp_pin();
427            EXTEND.ctlr2().modify(|w| {
428                w.set_isp_ps(in_positive.pin_sel());
429                w.set_isp_ns(true); // use GND
430                w.set_isp_ae(true);
431                w.set_isp_be(config.dc_bias);
432            });
433            Isp {
434                _marker: core::marker::PhantomData,
435            }
436        }
437
438        // PB6/PA6, PB7
439        pub fn new(in_positive: impl NonInvertingPin, in_negative: impl InvertingPin, config: IspConfig) -> Self {
440            in_positive.set_as_isp_pin();
441            in_negative.set_as_isp_pin();
442            EXTEND.ctlr2().modify(|w| {
443                w.set_isp_ps(in_positive.pin_sel());
444                w.set_isp_ns(false); // true: use GND; false: use PB7
445                w.set_isp_ae(true);
446                w.set_isp_be(config.dc_bias);
447            });
448            Isp {
449                _marker: core::marker::PhantomData,
450            }
451        }
452    }
453
454    pub trait NonInvertingPin {
455        fn set_as_isp_pin(&self) {}
456        fn pin_sel(&self) -> bool;
457    }
458    pub trait InvertingPin {
459        fn set_as_isp_pin(&self) {}
460    }
461    impl NonInvertingPin for peripherals::PA6 {
462        fn pin_sel(&self) -> bool {
463            true
464        }
465    }
466    // aka. ISP pin
467    impl NonInvertingPin for peripherals::PB6 {
468        fn pin_sel(&self) -> bool {
469            false
470        }
471    }
472    impl InvertingPin for peripherals::PB7 {}
473
474    impl<T: Instance> AdcChannel<T> for Isp {}
475    impl<T: Instance> SealedAdcChannel<T> for Isp {
476        fn channel(&self) -> u8 {
477            8
478        }
479    }
480
481    pub struct VhvDiv5;
482    impl<T: Instance> AdcChannel<T> for VhvDiv5 {}
483    impl<T: Instance> SealedAdcChannel<T> for VhvDiv5 {
484        fn channel(&self) -> u8 {
485            15
486        }
487    }
488}
489
490pub use ch_internal::*;