|
| 1 | +use core::marker::PhantomData; |
| 2 | +use core::sync::atomic::{Ordering, compiler_fence}; |
| 3 | + |
| 4 | +use embassy_hal_internal::Peri; |
| 5 | + |
| 6 | +use crate::adc::{Instance, RxDma}; |
| 7 | +use crate::dma::{ReadableRingBuffer, TransferOptions}; |
| 8 | +use crate::rcc; |
| 9 | + |
| 10 | +#[cfg_attr(feature = "defmt", derive(defmt::Format))] |
| 11 | +pub struct OverrunError; |
| 12 | + |
| 13 | +pub struct RingBufferedAdc<'d, T: Instance> { |
| 14 | + pub _phantom: PhantomData<T>, |
| 15 | + pub ring_buf: ReadableRingBuffer<'d, u16>, |
| 16 | +} |
| 17 | + |
| 18 | +impl<'d, T: Instance> RingBufferedAdc<'d, T> { |
| 19 | + pub(crate) fn new(dma: Peri<'d, impl RxDma<T>>, dma_buf: &'d mut [u16]) -> Self { |
| 20 | + //dma side setup |
| 21 | + let opts = TransferOptions { |
| 22 | + half_transfer_ir: true, |
| 23 | + circular: true, |
| 24 | + ..Default::default() |
| 25 | + }; |
| 26 | + |
| 27 | + // Safety: we forget the struct before this function returns. |
| 28 | + let request = dma.request(); |
| 29 | + |
| 30 | + let ring_buf = |
| 31 | + unsafe { ReadableRingBuffer::new(dma, request, T::regs().dr().as_ptr() as *mut u16, dma_buf, opts) }; |
| 32 | + |
| 33 | + Self { |
| 34 | + _phantom: PhantomData, |
| 35 | + ring_buf, |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + #[inline] |
| 40 | + fn start_continuous_sampling(&mut self) { |
| 41 | + // Start adc conversion |
| 42 | + T::regs().cr().modify(|reg| { |
| 43 | + reg.set_adstart(true); |
| 44 | + }); |
| 45 | + self.ring_buf.start(); |
| 46 | + } |
| 47 | + |
| 48 | + #[inline] |
| 49 | + pub fn stop_continuous_sampling(&mut self) { |
| 50 | + // Stop adc conversion |
| 51 | + if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { |
| 52 | + T::regs().cr().modify(|reg| { |
| 53 | + reg.set_adstp(true); |
| 54 | + }); |
| 55 | + while T::regs().cr().read().adstart() {} |
| 56 | + } |
| 57 | + } |
| 58 | + pub fn disable_adc(&mut self) { |
| 59 | + self.stop_continuous_sampling(); |
| 60 | + self.ring_buf.clear(); |
| 61 | + self.ring_buf.request_pause(); |
| 62 | + } |
| 63 | + |
| 64 | + pub fn teardown_adc(&mut self) { |
| 65 | + self.disable_adc(); |
| 66 | + |
| 67 | + //disable dma control |
| 68 | + #[cfg(not(any(adc_g0, adc_u0)))] |
| 69 | + T::regs().cfgr().modify(|reg| { |
| 70 | + reg.set_dmaen(false); |
| 71 | + }); |
| 72 | + #[cfg(any(adc_g0, adc_u0))] |
| 73 | + T::regs().cfgr1().modify(|reg| { |
| 74 | + reg.set_dmaen(false); |
| 75 | + }); |
| 76 | + |
| 77 | + //TODO: do we need to cleanup the DMA request here? |
| 78 | + |
| 79 | + compiler_fence(Ordering::SeqCst); |
| 80 | + } |
| 81 | + |
| 82 | + /// Reads measurements from the DMA ring buffer. |
| 83 | + /// |
| 84 | + /// This method fills the provided `measurements` array with ADC readings from the DMA buffer. |
| 85 | + /// The length of the `measurements` array should be exactly half of the DMA buffer length. Because interrupts are only generated if half or full DMA transfer completes. |
| 86 | + /// |
| 87 | + /// Each call to `read` will populate the `measurements` array in the same order as the channels defined with `sequence`. |
| 88 | + /// There will be many sequences worth of measurements in this array because it only returns if at least half of the DMA buffer is filled. |
| 89 | + /// For example if 2 channels are sampled `measurements` contain: `[sq0 sq1 sq0 sq1 sq0 sq1 ..]`. |
| 90 | + /// |
| 91 | + /// Note that the ADC Datarate can be very fast, it is suggested to use DMA mode inside tightly running tasks |
| 92 | + /// Otherwise, you'll see constant Overrun errors occuring, this means that you're sampling too quickly for the task to handle, and you may need to increase the buffer size. |
| 93 | + /// Example: |
| 94 | + /// ```rust,ignore |
| 95 | + /// const DMA_BUF_LEN: usize = 120; |
| 96 | + /// use embassy_stm32::adc::{Adc, AdcChannel} |
| 97 | + /// |
| 98 | + /// let mut adc = Adc::new(p.ADC1); |
| 99 | + /// let mut adc_pin0 = p.PA0.degrade_adc(); |
| 100 | + /// let mut adc_pin1 = p.PA1.degrade_adc(); |
| 101 | + /// let adc_dma_buf = [0u16; DMA_BUF_LEN]; |
| 102 | + /// |
| 103 | + /// let mut ring_buffered_adc: RingBufferedAdc<embassy_stm32::peripherals::ADC1> = adc.into_ring_buffered( |
| 104 | + /// p.DMA2_CH0, |
| 105 | + /// adc_dma_buf, [ |
| 106 | + /// (&mut *adc_pin0, SampleTime::CYCLES160_5), |
| 107 | + /// (&mut *adc_pin1, SampleTime::CYCLES160_5), |
| 108 | + /// ].into_iter()); |
| 109 | + /// |
| 110 | + /// |
| 111 | + /// let mut measurements = [0u16; DMA_BUF_LEN / 2]; |
| 112 | + /// loop { |
| 113 | + /// match ring_buffered_adc.read(&mut measurements).await { |
| 114 | + /// Ok(_) => { |
| 115 | + /// defmt::info!("adc1: {}", measurements); |
| 116 | + /// } |
| 117 | + /// Err(e) => { |
| 118 | + /// defmt::warn!("Error: {:?}", e); |
| 119 | + /// } |
| 120 | + /// } |
| 121 | + /// } |
| 122 | + /// ``` |
| 123 | + /// |
| 124 | + /// |
| 125 | + /// [`teardown_adc`]: #method.teardown_adc |
| 126 | + /// [`start_continuous_sampling`]: #method.start_continuous_sampling |
| 127 | + pub async fn read(&mut self, measurements: &mut [u16]) -> Result<usize, OverrunError> { |
| 128 | + assert_eq!( |
| 129 | + self.ring_buf.capacity() / 2, |
| 130 | + measurements.len(), |
| 131 | + "Buffer size must be half the size of the ring buffer" |
| 132 | + ); |
| 133 | + |
| 134 | + let r = T::regs(); |
| 135 | + |
| 136 | + // Start background receive if it was not already started |
| 137 | + if !r.cr().read().adstart() { |
| 138 | + self.start_continuous_sampling(); |
| 139 | + } |
| 140 | + |
| 141 | + self.ring_buf.read_exact(measurements).await.map_err(|_| OverrunError) |
| 142 | + } |
| 143 | + |
| 144 | + /// Read bytes that are readily available in the ring buffer. |
| 145 | + /// If no bytes are currently available in the buffer the call waits until the some |
| 146 | + /// bytes are available (at least one byte and at most half the buffer size) |
| 147 | + /// |
| 148 | + /// Background receive is started if `start_continuous_sampling()` has not been previously called. |
| 149 | + /// |
| 150 | + /// Receive in the background is terminated if an error is returned. |
| 151 | + /// It must then manually be started again by calling `start_continuous_sampling()` or by re-calling `blocking_read()`. |
| 152 | + pub fn blocking_read(&mut self, buf: &mut [u16]) -> Result<usize, OverrunError> { |
| 153 | + let r = T::regs(); |
| 154 | + |
| 155 | + // Start background receive if it was not already started |
| 156 | + if !r.cr().read().adstart() { |
| 157 | + self.start_continuous_sampling(); |
| 158 | + } |
| 159 | + |
| 160 | + loop { |
| 161 | + match self.ring_buf.read(buf) { |
| 162 | + Ok((0, _)) => {} |
| 163 | + Ok((len, _)) => { |
| 164 | + return Ok(len); |
| 165 | + } |
| 166 | + Err(_) => { |
| 167 | + self.stop_continuous_sampling(); |
| 168 | + return Err(OverrunError); |
| 169 | + } |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +impl<T: Instance> Drop for RingBufferedAdc<'_, T> { |
| 176 | + fn drop(&mut self) { |
| 177 | + self.teardown_adc(); |
| 178 | + rcc::disable::<T>(); |
| 179 | + } |
| 180 | +} |
0 commit comments