consortium-hal-imx9 0.5.0

Consortium HAL for i.MX 9 family devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! Polling ADC driver for the i.MX 9 SAR ADC.
//!
//! Select an instance by handing its peripheral singleton to [`Adc::new`]:
//!
//! ```ignore
//! let p = consortium_hal_imx9::init();
//! let adc = Adc::new(p.ADC, Config::default());
//! ```
//!
//! Clock-root and pin-mux configuration are intentionally left to the caller.

use embassy_hal_internal::{Peri, PeripheralType};
use pac::peripherals::adc::{ADC, ADC_NCMR0, ADC_NCMR1};

use crate::pac;

#[cfg(feature = "dma")]
use crate::dma::{DmaChannel, ReadableRingBuffer, RingError, Transfer, request};
#[cfg(feature = "dma")]
use core::future::Future;
#[cfg(feature = "dma")]
use core::pin::Pin;
#[cfg(feature = "dma")]
use core::task::{Context, Poll};

/// ADC configuration shared by i.MX93 and i.MX95.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Config {
    /// Use the bus clock directly instead of bus clock divided by two.
    pub full_speed_clock: bool,
    /// Sampling-time selector (`0..=3`).
    pub sample_time: u8,
    /// Number-of-samples selector (`0..=3`).
    pub sample_count: u8,
    /// Enable hardware averaging.
    pub averaging: bool,
}

/// ADC operation error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// Only precision channels 0-7 and internal channels 32-39 are available.
    InvalidChannel,
    /// A conversion is already active.
    Busy,
    /// Hardware calibration failed.
    CalibrationFailed,
}

/// Normal-conversion trigger used by DMA sampling.
#[cfg(feature = "dma")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DmaTrigger {
    /// Start immediately and scan continuously.
    SoftwareContinuous,
    /// Perform a conversion on each rising external trigger.
    ExternalRising,
    /// Perform a conversion on each falling external trigger.
    ExternalFalling,
}

/// Crate-internal half of [`Instance`]: visible to the generated bindings that
/// implement it, sealed against downstream crates.
pub(crate) trait SealedInstance {
    /// This instance's register block, at its database-resolved base.
    fn regs() -> ADC;
    /// The CCM gate the constructor opens before the first register access
    /// (see [`crate::clock`]); `None` where this core need not open one.
    const LPCG: Option<u32>;
}

/// An ADC instance the [`Adc`] driver can drive.
///
/// Implemented by the generated peripheral singletons; sealed so the base
/// address stays single-sourced from the chip database.
#[allow(private_bounds)]
pub trait Instance: SealedInstance + PeripheralType {
    /// End-of-conversion NVIC line, when the chip routes one to this core.
    const IRQ: Option<u16>;
}

/// Bind a generated peripheral singleton to this driver. Invoked only by the
/// generated `peripherals` module.
macro_rules! impl_adc {
    ($instance:ident, $base:expr, $irq:expr) => {
        impl crate::adc::SealedInstance for crate::peripherals::$instance {
            const LPCG: ::core::option::Option<u32> = crate::clock::lpcg(stringify!($instance));

            #[inline]
            fn regs() -> crate::pac::peripherals::adc::ADC {
                // SAFETY: `$base` is this instance's ADC base as extracted from
                // the chip database, and the singleton this impl is keyed to
                // can be held by only one driver at a time.
                unsafe { crate::pac::peripherals::adc::ADC::from_ptr($base as *mut ()) }
            }
        }

        impl crate::adc::Instance for crate::peripherals::$instance {
            const IRQ: ::core::option::Option<u16> = $irq;
        }
    };
}
pub(crate) use impl_adc;

/// Polling ADC driver.
pub struct Adc {
    adc: ADC,
    active_channel: Option<u8>,
}

impl Adc {
    /// Build a driver over an arbitrary register block, for tests that stand a
    /// plain array in for the ADC.
    #[cfg(test)]
    fn over(adc: ADC) -> Self {
        Self {
            adc,
            active_channel: None,
        }
    }

