Merge pull request #1705 from JuliDi/stm32h7-dac-dma-example

[STM32] H7 DAC DMA example and feature documentation
This commit is contained in:
Dario Nieuwenhuis 2023-07-28 17:07:05 +00:00 committed by GitHub
commit e97b14c068
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 188 additions and 118 deletions

View file

@ -67,6 +67,7 @@ cfg-if = "1.0.0"
embedded-io = { version = "0.4.0", features = ["async"], optional = true } embedded-io = { version = "0.4.0", features = ["async"], optional = true }
chrono = { version = "^0.4", default-features = false, optional = true} chrono = { version = "^0.4", default-features = false, optional = true}
bit_field = "0.10.2" bit_field = "0.10.2"
document-features = "0.2.7"
[dev-dependencies] [dev-dependencies]
critical-section = { version = "1.1", features = ["std"] } critical-section = { version = "1.1", features = ["std"] }
@ -78,40 +79,63 @@ stm32-metapac = { version = "13", default-features = false, features = ["metadat
[features] [features]
default = ["rt"] default = ["rt"]
## Enable `stm32-metapac`'s `rt` feature
rt = ["stm32-metapac/rt"] rt = ["stm32-metapac/rt"]
## Use [`defmt`](https://docs.rs/defmt/latest/defmt/) for logging
defmt = ["dep:defmt", "bxcan/unstable-defmt", "embassy-sync/defmt", "embassy-embedded-hal/defmt", "embassy-hal-internal/defmt", "embedded-io?/defmt", "embassy-usb-driver?/defmt", "embassy-net-driver/defmt"] defmt = ["dep:defmt", "bxcan/unstable-defmt", "embassy-sync/defmt", "embassy-embedded-hal/defmt", "embassy-hal-internal/defmt", "embedded-io?/defmt", "embassy-usb-driver?/defmt", "embassy-net-driver/defmt"]
memory-x = ["stm32-metapac/memory-x"]
exti = [] exti = []
# Enables additional driver features that depend on embassy-time ## Automatically generate `memory.x` file using [`stm32-metapac`](https://docs.rs/stm32-metapac/)
memory-x = ["stm32-metapac/memory-x"]
## Enable nightly-only features
nightly = ["embedded-hal-1", "embedded-hal-async", "embedded-storage-async", "dep:embedded-io", "dep:embassy-usb-driver", "embassy-embedded-hal/nightly"]
## Re-export stm32-metapac at `embassy_stm32::pac`.
## This is unstable because semver-minor (non-breaking) releases of embassy-stm32 may major-bump (breaking) the stm32-metapac version.
## If this is an issue for you, you're encouraged to directly depend on a fixed version of the PAC.
## There are no plans to make this stable.
unstable-pac = []
## Implement embedded-hal 1.0 alpha traits.
## Implement embedded-hal-async traits if `nightly` is set as well.
unstable-traits = ["embedded-hal-1", "dep:embedded-hal-nb"]
#! ## Time
## Enables additional driver features that depend on embassy-time
time = ["dep:embassy-time"] time = ["dep:embassy-time"]
# Features starting with `_` are for internal use only. They're not intended # Features starting with `_` are for internal use only. They're not intended
# to be enabled by other crates, and are not covered by semver guarantees. # to be enabled by other crates, and are not covered by semver guarantees.
_time-driver = ["time"] _time-driver = ["time"]
## Use any time driver
time-driver-any = ["_time-driver"] time-driver-any = ["_time-driver"]
## Use TIM2 as time driver
time-driver-tim2 = ["_time-driver"] time-driver-tim2 = ["_time-driver"]
## Use TIM3 as time driver
time-driver-tim3 = ["_time-driver"] time-driver-tim3 = ["_time-driver"]
## Use TIM4 as time driver
time-driver-tim4 = ["_time-driver"] time-driver-tim4 = ["_time-driver"]
## Use TIM5 as time driver
time-driver-tim5 = ["_time-driver"] time-driver-tim5 = ["_time-driver"]
## Use TIM12 as time driver
time-driver-tim12 = ["_time-driver"] time-driver-tim12 = ["_time-driver"]
## Use TIM15 as time driver
time-driver-tim15 = ["_time-driver"] time-driver-tim15 = ["_time-driver"]
# Enable nightly-only features
nightly = ["embedded-hal-1", "embedded-hal-async", "embedded-storage-async", "dep:embedded-io", "dep:embassy-usb-driver", "embassy-embedded-hal/nightly"]
# Reexport stm32-metapac at `embassy_stm32::pac`. #! ## Chip-selection features
# This is unstable because semver-minor (non-breaking) releases of embassy-stm32 may major-bump (breaking) the stm32-metapac version. #! Select your chip by specifying the model as a feature, e.g. `stm32c011d6`.
# If this is an issue for you, you're encouraged to directly depend on a fixed version of the PAC. #! Check the `Cargo.toml` for the latest list of supported chips.
# There are no plans to make this stable. #!
unstable-pac = [] #! **Important:** Do not forget to adapt the target chip in your toolchain,
#! e.g. in `.cargo/config.toml`.
# Implement embedded-hal 1.0 alpha traits.
# Implement embedded-hal-async traits if `nightly` is set as well.
unstable-traits = ["embedded-hal-1", "dep:embedded-hal-nb"]
# Chip-selection features
stm32c011d6 = [ "stm32-metapac/stm32c011d6" ] stm32c011d6 = [ "stm32-metapac/stm32c011d6" ]
stm32c011f4 = [ "stm32-metapac/stm32c011f4" ] stm32c011f4 = [ "stm32-metapac/stm32c011f4" ]
stm32c011f6 = [ "stm32-metapac/stm32c011f6" ] stm32c011f6 = [ "stm32-metapac/stm32c011f6" ]
@ -1445,4 +1469,4 @@ stm32wle5cb = [ "stm32-metapac/stm32wle5cb" ]
stm32wle5cc = [ "stm32-metapac/stm32wle5cc" ] stm32wle5cc = [ "stm32-metapac/stm32wle5cc" ]
stm32wle5j8 = [ "stm32-metapac/stm32wle5j8" ] stm32wle5j8 = [ "stm32-metapac/stm32wle5j8" ]
stm32wle5jb = [ "stm32-metapac/stm32wle5jb" ] stm32wle5jb = [ "stm32-metapac/stm32wle5jb" ]
stm32wle5jc = [ "stm32-metapac/stm32wle5jc" ] stm32wle5jc = [ "stm32-metapac/stm32wle5jc" ]

View file

@ -1,6 +1,9 @@
#![cfg_attr(not(test), no_std)] #![cfg_attr(not(test), no_std)]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))] #![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))]
//! ## Feature flags
#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
// This must go FIRST so that all the other modules see its macros. // This must go FIRST so that all the other modules see its macros.
pub mod fmt; pub mod fmt;
include!(concat!(env!("OUT_DIR"), "/_macros.rs")); include!(concat!(env!("OUT_DIR"), "/_macros.rs"));

View file

@ -6,7 +6,7 @@ license = "MIT OR Apache-2.0"
[dependencies] [dependencies]
# Change stm32f767zi to your chip name, if necessary. # Change stm32f767zi to your chip name, if necessary.
embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32f767zi", "unstable-pac", "time-driver-any", "exti"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32f767zi", "memory-x", "unstable-pac", "time-driver-any", "exti"] }
embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] }
embassy-executor = { version = "0.2.0", path = "../../embassy-executor", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } embassy-executor = { version = "0.2.0", path = "../../embassy-executor", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] }
embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }

