Skip to content

DAC Improvements - Dual DAC support and DMA #213

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ stm32g4 = { version = "0.16.0", features = ["atomics"] }
paste = "1.0"
fugit = "0.3.7"
stm32-usbd = { version = "0.7.0", optional = true }
fixed = { version = "1.28.0", optional = true }
fixed = { version = "1.28.0" }
embedded-io = "0.6"

[dependencies.cortex-m]
Expand Down Expand Up @@ -106,7 +106,7 @@ defmt = [
"embedded-io/defmt-03",
"embedded-test/defmt",
]
cordic = ["dep:fixed"]
cordic = []
adc3 = []
adc4 = []
adc5 = []
Expand Down
62 changes: 62 additions & 0 deletions examples/dual-dac.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//! Simple Dual DAC example for STM32G4 microcontrollers.
//!
//! This simple example configures DAC1 in DualDac mode and outputs a wrapping
//! ramp on PA4, and its inverse on PA5.
//!
//! This example highlights using the [`hal::dac::format::SampleQ15`] format for
//! native Q1.15 fixed point conversion by the DAC hardware when moving from holding register
//! to output register.
//!
//! Setting a channel to 0.0 will output a DC voltage of Vref/2, negative
//! values will be in the range [0.0..Vref/2], and positive values will be [Vref/2..Vref].
//!

#![deny(unsafe_code)]
#![no_main]
#![no_std]

use fixed::types::I1F15;
use hal::dac::dual::DualDacExt;
use hal::delay::SYSTDelayExt;
use hal::gpio::GpioExt;
use hal::rcc::RccExt;
use stm32g4xx_hal as hal;
mod utils;
extern crate cortex_m_rt as rt;

use hal::stm32;
use rt::entry;

#[entry]
fn main() -> ! {
let dp = stm32::Peripherals::take().expect("cannot take peripherals");
let cp = cortex_m::Peripherals::take().expect("cannot take core peripherals");

let mut rcc = dp.RCC.constrain();
let mut delay = cp.SYST.delay(&rcc.clocks);

let gpioa = dp.GPIOA.split(&mut rcc);

// Get a DualDac instance from DAC1 with channel outputs on PA4 and PA5
let dac = dp.DAC1.into_dual::<hal::dac::format::SampleQ15, _>(
(gpioa.pa4, gpioa.pa5),
&mut rcc,
&mut delay,
);

// Enable the DAC
let mut dac = dac.enable();

// Create an initial value that we'll sweep using the minimum fixed point value (-1.0)
let mut value = I1F15::MIN;

loop {
// Output value on channel 1, and inverted value on channel 2
// This uses the DAC's dual channel hold register, and native signed format mode
// to write both channels simultaneously with a single register write operation.
dac.set_channels(value, -value);

// Increment and wrap the value by the minimum fixed point type increment delta
value = value.wrapping_add(I1F15::DELTA);
}
}
89 changes: 88 additions & 1 deletion src/dac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,27 @@ use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ops::Deref;

use crate::dac::trigger::DacTriggerSource;
use crate::dma::mux::DmaMuxResources;
use crate::dma::traits::TargetAddress;
use crate::dma::MemoryToPeripheral;
use crate::gpio::{Analog, PA4, PA5, PA6};
use crate::pac;
use crate::rcc::{self, *};
use crate::stm32::dac1::mcr::HFSEL;
use embedded_hal::delay::DelayNs;

pub mod dual;
pub mod format;
pub mod trigger;

/// DAC Channel identifier
#[repr(u8)]
pub enum DacChannel {
Ch1 = 0,
Ch2 = 1,
}