    /// Bind and power up an ADC instance from its peripheral singleton.
    ///
    /// The platform must leave the instance's clock root enabled.
    pub fn new<T: Instance>(peri: Peri<'static, T>, config: Config) -> Self {
        assert!(config.sample_time <= 3);
        assert!(config.sample_count <= 3);
        // Owning the singleton for the driver's lifetime is what makes exclusive
        // register access safe; it is consumed here and never reissued.
        let _ = peri;
        // On i.MX 93 Linux closes the gate of every peripheral no kernel
        // driver claims; the first register access would BusFault without this.
        crate::clock::ungate(T::LPCG);
        let adc = T::regs();
        adc.MCR().modify(|w| {
            w.set_PWDN(false);
            w.set_ADCLKSE(config.full_speed_clock);
            w.set_TSAMP(config.sample_time);
            w.set_NRSMPL(config.sample_count);
            w.set_AVGEN(config.averaging);
            w.set_MODE(false);
        });
        Self {
            adc,
            active_channel: None,
        }
    }

    /// Run the ADC's hardware calibration and wait for completion.
    pub fn calibrate(&mut self) -> Result<(), Error> {
        self.adc.MCR().modify(|w| w.set_CALSTART(true));
        while self.adc.MSR().read().CALBUSY() {}
        if self.adc.MSR().read().CALFAIL() {
            Err(Error::CalibrationFailed)
        } else {
            Ok(())
        }
    }

    /// Start a single software-triggered conversion.
    pub fn start_conversion(&mut self, channel: u8) -> Result<(), Error> {
        if self.active_channel.is_some() || self.adc.MSR().read().NSTART() {
            return Err(Error::Busy);
        }
        match channel {
            0..=7 => {
                self.adc.NCMR0().write_value(ADC_NCMR0(1u32 << channel));
                self.adc.NCMR1().write_value(ADC_NCMR1(0));
                self.adc.CEOCFR0().write_value(1u32 << channel);
            }
            32..=39 => {
                self.adc.NCMR0().write_value(ADC_NCMR0(0));
                self.adc
                    .NCMR1()
                    .write_value(ADC_NCMR1(1u32 << (channel - 32)));
                self.adc.CEOCFR1().write_value(1u32 << (channel - 32));
            }
            _ => return Err(Error::InvalidChannel),
        }
        self.active_channel = Some(channel);
        self.adc.MCR().modify(|w| w.set_NSTART(true));
        Ok(())
    }

    /// Return the completed sample, or `None` while conversion is in progress.
    pub fn try_read(&mut self) -> Option<u16> {
        let channel = self.active_channel?;
        let value = if channel < 8 {
            let data = self.adc.PCDR(channel as usize).read();
            data.VALID().then(|| data.CDATA())
        } else {
            let data = self.adc.ICDR((channel - 32) as usize).read();
            data.VALID().then(|| data.CDATA())
        };
        let value = value?;
        self.active_channel = None;
        Some(value)
    }

    /// Start a conversion and busy-wait for its result.
    pub fn read_blocking(&mut self, channel: u8) -> Result<u16, Error> {
        self.start_conversion(channel)?;
        loop {
            if let Some(value) = self.try_read() {
                return Ok(value);
            }
        }
    }