View file

@ -1,43 +1,5 @@
//! adapted from https://github.com/stm32-rs/stm32f7xx-hal/blob/master/build.rs fn main() {
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use std::{env, io};
#[derive(Debug)]
enum Error {
Env(env::VarError),
Io(io::Error),
}
impl From<env::VarError> for Error {
fn from(error: env::VarError) -> Self {
Self::Env(error)
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
fn main() -> Result<(), Error> {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=memory.x");
let out_dir = env::var("OUT_DIR")?;
let out_dir = PathBuf::from(out_dir);
let memory_x = include_bytes!("memory.x").as_ref();
File::create(out_dir.join("memory.x"))?.write_all(memory_x)?;
// Tell Cargo where to find the file.
println!("cargo:rustc-link-search={}", out_dir.display());
println!("cargo:rustc-link-arg-bins=--nmagic"); println!("cargo:rustc-link-arg-bins=--nmagic");
println!("cargo:rustc-link-arg-bins=-Tlink.x"); println!("cargo:rustc-link-arg-bins=-Tlink.x");
println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
Ok(())
} }

View file

@ -1,12 +0,0 @@
/* For STM32F765,767,768,769,777,778,779 devices */
MEMORY
{
/* NOTE K = KiBi = 1024 bytes */
FLASH : ORIGIN = 0x08000000, LENGTH = 2M
RAM : ORIGIN = 0x20000000, LENGTH = 368K + 16K
}
/* This is where the call stack will be allocated. */
/* The stack is of the full descending type. */
/* NOTE Do NOT modify `_stack_start` unless you know what you are doing */
_stack_start = ORIGIN(RAM) + LENGTH(RAM);

View file

@ -6,7 +6,7 @@ license = "MIT OR Apache-2.0"
[dependencies] [dependencies]
# Change stm32h563zi to your chip name, if necessary. # Change stm32h563zi to your chip name, if necessary.
embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32h563zi", "time-driver-any", "exti", "unstable-pac", "unstable-traits"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32h563zi", "memory-x", "time-driver-any", "exti", "unstable-pac", "unstable-traits"] }
embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] }
embassy-executor = { version = "0.2.0", path = "../../embassy-executor", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } embassy-executor = { version = "0.2.0", path = "../../embassy-executor", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] }
embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "unstable-traits", "tick-hz-32_768"] } embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "unstable-traits", "tick-hz-32_768"] }

