Skip to main content

nrf52/
adc.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! ADC driver for the nRF52. Uses the SAADC peripheral.
6
7use core::cell::Cell;
8use core::cmp;
9use core::ptr::addr_of;
10use kernel::ErrorCode;
11use kernel::hil;
12use kernel::utilities::StaticRef;
13use kernel::utilities::cells::{OptionalCell, TakeCell};
14use tock_registers_v0::interfaces::{Readable, Writeable};
15use tock_registers_v0::registers::{ReadOnly, ReadWrite, WriteOnly};
16use tock_registers_v0::{register_bitfields, register_structs};
17
18register_structs! {
19    pub AdcRegisters {
20        /// Start the ADC and prepare the result buffer in RAM
21        (0x000 => tasks_start: WriteOnly<u32, TASK::Register>),
22        /// Take one ADC sample, if scan is enabled all channels are sampled
23        (0x004 => tasks_sample: WriteOnly<u32, TASK::Register>),
24        /// Stop the ADC and terminate any on-going conversion
25        (0x008 => tasks_stop: WriteOnly<u32, TASK::Register>),
26        /// Starts offset auto-calibration
27        (0x00C => tasks_calibrateoffset: WriteOnly<u32, TASK::Register>),
28        (0x010 => _reserved0),
29        /// The ADC has started
30        (0x100 => events_started: ReadWrite<u32, EVENT::Register>),
31        /// The ADC has filled up the Result buffer
32        (0x104 => events_end: ReadWrite<u32, EVENT::Register>),
33        /// A conversion task has been completed. Depending on the mode, multiple conversion
34        (0x108 => events_done: ReadWrite<u32, EVENT::Register>),
35        /// A result is ready to get transferred to RAM
36        (0x10C => events_resultdone: ReadWrite<u32, EVENT::Register>),
37        /// Calibration is complete
38        (0x110 => events_calibratedone: ReadWrite<u32, EVENT::Register>),
39        /// The ADC has stopped
40        (0x114 => events_stopped: ReadWrite<u32, EVENT::Register>),
41        /// Last result is equal or above `CH[X].LIMIT`
42        (0x118 => events_ch: [AdcEventChRegisters; 8]),
43        (0x158 => _reserved1),
44        /// Enable or disable interrupt
45        (0x300 => inten: ReadWrite<u32, INTEN::Register>),
46        /// Enable interrupt
47        (0x304 => intenset: ReadWrite<u32, INTEN::Register>),
48        /// Disable interrupt
49        (0x308 => intenclr: ReadWrite<u32, INTEN::Register>),
50        (0x30C => _reserved2),
51        /// Status
52        (0x400 => status: ReadOnly<u32>),
53        (0x404 => _reserved3),
54        /// Enable or disable ADC
55        (0x500 => enable: ReadWrite<u32, ENABLE::Register>),
56        (0x504 => _reserved4),
57        (0x510 => ch: [AdcChRegisters; 8]),
58        (0x590 => _reserved5),
59        /// Resolution configuration
60        (0x5F0 => resolution: ReadWrite<u32, RESOLUTION::Register>),
61        /// Oversampling configuration. OVERSAMPLE should not be combined with SCAN. The RES
62        (0x5F4 => oversample: ReadWrite<u32>),
63        /// Controls normal or continuous sample rate
64        (0x5F8 => samplerate: ReadWrite<u32, SAMPLERATE::Register>),
65        (0x5FC => _reserved6),
66        /// Pointer to store samples to
67        (0x62C => result_ptr: ReadWrite<u32>),
68        /// Number of 16 bit samples to save in RAM
69        (0x630 => result_maxcnt: ReadWrite<u32, RESULT_MAXCNT::Register>),
70        /// Number of 16 bit samples recorded to RAM
71        (0x634 => result_amount: ReadWrite<u32, RESULT_AMOUNT::Register>),
72        (0x638 => @END),
73    }
74}
75
76register_structs! {
77    AdcEventChRegisters {
78        (0x0 => limith: ReadWrite<u32, EVENT::Register>),
79        (0x4 => limitl: ReadWrite<u32, EVENT::Register>),
80        (0x8 => @END),
81    }
82}
83
84register_structs! {
85    AdcChRegisters {
86        (0x0 => pselp: ReadWrite<u32, PSEL::Register>),
87        (0x4 => pseln: ReadWrite<u32, PSEL::Register>),
88        (0x8 => config: ReadWrite<u32, CONFIG::Register>),
89        (0xC => limit: ReadWrite<u32, LIMIT::Register>),
90        (0x10 => @END),
91    }
92}
93
94register_bitfields![u32,
95    INTEN [
96        /// Enable or disable interrupt on EVENTS_STARTED event
97        STARTED 0,
98        /// Enable or disable interrupt on EVENTS_END event
99        END 1,
100        /// Enable or disable interrupt on EVENTS_DONE event
101        DONE 2,
102        /// Enable or disable interrupt on EVENTS_RESULTDONE event
103        RESULTDONE 3,
104        /// Enable or disable interrupt on EVENTS_CALIBRATEDONE event
105        CALIBRATEDONE 4,
106        /// Enable or disable interrupt on EVENTS_STOPPED event
107        STOPPED 5,
108        /// Enable or disable interrupt on EVENTS_CH[0].LIMITH event
109        CH0LIMITH 6,
110        /// Enable or disable interrupt on EVENTS_CH[0].LIMITL event
111        CH0LIMITL 7,
112        /// Enable or disable interrupt on EVENTS_CH[1].LIMITH event
113        CH1LIMITH 8,
114        /// Enable or disable interrupt on EVENTS_CH[1].LIMITL event
115        CH1LIMITL 9,
116        /// Enable or disable interrupt on EVENTS_CH[2].LIMITH event
117        CH2LIMITH 10,
118        /// Enable or disable interrupt on EVENTS_CH[2].LIMITL event
119        CH2LIMITL 11,
120        /// Enable or disable interrupt on EVENTS_CH[3].LIMITH event
121        CH3LIMITH 12,
122        /// Enable or disable interrupt on EVENTS_CH[3].LIMITL event
123        CH3LIMITL 13,
124        /// Enable or disable interrupt on EVENTS_CH[4].LIMITH event
125        CH4LIMITH 14,
126        /// Enable or disable interrupt on EVENTS_CH[4].LIMITL event
127        CH4LIMITL 15,
128        /// Enable or disable interrupt on EVENTS_CH[5].LIMITH event
129        CH5LIMITH 16,
130        /// Enable or disable interrupt on EVENTS_CH[5].LIMITL event
131        CH5LIMITL 17,
132        /// Enable or disable interrupt on EVENTS_CH[6].LIMITH event
133        CH6LIMITH 18,
134        /// Enable or disable interrupt on EVENTS_CH[6].LIMITL event
135        CH6LIMITL 19,
136        /// Enable or disable interrupt on EVENTS_CH[7].LIMITH event
137        CH7LIMITH 20,
138        /// Enable or disable interrupt on EVENTS_CH[7].LIMITL event
139        CH7LIMITL 21
140    ],
141    ENABLE [
142        ENABLE 0
143    ],
144    SAMPLERATE [
145        /// Capture and compare value. Sample rate is 16 MHz/CC
146        CC OFFSET(0) NUMBITS(11) [],
147        /// Select mode for sample rate control
148        MODE OFFSET(12) NUMBITS(1) [
149            /// Rate is controlled from SAMPLE task
150            Task = 0,
151            /// Rate is controlled from local timer (use CC to control the rate)
152            Timers = 1
153        ]
154    ],
155    EVENT [
156        EVENT 0
157    ],
158    TASK [
159        TASK 0
160    ],
161    PSEL [
162        PSEL OFFSET(0) NUMBITS(5) [
163            NotConnected = 0,
164            AnalogInput0 = 1,
165            AnalogInput1 = 2,
166            AnalogInput2 = 3,
167            AnalogInput3 = 4,
168            AnalogInput4 = 5,
169            AnalogInput5 = 6,
170            AnalogInput6 = 7,
171            AnalogInput7 = 8,
172            VDD = 9,
173            VDDHDIV5 = 0xD
174        ]
175    ],
176    CONFIG [
177        RESP OFFSET(0) NUMBITS(2) [
178            Bypass = 0,
179            Pulldown = 1,
180            Pullup = 2,
181            VDD1_2 = 3
182        ],
183        RESN OFFSET(4) NUMBITS(2) [
184            Bypass = 0,
185            Pulldown = 1,
186            Pullup = 2,
187            VDD1_2 = 3
188        ],
189        GAIN OFFSET(8) NUMBITS(3) [
190            Gain1_6 = 0,
191            Gain1_5 = 1,
192            Gain1_4 = 2,
193            Gain1_3 = 3,
194            Gain1_2 = 4,
195            Gain1 = 5,
196            Gain2 = 6,
197            Gain4 = 7
198        ],
199        REFSEL OFFSET(12) NUMBITS(1) [
200            Internal = 0,
201            VDD1_4 = 1
202        ],
203        TACQ OFFSET(16) NUMBITS(3) [
204            us3 = 0,
205            us5 = 1,
206            us10 = 2,
207            us15 = 3,
208            us20 = 4,
209            us40 = 5
210        ],
211        MODE OFFSET(20) NUMBITS(1) [
212            SE = 0,
213            Diff = 1
214        ],
215        BURST OFFSET(24) NUMBITS(1) [
216            Disable = 0,
217            Enable = 1
218        ]
219    ],
220    LIMIT [
221        LOW OFFSET(0) NUMBITS(16) [],
222        HIGH OFFSET(16) NUMBITS(16) []
223    ],
224    RESOLUTION [
225        VAL OFFSET(0) NUMBITS(3) [
226            bit8 = 0,
227            bit10 = 1,
228            bit12 = 2,
229            bit14 = 3
230        ]
231    ],
232    RESULT_MAXCNT [
233        MAXCNT OFFSET(0) NUMBITS(16) []
234    ],
235    RESULT_AMOUNT [
236        AMOUNT OFFSET(0) NUMBITS(16) []
237    ]
238];
239
240#[derive(Copy, Clone, Debug, PartialEq)]
241pub enum AdcChannel {
242    AnalogInput0 = 1,
243    AnalogInput1 = 2,
244    AnalogInput2 = 3,
245    AnalogInput3 = 4,
246    AnalogInput4 = 5,
247    AnalogInput5 = 6,
248    AnalogInput6 = 7,
249    AnalogInput7 = 8,
250    VDD = 9,
251    VDDHDIV5 = 0xD,
252}
253
254// Buffer to save completed sample to.
255static mut SAMPLE: [u16; 1] = [0; 1];
256
257#[repr(u8)]
258#[derive(Copy, Clone, Debug)]
259pub enum AdcChannelGain {
260    Gain1_6 = 0,
261    Gain1_5 = 1,
262    Gain1_4 = 2,
263    Gain1_3 = 3,
264    Gain1_2 = 4,
265    Gain1 = 5,
266    Gain2 = 6,
267    Gain4 = 7,
268}
269
270#[repr(u8)]
271#[derive(Copy, Clone, Debug)]
272pub enum AdcChannelResistor {
273    Bypass = 0,
274    Pulldown = 1,
275    Pullup = 2,
276    VDD1_2 = 3,
277}
278
279#[allow(non_camel_case_types)]
280#[repr(u8)]
281#[derive(Clone, Copy, Debug)]
282pub enum AdcChannelSamplingTime {
283    us3 = 0,
284    us5 = 1,
285    us10 = 2,
286    us15 = 3,
287    us20 = 4,
288    us40 = 5,
289}
290
291#[derive(Copy, Clone, Debug)]
292pub struct AdcChannelSetup {
293    channel: AdcChannel,
294    gain: AdcChannelGain,
295    resp: AdcChannelResistor,
296    resn: AdcChannelResistor,
297    sampling_time: AdcChannelSamplingTime,
298}
299
300impl PartialEq for AdcChannelSetup {
301    fn eq(&self, other: &Self) -> bool {
302        self.channel == other.channel
303    }
304}
305
306impl AdcChannelSetup {
307    pub fn new(channel: AdcChannel) -> AdcChannelSetup {
308        AdcChannelSetup {
309            channel,
310            gain: AdcChannelGain::Gain1_4,
311            resp: AdcChannelResistor::Bypass,
312            resn: AdcChannelResistor::Pulldown,
313            sampling_time: AdcChannelSamplingTime::us10,
314        }
315    }
316
317    pub fn setup(
318        channel: AdcChannel,
319        gain: AdcChannelGain,
320        resp: AdcChannelResistor,
321        resn: AdcChannelResistor,
322        sampling_time: AdcChannelSamplingTime,
323    ) -> AdcChannelSetup {
324        AdcChannelSetup {
325            channel,
326            gain,
327            resp,
328            resn,
329            sampling_time,
330        }
331    }
332}
333
334#[derive(Clone, Copy)]
335enum AdcMode {
336    Idle,
337    Calibrate,
338    Single,
339    HighSpeed,
340}
341
342pub struct Adc<'a> {
343    registers: StaticRef<AdcRegisters>,
344    reference: Cell<usize>,
345    mode: Cell<AdcMode>,
346    client: OptionalCell<&'a dyn hil::adc::Client>,
347    highspeed_client: OptionalCell<&'a dyn hil::adc::HighSpeedClient>,
348
349    buffer: TakeCell<'static, [u16]>,
350    length: Cell<usize>,
351    next_buffer: TakeCell<'static, [u16]>,
352    next_length: Cell<usize>,
353}
354
355impl Adc<'_> {
356    pub const fn new(registers: StaticRef<AdcRegisters>, voltage_reference_in_mv: usize) -> Self {
357        Self {
358            registers,
359            reference: Cell::new(voltage_reference_in_mv),
360            mode: Cell::new(AdcMode::Idle),
361            client: OptionalCell::empty(),
362            highspeed_client: OptionalCell::empty(),
363            buffer: TakeCell::empty(),
364            length: Cell::new(0),
365            next_buffer: TakeCell::empty(),
366            next_length: Cell::new(0),
367        }
368    }
369
370    // Calibrate and measure the actual VDD of the board.
371    pub fn calibrate(&self) {
372        self.mode.set(AdcMode::Calibrate);
373
374        // Enable the ADC
375        self.registers.enable.write(ENABLE::ENABLE::SET);
376        self.registers.inten.write(INTEN::CALIBRATEDONE::SET);
377        self.registers.tasks_calibrateoffset.write(TASK::TASK::SET);
378    }
379
380    pub fn handle_interrupt(&self) {
381        match self.mode.get() {
382            AdcMode::Calibrate => {
383                if self.registers.events_calibratedone.is_set(EVENT::EVENT) {
384                    self.registers
385                        .events_calibratedone
386                        .write(EVENT::EVENT::CLEAR);
387
388                    // After calibration, read VDD to set our voltage reference.
389                    self.registers.ch[0].pselp.write(PSEL::PSEL::VDD);
390                    self.registers.ch[0].pseln.write(PSEL::PSEL::NotConnected);
391
392                    // Configure the ADC for a single read.
393                    self.registers.ch[0].config.write(
394                        CONFIG::GAIN::Gain1_6
395                            + CONFIG::REFSEL::Internal
396                            + CONFIG::TACQ::us10
397                            + CONFIG::RESP::Bypass
398                            + CONFIG::RESN::Bypass
399                            + CONFIG::MODE::SE,
400                    );
401
402                    self.setup_resolution();
403                    self.setup_sample_count(1);
404
405                    // Where to put the reading.
406                    let sample: *const [u16; 1] = addr_of!(SAMPLE);
407                    let sample: *const u16 = sample.cast();
408                    self.registers.result_ptr.set(sample as u32);
409
410                    // No automatic sampling, will trigger manually.
411                    self.registers.samplerate.write(SAMPLERATE::MODE::Task);
412
413                    // Enable the ADC
414                    self.registers.enable.write(ENABLE::ENABLE::SET);
415
416                    // Enable started, sample end, and stopped interrupts.
417                    self.registers
418                        .inten
419                        .write(INTEN::STARTED::SET + INTEN::END::SET + INTEN::STOPPED::SET);
420
421                    self.registers.tasks_start.write(TASK::TASK::SET);
422
423                    // self.registers.enable.write(ENABLE::ENABLE::CLEAR);
424                } else if self.registers.events_started.is_set(EVENT::EVENT) {
425                    self.registers.events_started.write(EVENT::EVENT::CLEAR);
426                    // ADC has started, now issue the sample.
427                    self.registers.tasks_sample.write(TASK::TASK::SET);
428                } else if self.registers.events_end.is_set(EVENT::EVENT) {
429                    self.registers.events_end.write(EVENT::EVENT::CLEAR);
430                    // Reading finished. Turn off the ADC.
431                    self.registers.tasks_stop.write(TASK::TASK::SET);
432                } else if self.registers.events_stopped.is_set(EVENT::EVENT) {
433                    self.registers.events_stopped.write(EVENT::EVENT::CLEAR);
434                    // ADC is stopped. Disable and return value.
435                    self.registers.enable.write(ENABLE::ENABLE::CLEAR);
436
437                    let reading = unsafe { SAMPLE[0] as i16 } as usize;
438
439                    // reading = val * (gain/ref) * 2^12
440                    //         = val * ((1/6)/0.6 V) * 2^12
441                    //         = val * 1/3600 mV * 2^12
442                    // val = (reading * 3600 mV) / 2^12
443                    let val = (reading * 3600) / (1 << 12);
444
445                    // If the reading looks like it exists in a reasonable range
446                    // than save this as the reference.
447                    if val > 1000 && val < 5100 {
448                        self.reference.set(val);
449                    }
450                }
451            }
452
453            AdcMode::Single => {
454                // Determine what event occurred.
455                if self.registers.events_calibratedone.is_set(EVENT::EVENT) {
456                    self.registers
457                        .events_calibratedone
458                        .write(EVENT::EVENT::CLEAR);
459                    self.registers.enable.write(ENABLE::ENABLE::CLEAR);
460                } else if self.registers.events_started.is_set(EVENT::EVENT) {
461                    self.registers.events_started.write(EVENT::EVENT::CLEAR);
462                    // ADC has started, now issue the sample.
463                    self.registers.tasks_sample.write(TASK::TASK::SET);
464                } else if self.registers.events_end.is_set(EVENT::EVENT) {
465                    self.registers.events_end.write(EVENT::EVENT::CLEAR);
466                    // Reading finished. Turn off the ADC.
467                    self.registers.tasks_stop.write(TASK::TASK::SET);
468                } else if self.registers.events_stopped.is_set(EVENT::EVENT) {
469                    self.registers.events_stopped.write(EVENT::EVENT::CLEAR);
470                    // ADC is stopped. Disable and return value.
471                    self.registers.enable.write(ENABLE::ENABLE::CLEAR);
472
473                    let val = unsafe { SAMPLE[0] as i16 };
474                    self.client.map(|client| {
475                        // shift left to meet the ADC HIL requirement
476                        client.sample_ready(if val < 0 { 0 } else { val << 4 } as u16);
477                    });
478                }
479            }
480
481            AdcMode::HighSpeed => {
482                if self.registers.events_started.is_set(EVENT::EVENT) {
483                    self.registers.events_started.write(EVENT::EVENT::CLEAR);
484
485                    // According to PS1.7 Section 6.23.4, we can set the new
486                    // buffer address after we get the start event.
487                    self.next_buffer.map(|buf| {
488                        // First determine the buffer's length in samples.
489                        let dma_len = cmp::min(buf.len(), self.next_length.get());
490                        if dma_len > 0 {
491                            self.registers.result_ptr.set(buf.as_ptr() as u32);
492                        }
493                    });
494
495                    // Trigger sample task to start taking samples.
496                    self.registers.tasks_sample.write(TASK::TASK::SET);
497                } else if self.registers.events_end.is_set(EVENT::EVENT) {
498                    self.registers.events_end.write(EVENT::EVENT::CLEAR);
499
500                    let ret_buf = self.buffer.take().unwrap();
501
502                    // Left shift all samples to the MSB. This handles
503                    // differences in resolution between ADC chips and meets the
504                    // ADC HIL requirement.
505                    let length = self.length.get();
506                    for i in 0..length {
507                        ret_buf[i] <<= 4;
508                    }
509
510                    self.highspeed_client.map(|client| {
511                        client.samples_ready(ret_buf, length);
512                    });
513
514                    // Optionally setup to continue reading. We already
515                    // configured the address if valid.
516                    let length2 = self.next_length.get();
517                    if length2 > 0 {
518                        self.length.set(length2);
519                        self.buffer.put(self.next_buffer.take());
520                        self.registers
521                            .result_maxcnt
522                            .write(RESULT_MAXCNT::MAXCNT.val(length2 as u32));
523                        kernel::debug!("len2 {}", length2);
524
525                        // self.registers.tasks_sample.write(TASK::TASK::SET);
526                        self.registers.tasks_start.write(TASK::TASK::SET);
527                    }
528                } else if self.registers.events_stopped.is_set(EVENT::EVENT) {
529                    self.registers.events_stopped.write(EVENT::EVENT::CLEAR);
530                }
531            }
532
533            AdcMode::Idle => {}
534        }
535    }
536
537    fn setup_channel(&self, channel: &AdcChannelSetup) {
538        // Positive goes to the channel passed in, negative not connected.
539        self.registers.ch[0]
540            .pselp
541            .write(PSEL::PSEL.val(channel.channel as u32));
542        self.registers.ch[0].pseln.write(PSEL::PSEL::NotConnected);
543
544        // Configure the ADC for a single read.
545        self.registers.ch[0].config.write(
546            CONFIG::GAIN.val(channel.gain as u32)
547                + CONFIG::REFSEL::VDD1_4
548                + CONFIG::TACQ.val(channel.sampling_time as u32)
549                + CONFIG::RESP.val(channel.resp as u32)
550                + CONFIG::RESN.val(channel.resn as u32)
551                + CONFIG::MODE::SE,
552        );
553    }
554
555    fn setup_resolution(&self) {
556        // Set max resolution (with oversampling).
557        self.registers.resolution.write(RESOLUTION::VAL::bit12);
558    }
559
560    fn setup_sample_count(&self, count: usize) {
561        self.registers
562            .result_maxcnt
563            .write(RESULT_MAXCNT::MAXCNT.val(count as u32));
564    }
565
566    fn setup_frequency(&self, frequency: u32) {
567        let raw_cc = 16000000 / frequency;
568        let cc = raw_cc.clamp(80, 2047);
569
570        self.registers
571            .samplerate
572            .write(SAMPLERATE::MODE::Timers + SAMPLERATE::CC.val(cc));
573    }
574}
575
576/// Implements an ADC capable reading ADC samples on any channel.
577impl<'a> hil::adc::Adc<'a> for Adc<'a> {
578    type Channel = AdcChannelSetup;
579
580    fn sample(&self, channel: &Self::Channel) -> Result<(), ErrorCode> {
581        self.setup_channel(channel);
582        self.setup_resolution();
583
584        // Do one measurement.
585        self.registers
586            .result_maxcnt
587            .write(RESULT_MAXCNT::MAXCNT.val(1));
588        // Where to put the reading.
589        let sample: *const [u16; 1] = addr_of!(SAMPLE);
590        let sample: *const u16 = sample.cast();
591        self.registers.result_ptr.set(sample as u32);
592
593        // No automatic sampling, will trigger manually.
594        self.registers.samplerate.write(SAMPLERATE::MODE::Task);
595
596        // Enable the ADC
597        self.registers.enable.write(ENABLE::ENABLE::SET);
598
599        // Enable started, sample end, and stopped interrupts.
600        self.registers
601            .inten
602            .write(INTEN::STARTED::SET + INTEN::END::SET + INTEN::STOPPED::SET);
603
604        self.mode.set(AdcMode::Single);
605
606        // Start the SAADC and wait for the started interrupt.
607        self.registers.tasks_start.write(TASK::TASK::SET);
608
609        Ok(())
610    }
611
612    fn sample_continuous(
613        &self,
614        _channel: &Self::Channel,
615        _frequency: u32,
616    ) -> Result<(), ErrorCode> {
617        Err(ErrorCode::FAIL)
618    }
619
620    fn stop_sampling(&self) -> Result<(), ErrorCode> {
621        self.registers.tasks_stop.write(TASK::TASK::SET);
622        Ok(())
623    }
624
625    fn get_resolution_bits(&self) -> usize {
626        12
627    }
628
629    fn get_voltage_reference_mv(&self) -> Option<usize> {
630        Some(self.reference.get())
631    }
632
633    fn set_client(&self, client: &'a dyn hil::adc::Client) {
634        self.client.set(client);
635    }
636}
637
638impl<'a> hil::adc::AdcHighSpeed<'a> for Adc<'a> {
639    fn sample_highspeed(
640        &self,
641        channel: &Self::Channel,
642        frequency: u32,
643        buffer1: &'static mut [u16],
644        length1: usize,
645        buffer2: &'static mut [u16],
646        length2: usize,
647    ) -> Result<(), (ErrorCode, &'static mut [u16], &'static mut [u16])> {
648        if length1 == 0 {
649            // At least need to take one sample.
650            Err((ErrorCode::INVAL, buffer1, buffer2))
651        } else {
652            // Store the second buffer for later use
653            self.next_buffer.replace(buffer2);
654            self.next_length.set(length2);
655
656            self.setup_channel(channel);
657            self.setup_resolution();
658
659            // Use EasyDMA to save the samples to our buffer.
660            self.registers.result_ptr.set(buffer1.as_ptr() as u32);
661
662            // Also need to save these to return to the caller.
663            self.buffer.replace(buffer1);
664            self.length.set(length1);
665
666            // Number of measurements.
667            self.setup_sample_count(length1);
668
669            // Set the frequency best we can.
670            self.setup_frequency(frequency);
671
672            // Enable the ADC
673            self.registers.enable.write(ENABLE::ENABLE::SET);
674
675            // Enable started, sample end, and stopped interrupts.
676            self.registers
677                .inten
678                .write(INTEN::STARTED::SET + INTEN::END::SET + INTEN::STOPPED::SET);
679
680            self.mode.set(AdcMode::HighSpeed);
681
682            // Start the SAADC and wait for the started interrupt.
683            self.registers.tasks_start.write(TASK::TASK::SET);
684
685            Ok(())
686        }
687    }
688
689    fn provide_buffer(
690        &self,
691        buf: &'static mut [u16],
692        length: usize,
693    ) -> Result<(), (ErrorCode, &'static mut [u16])> {
694        if self.next_buffer.is_some() {
695            // we've already got a second buffer, we don't need a third yet
696            Err((ErrorCode::BUSY, buf))
697        } else {
698            // store the buffer for later use
699            self.next_buffer.replace(buf);
700            self.next_length.set(length);
701
702            Ok(())
703        }
704    }
705
706    fn retrieve_buffers(
707        &self,
708    ) -> Result<(Option<&'static mut [u16]>, Option<&'static mut [u16]>), ErrorCode> {
709        Ok((self.buffer.take(), self.next_buffer.take()))
710    }
711
712    fn set_highspeed_client(&self, client: &'a dyn hil::adc::HighSpeedClient) {
713        self.highspeed_client.set(client);
714    }
715}