    /// Start a finite DMA sample stream for one ADC channel.
    ///
    /// The SAR ADC stores each channel in a separate `PCDR`/`ICDR`; therefore
    /// this operation repeatedly samples one channel. A heterogeneous scan
    /// requires an eDMA scatter/gather sequence with one source register per
    /// channel.
    #[cfg(feature = "dma")]
    pub fn read_dma<'a>(
        &'a mut self,
        dma: &'a mut DmaChannel,
        channel: u8,
        samples: &'a mut [u16],
        trigger: DmaTrigger,
    ) -> Result<AdcDmaTransfer<'a>, Error> {
        self.prepare_dma_channel(channel, trigger)?;
        let register = self.channel_data_ptr(channel)?;
        // SAFETY: the selected PCDR/ICDR is the ADC1 request's data register.
        let transfer =
            unsafe { dma.read_peripheral_with_request(register, samples, request::ADC1) };
        self.enable_dma_channel(channel);
        self.start_dma_conversion(trigger);
        Ok(AdcDmaTransfer {
            adc: self,
            channel,
            transfer: Some(transfer),
        })
    }

    /// Construct a circular DMA sampler for one ADC channel.
    #[cfg(feature = "dma")]
    pub fn into_ring_buffered<'a>(
        &'a mut self,
        dma: &'a mut DmaChannel,
        channel: u8,
        samples: &'a mut [u16],
        trigger: DmaTrigger,
    ) -> Result<RingBufferedAdc<'a>, Error> {
        self.prepare_dma_channel(channel, trigger)?;
        let register = self.channel_data_ptr(channel)?;
        // SAFETY: the selected PCDR/ICDR is the ADC1 request's data register.
        let ring = unsafe { dma.read_circular(register, samples, request::ADC1) };
        Ok(RingBufferedAdc {
            adc: self,
            channel,
            trigger,
            ring: Some(ring),
            started: false,
        })
    }

    #[cfg(feature = "dma")]
    fn prepare_dma_channel(&mut self, channel: u8, trigger: DmaTrigger) -> Result<(), Error> {
        if self.active_channel.is_some() || self.adc.MSR().read().NSTART() {
            return Err(Error::Busy);
        }
        let (normal0, normal1) = channel_masks(channel)?;
        self.adc.NCMR0().write_value(ADC_NCMR0(normal0));
        self.adc.NCMR1().write_value(ADC_NCMR1(normal1));
        self.adc.CEOCFR0().write_value(normal0);
        self.adc.CEOCFR1().write_value(normal1);
        self.adc.DMAR0().write(|w| w.0 = 0);
        self.adc.DMAR1().write(|w| w.0 = 0);
        self.adc.DMAE().modify(|w| {
            w.set_DMAEN(false);
            // Clear the request by reading its data register. This matches a
            // circular stream where the eDMA request remains enabled.
            w.set_DCLR(true);
        });
        self.adc.MCR().modify(|w| {
            w.set_OWREN(true);
            w.set_TRGEN(!matches!(trigger, DmaTrigger::SoftwareContinuous));
            w.set_EDGE(matches!(trigger, DmaTrigger::ExternalRising));
            w.set_MODE(matches!(trigger, DmaTrigger::SoftwareContinuous));
        });
        Ok(())
    }

    #[cfg(feature = "dma")]
    fn channel_data_ptr(&self, channel: u8) -> Result<*const u16, Error> {
        match channel {
            0..=7 => Ok(self.adc.PCDR(channel as usize).as_ptr().cast::<u16>()),
            32..=39 => Ok(self
                .adc
                .ICDR((channel - 32) as usize)
                .as_ptr()
                .cast::<u16>()),
            _ => Err(Error::InvalidChannel),
        }
    }

    #[cfg(feature = "dma")]
    fn enable_dma_channel(&mut self, channel: u8) {
        if channel < 8 {
            self.adc.DMAR0().modify(|w| w.0 |= 1u32 << channel);
        } else {
            self.adc.DMAR1().modify(|w| w.0 |= 1u32 << (channel - 32));
        }
        self.adc.DMAE().modify(|w| w.set_DMAEN(true));
    }

    #[cfg(feature = "dma")]
    fn start_dma_conversion(&mut self, trigger: DmaTrigger) {
        if matches!(trigger, DmaTrigger::SoftwareContinuous) {
            self.adc.MCR().modify(|w| w.set_NSTART(true));
        }
    }

    #[cfg(feature = "dma")]
    fn stop_dma(&mut self) {
        self.adc.DMAE().modify(|w| w.set_DMAEN(false));
        self.adc.DMAR0().write(|w| w.0 = 0);
        self.adc.DMAR1().write(|w| w.0 = 0);
        self.adc.MCR().modify(|w| {
            w.set_NSTART(false);
            w.set_TRGEN(false);
            w.set_MODE(false);
        });
        self.active_channel = None;
    }
}

#[cfg(feature = "dma")]
fn channel_masks(channel: u8) -> Result<(u32, u32), Error> {
    match channel {
        0..=7 => Ok((1u32 << channel, 0)),
        32..=39 => Ok((0, 1u32 << (channel - 32))),
        _ => Err(Error::InvalidChannel),
    }
}

/// Finite ADC DMA sampling operation.
#[cfg(feature = "dma")]
pub struct AdcDmaTransfer<'a> {
    adc: &'a mut Adc,
    channel: u8,
    transfer: Option<Transfer<'a>>,
}

#[cfg(feature = "dma")]
impl AdcDmaTransfer<'_> {
    /// Busy-wait for every sample.
    pub fn wait_blocking(mut self) -> Result<(), crate::dma::Error> {
        let result = self
            .transfer
            .take()
            .expect("transfer already consumed")
            .wait_blocking();
        self.adc.stop_dma();
        result
    }

    /// Channel being sampled.
    pub const fn channel(&self) -> u8 {
        self.channel
    }
}

#[cfg(feature = "dma")]
impl Future for AdcDmaTransfer<'_> {
    type Output = Result<(), crate::dma::Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        let result = Pin::new(
            this.transfer
                .as_mut()
                .expect("transfer polled after completion"),
        )
        .poll(cx);
        if result.is_ready() {
            drop(this.transfer.take());
            this.adc.stop_dma();
        }
        result
    }
}