View file

@ -1,5 +0,0 @@
MEMORY
{
FLASH : ORIGIN = 0x08000000, LENGTH = 0x200000
RAM : ORIGIN = 0x20000000, LENGTH = 0x50000
}

View file

@ -1,5 +1,5 @@
[target.thumbv7em-none-eabihf] [target.thumbv7em-none-eabihf]
runner = 'probe-rs run --chip STM32H743ZITx' runner = 'probe-rs run --chip STM32H7A3ZITxQ'
[build] [build]
target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU) target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU)

View file

@ -6,7 +6,7 @@ license = "MIT OR Apache-2.0"
[dependencies] [dependencies]
# Change stm32h743bi to your chip name, if necessary. # Change stm32h743bi to your chip name, if necessary.
embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32h743bi", "time-driver-any", "exti", "unstable-pac", "unstable-traits"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32h743bi", "time-driver-any", "exti", "memory-x", "unstable-pac", "unstable-traits"] }
embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] }
embassy-executor = { version = "0.2.0", path = "../../embassy-executor", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } embassy-executor = { version = "0.2.0", path = "../../embassy-executor", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] }
embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "unstable-traits", "tick-hz-32_768"] } embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "unstable-traits", "tick-hz-32_768"] }

View file

@ -1,5 +0,0 @@
MEMORY
{
FLASH : ORIGIN = 0x8000000, LENGTH = 1024K
RAM : ORIGIN = 0x24000000, LENGTH = 384K
}

View file

