Skip to main content

ch32_hal/
dac.rs

1//! Digital to Analog Converter (DAC)
2#![macro_use]
3
4use core::marker::PhantomData;
5use core::sync::atomic::{AtomicU8, Ordering};
6
7use crate::dma::NoDma;
8use crate::gpio::{AnyPin, SealedPin};
9use crate::internal::drop::OnDrop;
10pub use crate::pac::dac::vals::{TrigSel as TriggerSel, Wave as Waveform};
11use crate::peripheral::RccPeripheral;
12use crate::{peripherals, Peri, PeripheralType};
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq)]
15#[cfg_attr(feature = "defmt", derive(defmt::Format))]
16pub enum Error {
17    /// The DMA transfer counter cannot represent the buffer length.
18    BufferTooLong,
19    /// DMA requires an enabled hardware trigger, excluding software trigger.
20    TriggerNotConfigured,
21    /// Waveform amplitude must be in the range 0..=11.
22    InvalidAmplitude,
23}
24
25struct State {
26    users: AtomicU8,
27}
28
29fn validate_dma(control: &crate::pac::dac::regs::Cr, channel: usize, length: usize) -> Result<(), Error> {
30    if length == 0 {
31        return Ok(());
32    }
33    if length > u16::MAX as usize {
34        return Err(Error::BufferTooLong);
35    }
36    if !control.ten(channel) || control.tsel(channel) == TriggerSel::SOFTWARE {
37        return Err(Error::TriggerNotConfigured);
38    }
39    Ok(())
40}
41
42fn acquire<T: Instance>(channels: u8) {
43    critical_section::with(|cs| {
44        let users = T::state().users.load(Ordering::Relaxed);
45        assert!(users + channels <= 2);
46        if users == 0 {
47            T::enable_and_reset_with_cs(cs);
48        }
49        T::state().users.store(users + channels, Ordering::Relaxed);
50    });
51}
52
53fn release<T: Instance>(channel: usize) {
54    critical_section::with(|cs| {
55        T::regs().cr().modify(|reg| {
56            reg.set_en(channel, false);
57            reg.set_dmaen(channel, false);
58            reg.set_ten(channel, false);
59        });
60        let users = T::state().users.load(Ordering::Relaxed);
61        T::state().users.store(users - 1, Ordering::Relaxed);
62        if users == 1 {
63            T::disable_with_cs(cs);
64        }
65    });
66}
67
68#[derive(Debug, Copy, Clone, Eq, PartialEq)]
69#[cfg_attr(feature = "defmt", derive(defmt::Format))]
70/// Single 8 or 12 bit value that can be output by the DAC.
71///
72/// 12-bit values outside the permitted range are silently truncated.
73pub enum Value {
74    /// 8 bit value
75    Bit8(u8),
76    /// Unshifted 12-bit value, written through the left-aligned register.
77    Bit12Left(u16),
78    /// 12 bit value stored in a u16, right-aligned
79    Bit12Right(u16),
80}
81
82#[derive(Debug, Copy, Clone, Eq, PartialEq)]
83#[cfg_attr(feature = "defmt", derive(defmt::Format))]
84/// Dual 8 or 12 bit values that can be output by the DAC channels 1 and 2 simultaneously.
85///
86/// 12-bit values outside the permitted range are silently truncated.
87pub enum DualValue {
88    /// 8 bit value
89    Bit8(u8, u8),
90    /// Unshifted 12-bit values, written through the left-aligned register.
91    Bit12Left(u16, u16),
92    /// 12 bit value stored in a u16, right-aligned
93    Bit12Right(u16, u16),
94}
95
96#[derive(Debug, Copy, Clone, Eq, PartialEq)]
97#[cfg_attr(feature = "defmt", derive(defmt::Format))]
98/// Array variant of [`Value`].
99pub enum ValueArray<'a> {
100    /// 8 bit values
101    Bit8(&'a [u8]),
102    /// DMA words with each 12-bit sample already aligned to bits 15:4.
103    Bit12Left(&'a [u16]),
104    /// 12 bit values stored in a u16, right-aligned
105    Bit12Right(&'a [u16]),
106}
107
108/// Driver for a single DAC channel.
109///
110/// If you want to use both channels, either together or independently,
111/// create a [`Dac`] first and use it to access each channel.
112pub struct DacChannel<'d, T: Instance, const N: u8, DMA: PeripheralType = NoDma> {
113    phantom: PhantomData<&'d mut T>,
114    pin: Peri<'d, AnyPin>,
115    #[allow(unused)]
116    dma: Peri<'d, DMA>,
117}
118
119/// DAC channel 1 type alias.
120pub type DacCh1<'d, T, DMA = NoDma> = DacChannel<'d, T, 1, DMA>;
121/// DAC channel 2 type alias.
122pub type DacCh2<'d, T, DMA = NoDma> = DacChannel<'d, T, 2, DMA>;
123
124impl<'d, T: Instance, const N: u8, DMA: PeripheralType> DacChannel<'d, T, N, DMA> {
125    const IDX: usize = (N - 1) as usize;
126
127    /// Create a new `DacChannel` instance, consuming the underlying DAC peripheral.
128    ///
129    /// If you're not using DMA, pass [`dma::NoDma`] for the `dma` argument.
130    ///
131    /// The channel is enabled on creation and begin to drive the output pin.
132    /// Note that methods such as `set_trigger()` will
133    /// disable the channel; you must re-enable it with `enable()`.
134    ///
135    /// By default, triggering is disabled, but it can be enabled using
136    /// [`DacChannel::set_trigger()`].
137    pub fn new(_peri: Peri<'d, T>, dma: Peri<'d, DMA>, pin: Peri<'d, impl DacPin<T, N> + crate::gpio::Pin>) -> Self {
138        assert!(N == 1 || N == 2);
139        pin.set_as_analog();
140        acquire::<T>(1);
141        let mut dac = Self {
142            phantom: PhantomData,
143            pin: pin.into(),
144            dma,
145        };
146        dac.enable();
147        dac
148    }
149
150    /// Enable or disable this channel.
151    pub fn set_enable(&mut self, on: bool) {
152        critical_section::with(|_| {
153            T::regs().cr().modify(|reg| {
154                reg.set_en(Self::IDX, on);
155            });
156        });
157    }
158
159    /// Enable this channel.
160    pub fn enable(&mut self) {
161        self.set_enable(true)
162    }
163
164    /// Disable this channel.
165    pub fn disable(&mut self) {
166        self.set_enable(false)
167    }
168
169    /// Enable the output buffer, or bypass it for a high-impedance load.
170    pub fn set_buffering(&mut self, enabled: bool) {
171        critical_section::with(|_| {
172            T::regs().cr().modify(|reg| reg.set_boff(Self::IDX, !enabled));
173        });
174    }
175
176    /// Select noise or triangle generation and its mask/amplitude encoding.
177    pub fn set_waveform(&mut self, waveform: Waveform, amplitude: u8) -> Result<(), Error> {
178        if amplitude > 11 {
179            return Err(Error::InvalidAmplitude);
180        }
181        critical_section::with(|_| {
182            T::regs().cr().modify(|reg| {
183                reg.set_wave(Self::IDX, waveform);
184                reg.set_mamp(Self::IDX, amplitude);
185            });
186        });
187        Ok(())
188    }
189
190    /// Set the trigger source for this channel.
191    ///
192    /// This method disables the channel, so you may need to re-enable afterwards.
193    pub fn set_trigger(&mut self, source: TriggerSel) {
194        critical_section::with(|_| {
195            T::regs().cr().modify(|reg| {
196                reg.set_en(Self::IDX, false);
197                reg.set_tsel(Self::IDX, source);
198            });
199        });
200    }
201
202    /// Enable or disable triggering for this channel.
203    pub fn set_triggering(&mut self, on: bool) {
204        critical_section::with(|_| {
205            T::regs().cr().modify(|reg| {
206                reg.set_ten(Self::IDX, on);
207            });
208        });
209    }
210
211    /// Software trigger this channel.
212    pub fn trigger(&mut self) {
213        T::regs().swtrigr().write(|reg| {
214            reg.set_swtrig(Self::IDX, true);
215        });
216    }
217
218    /// Write a new value to this channel.
219    ///
220    /// If triggering is not enabled, the new value is immediately output; otherwise,
221    /// it will be output after the next trigger.
222    pub fn set(&mut self, value: Value) {
223        match value {
224            Value::Bit8(v) => T::regs().dhr8r(Self::IDX).write(|reg| reg.set_dhr(v)),
225            Value::Bit12Left(v) => T::regs().dhr12l(Self::IDX).write(|reg| reg.set_dhr(v)),
226            Value::Bit12Right(v) => T::regs().dhr12r(Self::IDX).write(|reg| reg.set_dhr(v)),
227        }
228    }
229
230    /// Read the current output value of the DAC.
231    pub fn read(&self) -> u16 {
232        T::regs().dor(Self::IDX).read().dor()
233    }
234}
235
236macro_rules! impl_dma_methods {
237    ($n:literal, $trait:ident) => {
238        impl<'d, T: Instance, DMA: PeripheralType> DacChannel<'d, T, $n, DMA>
239        where
240            DMA: $trait<T>,
241        {
242            /// Write `data` to this channel via DMA.
243            ///
244            /// To prevent delays or glitches when outputing a periodic waveform, the `circular`
245            /// flag can be set. This configures a circular DMA transfer that continually outputs
246            /// `data`. Note that for performance reasons in circular mode the transfer-complete
247            /// interrupt is disabled.
248            #[cfg(not(gpdma))]
249            pub async fn write(&mut self, data: ValueArray<'_>, circular: bool) {
250                self.try_write(data, circular)
251                    .await
252                    .expect("invalid DAC DMA configuration");
253            }
254
255            /// DMA output, stopping the channel on cancellation.
256            ///
257            /// Requires triggering enabled with a timer or EXTI source. Circular
258            /// transfers run until cancelled. Empty buffers leave the DAC unchanged.
259            /// Completion means all samples reached the holding register; the last
260            /// sample may need another trigger to reach the output. The channel
261            /// stays enabled on completion, with its DMA request disabled.
262            #[cfg(not(gpdma))]
263            pub async fn try_write(&mut self, data: ValueArray<'_>, circular: bool) -> Result<(), Error> {
264                let length = match &data {
265                    ValueArray::Bit8(buffer) => buffer.len(),
266                    ValueArray::Bit12Left(buffer) | ValueArray::Bit12Right(buffer) => buffer.len(),
267                };
268                if length == 0 {
269                    return Ok(());
270                }
271                let control = T::regs().cr().read();
272                validate_dma(&control, Self::IDX, length)?;
273                let cleanup = OnDrop::new(|| {
274                    critical_section::with(|_| {
275                        T::regs().cr().modify(|w| {
276                            w.set_en(Self::IDX, false);
277                            w.set_dmaen(Self::IDX, false);
278                        });
279                    });
280                });
281
282                let tx_request = self.dma.request();
283
284                let tx_options = crate::dma::TransferOptions {
285                    circular,
286                    half_transfer_ir: false,
287                    complete_transfer_ir: !circular,
288                    ..Default::default()
289                };
290
291                let tx_f = match data {
292                    ValueArray::Bit8(buf) => unsafe {
293                        crate::dma::Transfer::new_write(
294                            self.dma.clone_unchecked(),
295                            tx_request,
296                            buf,
297                            T::regs().dhr8r(Self::IDX).as_ptr() as *mut u8,
298                            tx_options,
299                        )
300                    },
301                    ValueArray::Bit12Left(buf) => unsafe {
302                        crate::dma::Transfer::new_write(
303                            self.dma.clone_unchecked(),
304                            tx_request,
305                            buf,
306                            T::regs().dhr12l(Self::IDX).as_ptr() as *mut u16,
307                            tx_options,
308                        )
309                    },
310                    ValueArray::Bit12Right(buf) => unsafe {
311                        crate::dma::Transfer::new_write(
312                            self.dma.clone_unchecked(),
313                            tx_request,
314                            buf,
315                            T::regs().dhr12r(Self::IDX).as_ptr() as *mut u16,
316                            tx_options,
317                        )
318                    },
319                };
320
321                critical_section::with(|_| {
322                    T::regs().cr().modify(|w| {
323                        w.set_en(Self::IDX, true);
324                        w.set_dmaen(Self::IDX, true);
325                    });
326                });
327
328                tx_f.await;
329                critical_section::with(|_| {
330                    T::regs().cr().modify(|w| w.set_dmaen(Self::IDX, false));
331                });
332                cleanup.defuse();
333                Ok(())
334            }
335        }
336    };
337}
338
339impl_dma_methods!(1, DacDma1);
340impl_dma_methods!(2, DacDma2);
341
342impl<'d, T: Instance, const N: u8, DMA: PeripheralType> Drop for DacChannel<'d, T, N, DMA> {
343    fn drop(&mut self) {
344        self.pin.set_as_disconnected();
345        release::<T>(Self::IDX);
346    }
347}
348
349/// DAC driver.
350///
351/// Use this struct when you want to use both channels, either together or independently.
352///
353/// # Example
354///
355/// ```ignore
356/// // Pins may need to be changed for your specific device.
357/// let (dac_ch1, dac_ch2) = ch32_hal::dac::Dac::new(p.DAC1, dma_ch1, dma_ch2, p.PA4, p.PA5).split();
358/// ```
359pub struct Dac<'d, T: Instance, DMACh1: PeripheralType = NoDma, DMACh2: PeripheralType = NoDma> {
360    ch1: DacChannel<'d, T, 1, DMACh1>,
361    ch2: DacChannel<'d, T, 2, DMACh2>,
362}
363
364impl<'d, T: Instance, DMACh1: PeripheralType, DMACh2: PeripheralType> Dac<'d, T, DMACh1, DMACh2> {
365    /// Create a new `Dac` instance, consuming the underlying DAC peripheral.
366    ///
367    /// This struct allows you to access both channels of the DAC, where available. You can either
368    /// call `split()` to obtain separate `DacChannel`s, or use methods on `Dac` to use
369    /// the two channels together.
370    ///
371    /// The channels are enabled on creation and begin to drive their output pins.
372    /// Note that methods such as `set_trigger()` will
373    /// disable the channel; you must re-enable them with `enable()`.
374    ///
375    /// By default, triggering is disabled, but it can be enabled using the `set_trigger()`
376    /// method on the underlying channels.
377    pub fn new(
378        _peri: Peri<'d, T>,
379        dma_ch1: Peri<'d, DMACh1>,
380        dma_ch2: Peri<'d, DMACh2>,
381        pin_ch1: Peri<'d, impl DacPin<T, 1> + crate::gpio::Pin>,
382        pin_ch2: Peri<'d, impl DacPin<T, 2> + crate::gpio::Pin>,
383    ) -> Self {
384        pin_ch1.set_as_analog();
385        pin_ch2.set_as_analog();
386
387        acquire::<T>(2);
388
389        let mut ch1 = DacCh1 {
390            phantom: PhantomData,
391            pin: pin_ch1.into(),
392            dma: dma_ch1,
393        };
394        #[cfg(any(dac_v5, dac_v6, dac_v7))]
395        ch1.set_hfsel();
396        ch1.enable();
397
398        let mut ch2 = DacCh2 {
399            phantom: PhantomData,
400            pin: pin_ch2.into(),
401            dma: dma_ch2,
402        };
403        #[cfg(any(dac_v5, dac_v6, dac_v7))]
404        ch2.set_hfsel();
405        ch2.enable();
406
407        Self { ch1, ch2 }
408    }
409
410    /// Split this `Dac` into separate channels.
411    ///
412    /// You can access and move the channels around separately after splitting.
413    pub fn split(self) -> (DacCh1<'d, T, DMACh1>, DacCh2<'d, T, DMACh2>) {
414        (self.ch1, self.ch2)
415    }
416
417    /// Temporarily access channel 1.
418    pub fn ch1(&mut self) -> &mut DacCh1<'d, T, DMACh1> {
419        &mut self.ch1
420    }
421
422    /// Temporarily access channel 2.
423    pub fn ch2(&mut self) -> &mut DacCh2<'d, T, DMACh2> {
424        &mut self.ch2
425    }
426
427    /// Trigger both channels in the same peripheral write.
428    pub fn trigger(&mut self) {
429        T::regs().swtrigr().write(|reg| {
430            reg.set_swtrig(0, true);
431            reg.set_swtrig(1, true);
432        });
433    }
434
435    /// Simultaneously update channels 1 and 2 with a new value.
436    ///
437    /// If triggering is not enabled, the new values are immediately output;
438    /// otherwise, they will be output after the next trigger.
439    pub fn set(&mut self, values: DualValue) {
440        match values {
441            DualValue::Bit8(v1, v2) => T::regs().dhr8rd().write(|reg| {
442                reg.set_dhr(0, v1);
443                reg.set_dhr(1, v2);
444            }),
445            DualValue::Bit12Left(v1, v2) => T::regs().dhr12ld().write(|reg| {
446                reg.set_dhr(0, v1);
447                reg.set_dhr(1, v2);
448            }),
449            DualValue::Bit12Right(v1, v2) => T::regs().dhr12rd().write(|reg| {
450                reg.set_dhr(0, v1);
451                reg.set_dhr(1, v2);
452            }),
453        }
454    }
455}
456
457trait SealedInstance {
458    fn regs() -> &'static crate::pac::dac::Dac;
459    fn state() -> &'static State;
460}
461
462/// DAC instance.
463#[allow(private_bounds)]
464pub trait Instance: SealedInstance + embassy_hal_internal::PeripheralType + RccPeripheral + 'static {}
465dma_trait!(DacDma1, Instance);
466dma_trait!(DacDma2, Instance);
467
468/// Marks a pin that can be used with the DAC
469pub trait DacPin<T: Instance, const C: u8>: crate::gpio::Pin + 'static {}
470
471foreach_peripheral!(
472    (dac, $inst:ident) => {
473        impl crate::dac::SealedInstance for peripherals::$inst {
474            fn regs() -> &'static crate::pac::dac::Dac {
475                &crate::pac::$inst
476            }
477
478            fn state() -> &'static State {
479                static STATE: State = State { users: AtomicU8::new(0) };
480                &STATE
481            }
482        }
483
484        impl crate::dac::Instance for peripherals::$inst {}
485    };
486);
487
488macro_rules! impl_dac_pin {
489    ($inst:ident, $pin:ident, $ch:expr) => {
490        impl crate::dac::DacPin<peripherals::$inst, $ch> for crate::peripherals::$pin {}
491    };
492}