#[cfg(feature = "dma")]
impl Drop for AdcDmaTransfer<'_> {
    fn drop(&mut self) {
        drop(self.transfer.take());
        self.adc.stop_dma();
    }
}

/// Circular one-channel ADC sample consumer.
#[cfg(feature = "dma")]
pub struct RingBufferedAdc<'a> {
    adc: &'a mut Adc,
    channel: u8,
    trigger: DmaTrigger,
    ring: Option<ReadableRingBuffer<'a, u16>>,
    started: bool,
}

#[cfg(feature = "dma")]
impl<'a> RingBufferedAdc<'a> {
    /// Enable the ADC request and begin sampling.
    pub fn start(&mut self) {
        if !self.started {
            self.adc.enable_dma_channel(self.channel);
            self.ring_mut().start();
            self.adc.start_dma_conversion(self.trigger);
            self.started = true;
        }
    }

    /// Read immediately available samples.
    pub fn read(&mut self, output: &mut [u16]) -> Result<(usize, usize), RingError> {
        self.ring_mut().read(output)
    }

    /// Fill `output` asynchronously.
    pub async fn read_exact(&mut self, output: &mut [u16]) -> Result<usize, RingError> {
        self.ring_mut().read_exact(output).await
    }

    /// Return the newest samples.
    pub fn read_latest(&mut self, output: &mut [u16]) -> Result<usize, RingError> {
        self.ring_mut().read_latest(output)
    }

    /// Number of unread samples.
    pub fn len(&self) -> Result<usize, RingError> {
        self.ring.as_ref().expect("ring has been released").len()
    }

    /// Whether no samples are available.
    pub fn is_empty(&self) -> Result<bool, RingError> {
        self.ring
            .as_ref()
            .expect("ring has been released")
            .is_empty()
    }

    /// Pause eDMA requests.
    pub fn pause(&mut self) {
        self.ring_mut().pause();
    }

    /// Resume eDMA requests.
    pub fn resume(&mut self) {
        self.ring_mut().resume();
    }

    /// Stop eDMA before disabling the ADC request.
    pub async fn stop(&mut self) {
        self.ring_mut().stop().await;
        self.adc.stop_dma();
        self.started = false;
    }

    fn ring_mut(&mut self) -> &mut ReadableRingBuffer<'a, u16> {
        self.ring.as_mut().expect("ring has been released")
    }
}

#[cfg(feature = "dma")]
impl Drop for RingBufferedAdc<'_> {
    fn drop(&mut self) {
        drop(self.ring.take());
        self.adc.stop_dma();
    }
}

#[cfg(all(test, feature = "dma"))]
mod tests {
    use super::*;
    use crate::dma::DmaState;

    #[cfg(feature = "mimx93")]
    const ADC_DMA_CHANNEL: usize = 30;
    #[cfg(feature = "mimx95")]
    const ADC_DMA_CHANNEL: usize = 7;

    #[test]
    fn finite_dma_configures_and_cleans_adc_requests() {
        static STATE: DmaState = DmaState::new();
        let mut adc_registers = [0u32; 0x100];
        let words = ((ADC_DMA_CHANNEL + 2) * 0x1_0000) / 4;
        let mut dma_registers = std::vec![0u32; words];

        // SAFETY: both fake register blocks are exclusively owned by the test.
        // SAFETY: the fake ADC registers are word-aligned, cover every offset
        // the driver touches, and outlive the driver built over them.
        let mut adc = Adc::over(unsafe { ADC::from_ptr(adc_registers.as_mut_ptr().cast()) });
        // The allocation covers the management page plus every channel page.
        let mut dma = DmaChannel::claim(
            crate::dma::DmaController::Dma3,
            dma_registers.as_mut_ptr().cast(),
            ADC_DMA_CHANNEL,
            &STATE,
        );
        let mut samples = [0u16; 4];

        {
            let transfer = adc
                .read_dma(&mut dma, 3, &mut samples, DmaTrigger::SoftwareContinuous)
                .unwrap();
            assert_eq!(adc_registers[0x44 / 4], 1 << 3);
            assert_eq!(adc_registers[0x40 / 4] & 0x3, 0x3);
            assert_ne!(adc_registers[0] & (1 << 24), 0);
            drop(transfer);
        }

        assert_eq!(adc_registers[0x44 / 4], 0);
        assert_eq!(adc_registers[0x40 / 4] & 0x1, 0);
        assert_eq!(adc_registers[0] & (1 << 24), 0);
    }
}