@ -0,0 +1,140 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use defmt::*;
use embassy_executor::Spawner;
use embassy_stm32::dac::{DacChannel, ValueArray};
use embassy_stm32::pac::timer::vals::{Mms, Opm};
use embassy_stm32::peripherals::{TIM6, TIM7};
use embassy_stm32::rcc::low_level::RccPeripheral;
use embassy_stm32::time::{mhz, Hertz};
use embassy_stm32::timer::low_level::Basic16bitInstance;
use micromath::F32Ext;
use {defmt_rtt as _, panic_probe as _};
pub type Dac1Type =
embassy_stm32::dac::DacCh1<'static, embassy_stm32::peripherals::DAC1, embassy_stm32::peripherals::DMA1_CH3>;
pub type Dac2Type =
embassy_stm32::dac::DacCh2<'static, embassy_stm32::peripherals::DAC1, embassy_stm32::peripherals::DMA1_CH4>;
#[embassy_executor::main]
async fn main(spawner: Spawner) {
let mut config = embassy_stm32::Config::default();
config.rcc.sys_ck = Some(mhz(400));
config.rcc.hclk = Some(mhz(100));
config.rcc.pll1.q_ck = Some(mhz(100));
// Initialize the board and obtain a Peripherals instance
let p: embassy_stm32::Peripherals = embassy_stm32::init(config);
// Obtain two independent channels (p.DAC1 can only be consumed once, though!)
let (dac_ch1, dac_ch2) = embassy_stm32::dac::Dac::new(p.DAC1, p.DMA1_CH3, p.DMA1_CH4, p.PA4, p.PA5).split();
spawner.spawn(dac_task1(dac_ch1)).ok();
spawner.spawn(dac_task2(dac_ch2)).ok();
}
#[embassy_executor::task]
async fn dac_task1(mut dac: Dac1Type) {
let data: &[u8; 256] = &calculate_array::<256>();
info!("TIM6 frequency is {}", TIM6::frequency());
const FREQUENCY: Hertz = Hertz::hz(200);
// Compute the reload value such that we obtain the FREQUENCY for the sine
let reload: u32 = (TIM6::frequency().0 / FREQUENCY.0) / data.len() as u32;
// Depends on your clock and on the specific chip used, you may need higher or lower values here
if reload < 10 {
error!("Reload value {} below threshold!", reload);
}
dac.select_trigger(embassy_stm32::dac::Ch1Trigger::Tim6).unwrap();
dac.enable_channel().unwrap();
TIM6::enable();
TIM6::regs().arr().modify(|w| w.set_arr(reload as u16 - 1));
TIM6::regs().cr2().modify(|w| w.set_mms(Mms::UPDATE));
TIM6::regs().cr1().modify(|w| {
w.set_opm(Opm::DISABLED);
w.set_cen(true);
});
debug!(
"TIM6 Frequency {}, Target Frequency {}, Reload {}, Reload as u16 {}, Samples {}",
TIM6::frequency(),
FREQUENCY,
reload,
reload as u16,
data.len()
);
// Loop technically not necessary if DMA circular mode is enabled
loop {
info!("Loop DAC1");
if let Err(e) = dac.write(ValueArray::Bit8(data), true).await {
error!("Could not write to dac: {}", e);
}
}
}
#[embassy_executor::task]
async fn dac_task2(mut dac: Dac2Type) {
let data: &[u8; 256] = &calculate_array::<256>();
info!("TIM7 frequency is {}", TIM7::frequency());
const FREQUENCY: Hertz = Hertz::hz(600);
let reload: u32 = (TIM7::frequency().0 / FREQUENCY.0) / data.len() as u32;
if reload < 10 {
error!("Reload value {} below threshold!", reload);
}
TIM7::enable();
TIM7::regs().arr().modify(|w| w.set_arr(reload as u16 - 1));
TIM7::regs().cr2().modify(|w| w.set_mms(Mms::UPDATE));
TIM7::regs().cr1().modify(|w| {
w.set_opm(Opm::DISABLED);
w.set_cen(true);
});
dac.select_trigger(embassy_stm32::dac::Ch2Trigger::Tim7).unwrap();
debug!(
"TIM7 Frequency {}, Target Frequency {}, Reload {}, Reload as u16 {}, Samples {}",
TIM7::frequency(),
FREQUENCY,
reload,
reload as u16,
data.len()
);
if let Err(e) = dac.write(ValueArray::Bit8(data), true).await {
error!("Could not write to dac: {}", e);
}
}
fn to_sine_wave(v: u8) -> u8 {
if v >= 128 {
// top half
let r = 3.14 * ((v - 128) as f32 / 128.0);
(r.sin() * 128.0 + 127.0) as u8
} else {
// bottom half
let r = 3.14 + 3.14 * (v as f32 / 128.0);
(r.sin() * 128.0 + 127.0) as u8
}
}
fn calculate_array<const N: usize>() -> [u8; N] {
let mut res = [0; N];
let mut i = 0;
while i < N {
res[i] = to_sine_wave(i as u8);
i += 1;
}
res
}

View file

@ -6,7 +6,7 @@ license = "MIT OR Apache-2.0"
[dependencies] [dependencies]
# Change stm32l4s5vi to your chip name, if necessary. # Change stm32l4s5vi to your chip name, if necessary.
embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "unstable-pac", "stm32l4s5vi", "time-driver-any", "exti", "unstable-traits", "chrono"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "unstable-pac", "stm32l4s5vi", "memory-x", "time-driver-any", "exti", "unstable-traits", "chrono"] }
embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] }
embassy-executor = { version = "0.2.0", path = "../../embassy-executor", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } embassy-executor = { version = "0.2.0", path = "../../embassy-executor", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] }
embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }

View file

@ -1,34 +1,4 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() { fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
// By default, Cargo will re-run a build script whenever
// any file in the project changes. By specifying `memory.x`
// here, we ensure the build script is only re-run when
// `memory.x` is changed.
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=--nmagic"); println!("cargo:rustc-link-arg-bins=--nmagic");
println!("cargo:rustc-link-arg-bins=-Tlink.x"); println!("cargo:rustc-link-arg-bins=-Tlink.x");
println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); println!("cargo:rustc-link-arg-bins=-Tdefmt.x");

View file

@ -1,7 +0,0 @@
MEMORY
{
/* NOTE 1 K = 1 KiBi = 1024 bytes */
/* These values correspond to the STM32L4S5 */
FLASH : ORIGIN = 0x08000000, LENGTH = 1024K
RAM : ORIGIN = 0x20000000, LENGTH = 128K
}