pub trait DacOut<V> {
fn get_value(&mut self) -> V;
fn set_value(&mut self, val: V);
Expand Down Expand Up @@ -137,6 +152,7 @@ impl SawtoothConfig {

/// Enabled DAC (type state)
pub struct Enabled;
pub struct EnabledDma;
// / Enabled DAC without output buffer (type state)
//pub struct EnabledUnbuffered;
/// Enabled DAC wave generator for triangle or noise wave form (type state)
Expand Down Expand Up @@ -282,6 +298,43 @@ impl<DAC: Instance, const CH: u8, const MODE_BITS: u8> DacCh<DAC, CH, MODE_BITS,
DacCh::new()
}

/// Enable trigger for the channel using the trigger source provided as a generic type parameter.
///
/// This will cause the DAC to copy the hold register to the output register
/// when the trigger is raised by a timer signal or external interrupt,
/// and issue a new DMA request if DMA is enabled.
#[inline(always)]
pub fn enable_trigger<Source>(&mut self)
where
Source: DacTriggerSource<DAC>,
{
// Set the TSELx bits to the trigger signal identifier from the DacTriggerSource impl
let dac = unsafe { &(*DAC::ptr()) };
if CH == DacChannel::Ch1 as u8 {
unsafe { dac.cr().modify(|_, w| w.tsel1().bits(Source::SIGNAL)) };
}
if CH == DacChannel::Ch2 as u8 {
unsafe { dac.cr().modify(|_, w| w.tsel2().bits(Source::SIGNAL)) };
}

// Enable the TENx flag in DAC CR
dac.cr().modify(|_, w| w.ten(CH).set_bit());
}

pub fn enable_dma(self, rcc: &mut Rcc) -> DacCh<DAC, CH, MODE_BITS, EnabledDma> {
let dac = unsafe { &(*DAC::ptr()) };

dac.mcr()
.modify(|_, w| unsafe { w.hfsel().variant(hfsel(rcc)).mode(CH).bits(MODE_BITS) });

dac.cr()
.modify(|_, w| w.dmaen(CH).set_bit().en(CH).set_bit());

dac.dhr12r(CH as usize).write(|w| unsafe { w.bits(0) });

DacCh::new()
}

pub fn enable_generator(
self,
config: GeneratorConfig,
Expand Down Expand Up @@ -450,7 +503,16 @@ impl<DAC: Instance, const CH: u8, const MODE_BITS: u8>
}
}

pub trait DacExt: Sized {
/// DMA state implementation
impl<DAC: Instance, const CH: u8, const MODE_BITS: u8> DacCh<DAC, CH, MODE_BITS, EnabledDma> {
pub fn start(&mut self, val: u16) {
let dac = unsafe { &(*DAC::ptr()) };
dac.dhr12r(CH as usize)
.write(|w| unsafe { w.bits(val as u32) });
}
}

pub trait DacExt: Instance + Sized {
fn constrain<PINS>(self, pins: PINS, rcc: &mut Rcc) -> PINS::Output
where
PINS: Pins<Self>;
Expand Down Expand Up @@ -478,3 +540,28 @@ macro_rules! impl_dac_ext {
}

impl_dac_ext!(pac::DAC1, pac::DAC2, pac::DAC3, pac::DAC4,);

macro_rules! impl_dac_dma {
($($DAC:ty, $channel:expr, $dmamux:ident)+) => {$(
unsafe impl<const MODE_BITS: u8, ED> TargetAddress<MemoryToPeripheral>
for DacCh<$DAC, $channel, MODE_BITS, ED>
where $DAC: Instance
{
type MemSize = u32;
const REQUEST_LINE: Option<u8> = Some(DmaMuxResources::$dmamux as u8);

fn address(&self) -> u32 {
let dac = unsafe { &(*<$DAC>::ptr()) };
dac.dhr12r($channel as usize) as *const _ as u32
}
}
)+};
}

impl_dac_dma!(pac::DAC1, 0, DAC1_CH1);
impl_dac_dma!(pac::DAC1, 1, DAC1_CH2);
impl_dac_dma!(pac::DAC2, 0, DAC2_CH1);
impl_dac_dma!(pac::DAC3, 0, DAC3_CH1);
impl_dac_dma!(pac::DAC3, 1, DAC3_CH2);
impl_dac_dma!(pac::DAC4, 0, DAC4_CH1);
impl_dac_dma!(pac::DAC4, 1, DAC4_CH2);
Loading
Loading