aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2024-12-31 11:33:35 +0100
committerGitHub <[email protected]>2024-12-31 11:33:35 +0100
commit18773c377a1eca726f928426249c899afddb1877 (patch)
tree323e26f58f860cdcc3dd2a1eb35da1067b6bd76b
parentdc9a83b9b3110e601a268d5135fe9d89a046c9de (diff)
parent41c8bf867bc185507e1b9eadbf5645e57004cd4f (diff)
Merge pull request #3688 from klownfish/u5_adc
STM32U5: Add ADC drivers
-rw-r--r--embassy-stm32/Cargo.toml4
-rw-r--r--embassy-stm32/build.rs9
-rw-r--r--embassy-stm32/src/adc/mod.rs70
-rw-r--r--embassy-stm32/src/adc/u5_adc4.rs479
-rw-r--r--embassy-stm32/src/adc/v4.rs17
-rw-r--r--embassy-stm32/src/lib.rs20
-rw-r--r--examples/stm32u5/src/bin/adc.rs109
7 files changed, 686 insertions, 22 deletions
diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml
index ffd9a67e7..f35271016 100644
--- a/embassy-stm32/Cargo.toml
+++ b/embassy-stm32/Cargo.toml
@@ -73,7 +73,7 @@ rand_core = "0.6.3"
73sdio-host = "0.5.0" 73sdio-host = "0.5.0"
74critical-section = "1.1" 74critical-section = "1.1"
75#stm32-metapac = { version = "15" } 75#stm32-metapac = { version = "15" }
76stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-ddb0e7abab14bf3e1399875767b8834442382988" } 76stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-392e41259ffc5ffbfd79169ee80451114fb367fe" }
77 77
78vcell = "0.1.3" 78vcell = "0.1.3"
79nb = "1.0.0" 79nb = "1.0.0"
@@ -102,7 +102,7 @@ proc-macro2 = "1.0.36"
102quote = "1.0.15" 102quote = "1.0.15"
103 103
104#stm32-metapac = { version = "15", default-features = false, features = ["metadata"]} 104#stm32-metapac = { version = "15", default-features = false, features = ["metadata"]}
105stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-ddb0e7abab14bf3e1399875767b8834442382988", default-features = false, features = ["metadata"] } 105stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-392e41259ffc5ffbfd79169ee80451114fb367fe", default-features = false, features = ["metadata"] }
106 106
107[features] 107[features]
108default = ["rt"] 108default = ["rt"]
diff --git a/embassy-stm32/build.rs b/embassy-stm32/build.rs
index f92d8b8ba..e293cf965 100644
--- a/embassy-stm32/build.rs
+++ b/embassy-stm32/build.rs
@@ -1238,13 +1238,12 @@ fn main() {
1238 // ======== 1238 // ========
1239 // Generate dma_trait_impl! 1239 // Generate dma_trait_impl!
1240 1240
1241 let signals: HashMap<_, _> = [ 1241 let mut signals: HashMap<_, _> = [
1242 // (kind, signal) => trait 1242 // (kind, signal) => trait
1243 (("adc", "ADC"), quote!(crate::adc::RxDma)), 1243 (("adc", "ADC"), quote!(crate::adc::RxDma)),
1244 (("adc", "ADC1"), quote!(crate::adc::RxDma)), 1244 (("adc", "ADC1"), quote!(crate::adc::RxDma)),
1245 (("adc", "ADC2"), quote!(crate::adc::RxDma)), 1245 (("adc", "ADC2"), quote!(crate::adc::RxDma)),
1246 (("adc", "ADC3"), quote!(crate::adc::RxDma)), 1246 (("adc", "ADC3"), quote!(crate::adc::RxDma)),
1247 (("adc", "ADC4"), quote!(crate::adc::RxDma)),
1248 (("ucpd", "RX"), quote!(crate::ucpd::RxDma)), 1247 (("ucpd", "RX"), quote!(crate::ucpd::RxDma)),
1249 (("ucpd", "TX"), quote!(crate::ucpd::TxDma)), 1248 (("ucpd", "TX"), quote!(crate::ucpd::TxDma)),
1250 (("usart", "RX"), quote!(crate::usart::RxDma)), 1249 (("usart", "RX"), quote!(crate::usart::RxDma)),
@@ -1279,6 +1278,12 @@ fn main() {
1279 ] 1278 ]
1280 .into(); 1279 .into();
1281 1280
1281 if chip_name.starts_with("stm32u5") {
1282 signals.insert(("adc", "ADC4"), quote!(crate::adc::RxDma4));
1283 } else {
1284 signals.insert(("adc", "ADC4"), quote!(crate::adc::RxDma));
1285 }
1286
1282 for p in METADATA.peripherals { 1287 for p in METADATA.peripherals {
1283 if let Some(regs) = &p.registers { 1288 if let Some(regs) = &p.registers {
1284 // FIXME: stm32u5a crash on Cordic driver 1289 // FIXME: stm32u5a crash on Cordic driver
diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs
index 4ab82c1d9..36898b8f9 100644
--- a/embassy-stm32/src/adc/mod.rs
+++ b/embassy-stm32/src/adc/mod.rs
@@ -4,7 +4,7 @@
4#![allow(missing_docs)] // TODO 4#![allow(missing_docs)] // TODO
5#![cfg_attr(adc_f3_v2, allow(unused))] 5#![cfg_attr(adc_f3_v2, allow(unused))]
6 6
7#[cfg(not(any(adc_f3_v2, adc_u5)))] 7#[cfg(not(any(adc_f3_v2)))]
8#[cfg_attr(adc_f1, path = "f1.rs")] 8#[cfg_attr(adc_f1, path = "f1.rs")]
9#[cfg_attr(adc_f3, path = "f3.rs")] 9#[cfg_attr(adc_f3, path = "f3.rs")]
10#[cfg_attr(adc_f3_v1_1, path = "f3_v1_1.rs")] 10#[cfg_attr(adc_f3_v1_1, path = "f3_v1_1.rs")]
@@ -12,33 +12,37 @@
12#[cfg_attr(adc_l0, path = "v1.rs")] 12#[cfg_attr(adc_l0, path = "v1.rs")]
13#[cfg_attr(adc_v2, path = "v2.rs")] 13#[cfg_attr(adc_v2, path = "v2.rs")]
14#[cfg_attr(any(adc_v3, adc_g0, adc_h5, adc_u0), path = "v3.rs")] 14#[cfg_attr(any(adc_v3, adc_g0, adc_h5, adc_u0), path = "v3.rs")]
15#[cfg_attr(adc_v4, path = "v4.rs")] 15#[cfg_attr(any(adc_v4, adc_u5), path = "v4.rs")]
16#[cfg_attr(adc_g4, path = "g4.rs")] 16#[cfg_attr(adc_g4, path = "g4.rs")]
17mod _version; 17mod _version;
18 18
19use core::marker::PhantomData; 19use core::marker::PhantomData;
20 20
21#[allow(unused)] 21#[allow(unused)]
22#[cfg(not(any(adc_f3_v2, adc_u5)))] 22#[cfg(not(any(adc_f3_v2)))]
23pub use _version::*; 23pub use _version::*;
24#[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] 24#[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))]
25use embassy_sync::waitqueue::AtomicWaker; 25use embassy_sync::waitqueue::AtomicWaker;
26 26
27#[cfg(not(any(adc_u5)))] 27#[cfg(adc_u5)]
28#[path = "u5_adc4.rs"]
29pub mod adc4;
30
28pub use crate::pac::adc::vals; 31pub use crate::pac::adc::vals;
29#[cfg(not(any(adc_f1, adc_f3_v2, adc_u5)))] 32#[cfg(not(any(adc_f1, adc_f3_v2)))]
30pub use crate::pac::adc::vals::Res as Resolution; 33pub use crate::pac::adc::vals::Res as Resolution;
31#[cfg(not(any(adc_u5)))]
32pub use crate::pac::adc::vals::SampleTime; 34pub use crate::pac::adc::vals::SampleTime;
33use crate::peripherals; 35use crate::peripherals;
34 36
35dma_trait!(RxDma, Instance); 37dma_trait!(RxDma, Instance);
38#[cfg(adc_u5)]
39dma_trait!(RxDma4, adc4::Instance);
36 40
37/// Analog to Digital driver. 41/// Analog to Digital driver.
38pub struct Adc<'d, T: Instance> { 42pub struct Adc<'d, T: Instance> {
39 #[allow(unused)] 43 #[allow(unused)]
40 adc: crate::PeripheralRef<'d, T>, 44 adc: crate::PeripheralRef<'d, T>,
41 #[cfg(not(any(adc_f3_v2, adc_f3_v1_1, adc_u5)))] 45 #[cfg(not(any(adc_f3_v2, adc_f3_v1_1)))]
42 sample_time: SampleTime, 46 sample_time: SampleTime,
43} 47}
44 48
@@ -59,7 +63,7 @@ impl State {
59trait SealedInstance { 63trait SealedInstance {
60 #[allow(unused)] 64 #[allow(unused)]
61 fn regs() -> crate::pac::adc::Adc; 65 fn regs() -> crate::pac::adc::Adc;
62 #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0, adc_u5)))] 66 #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0)))]
63 #[allow(unused)] 67 #[allow(unused)]
64 fn common_regs() -> crate::pac::adccommon::AdcCommon; 68 fn common_regs() -> crate::pac::adccommon::AdcCommon;
65 #[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] 69 #[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))]
@@ -67,7 +71,7 @@ trait SealedInstance {
67} 71}
68 72
69pub(crate) trait SealedAdcChannel<T> { 73pub(crate) trait SealedAdcChannel<T> {
70 #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] 74 #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4, adc_u5))]
71 fn setup(&mut self) {} 75 fn setup(&mut self) {}
72 76
73 #[allow(unused)] 77 #[allow(unused)]
@@ -101,7 +105,8 @@ pub(crate) fn blocking_delay_us(us: u32) {
101 adc_f3_v1_1, 105 adc_f3_v1_1,
102 adc_g0, 106 adc_g0,
103 adc_u0, 107 adc_u0,
104 adc_h5 108 adc_h5,
109 adc_u5
105)))] 110)))]
106#[allow(private_bounds)] 111#[allow(private_bounds)]
107pub trait Instance: SealedInstance + crate::Peripheral<P = Self> { 112pub trait Instance: SealedInstance + crate::Peripheral<P = Self> {
@@ -120,7 +125,8 @@ pub trait Instance: SealedInstance + crate::Peripheral<P = Self> {
120 adc_f3_v1_1, 125 adc_f3_v1_1,
121 adc_g0, 126 adc_g0,
122 adc_u0, 127 adc_u0,
123 adc_h5 128 adc_h5,
129 adc_u5
124))] 130))]
125#[allow(private_bounds)] 131#[allow(private_bounds)]
126pub trait Instance: SealedInstance + crate::Peripheral<P = Self> + crate::rcc::RccPeripheral { 132pub trait Instance: SealedInstance + crate::Peripheral<P = Self> + crate::rcc::RccPeripheral {
@@ -132,7 +138,7 @@ pub trait Instance: SealedInstance + crate::Peripheral<P = Self> + crate::rcc::R
132pub trait AdcChannel<T>: SealedAdcChannel<T> + Sized { 138pub trait AdcChannel<T>: SealedAdcChannel<T> + Sized {
133 #[allow(unused_mut)] 139 #[allow(unused_mut)]
134 fn degrade_adc(mut self) -> AnyAdcChannel<T> { 140 fn degrade_adc(mut self) -> AnyAdcChannel<T> {
135 #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] 141 #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4, adc_u5))]
136 self.setup(); 142 self.setup();
137 143
138 AnyAdcChannel { 144 AnyAdcChannel {
@@ -158,6 +164,38 @@ impl<T: Instance> SealedAdcChannel<T> for AnyAdcChannel<T> {
158 } 164 }
159} 165}
160 166
167#[cfg(adc_u5)]
168foreach_adc!(
169 (ADC4, $common_inst:ident, $clock:ident) => {
170 impl crate::adc::adc4::SealedInstance for peripherals::ADC4 {
171 fn regs() -> crate::pac::adc::Adc4 {
172 crate::pac::ADC4
173 }
174 }
175
176 impl crate::adc::adc4::Instance for peripherals::ADC4 {
177 type Interrupt = crate::_generated::peripheral_interrupts::ADC4::GLOBAL;
178 }
179 };
180
181 ($inst:ident, $common_inst:ident, $clock:ident) => {
182 impl crate::adc::SealedInstance for peripherals::$inst {
183 fn regs() -> crate::pac::adc::Adc {
184 crate::pac::$inst
185 }
186
187 fn common_regs() -> crate::pac::adccommon::AdcCommon {
188 return crate::pac::$common_inst
189 }
190 }
191
192 impl crate::adc::Instance for peripherals::$inst {
193 type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
194 }
195 };
196);
197
198#[cfg(not(adc_u5))]
161foreach_adc!( 199foreach_adc!(
162 ($inst:ident, $common_inst:ident, $clock:ident) => { 200 ($inst:ident, $common_inst:ident, $clock:ident) => {
163 impl crate::adc::SealedInstance for peripherals::$inst { 201 impl crate::adc::SealedInstance for peripherals::$inst {
@@ -165,7 +203,7 @@ foreach_adc!(
165 crate::pac::$inst 203 crate::pac::$inst
166 } 204 }
167 205
168 #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0, adc_u5)))] 206 #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0)))]
169 fn common_regs() -> crate::pac::adccommon::AdcCommon { 207 fn common_regs() -> crate::pac::adccommon::AdcCommon {
170 return crate::pac::$common_inst 208 return crate::pac::$common_inst
171 } 209 }
@@ -187,7 +225,7 @@ macro_rules! impl_adc_pin {
187 ($inst:ident, $pin:ident, $ch:expr) => { 225 ($inst:ident, $pin:ident, $ch:expr) => {
188 impl crate::adc::AdcChannel<peripherals::$inst> for crate::peripherals::$pin {} 226 impl crate::adc::AdcChannel<peripherals::$inst> for crate::peripherals::$pin {}
189 impl crate::adc::SealedAdcChannel<peripherals::$inst> for crate::peripherals::$pin { 227 impl crate::adc::SealedAdcChannel<peripherals::$inst> for crate::peripherals::$pin {
190 #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] 228 #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4, adc_u5))]
191 fn setup(&mut self) { 229 fn setup(&mut self) {
192 <Self as crate::gpio::SealedPin>::set_as_analog(self); 230 <Self as crate::gpio::SealedPin>::set_as_analog(self);
193 } 231 }
@@ -202,12 +240,12 @@ macro_rules! impl_adc_pin {
202/// Get the maximum reading value for this resolution. 240/// Get the maximum reading value for this resolution.
203/// 241///
204/// This is `2**n - 1`. 242/// This is `2**n - 1`.
205#[cfg(not(any(adc_f1, adc_f3_v2, adc_u5)))] 243#[cfg(not(any(adc_f1, adc_f3_v2)))]
206pub const fn resolution_to_max_count(res: Resolution) -> u32 { 244pub const fn resolution_to_max_count(res: Resolution) -> u32 {
207 match res { 245 match res {
208 #[cfg(adc_v4)] 246 #[cfg(adc_v4)]
209 Resolution::BITS16 => (1 << 16) - 1, 247 Resolution::BITS16 => (1 << 16) - 1,
210 #[cfg(adc_v4)] 248 #[cfg(any(adc_v4, adc_u5))]
211 Resolution::BITS14 => (1 << 14) - 1, 249 Resolution::BITS14 => (1 << 14) - 1,
212 #[cfg(adc_v4)] 250 #[cfg(adc_v4)]
213 Resolution::BITS14V => (1 << 14) - 1, 251 Resolution::BITS14V => (1 << 14) - 1,
diff --git a/embassy-stm32/src/adc/u5_adc4.rs b/embassy-stm32/src/adc/u5_adc4.rs
new file mode 100644
index 000000000..0635dad9b
--- /dev/null
+++ b/embassy-stm32/src/adc/u5_adc4.rs
@@ -0,0 +1,479 @@
1#[allow(unused)]
2use pac::adc::vals::{Adc4Dmacfg, Adc4Exten, Adc4OversamplingRatio};
3
4use super::{blocking_delay_us, AdcChannel, AnyAdcChannel, RxDma4, SealedAdcChannel};
5use crate::dma::Transfer;
6pub use crate::pac::adc::regs::Adc4Chselrmod0;
7pub use crate::pac::adc::vals::{Adc4Presc as Presc, Adc4Res as Resolution, Adc4SampleTime as SampleTime};
8use crate::time::Hertz;
9use crate::{pac, rcc, Peripheral};
10
11const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55);
12
13/// Default VREF voltage used for sample conversion to millivolts.
14pub const VREF_DEFAULT_MV: u32 = 3300;
15/// VREF voltage used for factory calibration of VREFINTCAL register.
16pub const VREF_CALIB_MV: u32 = 3300;
17
18const VREF_CHANNEL: u8 = 0;
19const VCORE_CHANNEL: u8 = 12;
20const TEMP_CHANNEL: u8 = 13;
21const VBAT_CHANNEL: u8 = 14;
22const DAC_CHANNEL: u8 = 21;
23
24// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs
25/// Internal voltage reference channel.
26pub struct VrefInt;
27impl<T: Instance> AdcChannel<T> for VrefInt {}
28impl<T: Instance> SealedAdcChannel<T> for VrefInt {
29 fn channel(&self) -> u8 {
30 VREF_CHANNEL
31 }
32}
33
34/// Internal temperature channel.
35pub struct Temperature;
36impl<T: Instance> AdcChannel<T> for Temperature {}
37impl<T: Instance> SealedAdcChannel<T> for Temperature {
38 fn channel(&self) -> u8 {
39 TEMP_CHANNEL
40 }
41}
42
43/// Internal battery voltage channel.
44pub struct Vbat;
45impl<T: Instance> AdcChannel<T> for Vbat {}
46impl<T: Instance> SealedAdcChannel<T> for Vbat {
47 fn channel(&self) -> u8 {
48 VBAT_CHANNEL
49 }
50}
51
52/// Internal DAC channel.
53pub struct Dac;
54impl<T: Instance> AdcChannel<T> for Dac {}
55impl<T: Instance> SealedAdcChannel<T> for Dac {
56 fn channel(&self) -> u8 {
57 DAC_CHANNEL
58 }
59}
60
61/// Internal Vcore channel.
62pub struct Vcore;
63impl<T: Instance> AdcChannel<T> for Vcore {}
64impl<T: Instance> SealedAdcChannel<T> for Vcore {
65 fn channel(&self) -> u8 {
66 VCORE_CHANNEL
67 }
68}
69
70pub enum DacChannel {
71 OUT1,
72 OUT2,
73}
74
75/// Number of samples used for averaging.
76pub enum Averaging {
77 Disabled,
78 Samples2,
79 Samples4,
80 Samples8,
81 Samples16,
82 Samples32,
83 Samples64,
84 Samples128,
85 Samples256,
86}
87
88pub const fn resolution_to_max_count(res: Resolution) -> u32 {
89 match res {
90 Resolution::BITS12 => (1 << 12) - 1,
91 Resolution::BITS10 => (1 << 10) - 1,
92 Resolution::BITS8 => (1 << 8) - 1,
93 Resolution::BITS6 => (1 << 6) - 1,
94 #[allow(unreachable_patterns)]
95 _ => core::unreachable!(),
96 }
97}
98
99// NOTE (unused): The prescaler enum closely copies the hardware capabilities,
100// but high prescaling doesn't make a lot of sense in the current implementation and is ommited.
101#[allow(unused)]
102enum Prescaler {
103 NotDivided,
104 DividedBy2,
105 DividedBy4,
106 DividedBy6,
107 DividedBy8,
108 DividedBy10,
109 DividedBy12,
110 DividedBy16,
111 DividedBy32,
112 DividedBy64,
113 DividedBy128,
114 DividedBy256,
115}
116
117impl Prescaler {
118 fn from_ker_ck(frequency: Hertz) -> Self {
119 let raw_prescaler = frequency.0 / MAX_ADC_CLK_FREQ.0;
120 match raw_prescaler {
121 0 => Self::NotDivided,
122 1 => Self::DividedBy2,
123 2..=3 => Self::DividedBy4,
124 4..=5 => Self::DividedBy6,
125 6..=7 => Self::DividedBy8,
126 8..=9 => Self::DividedBy10,
127 10..=11 => Self::DividedBy12,
128 _ => unimplemented!(),
129 }
130 }
131
132 fn divisor(&self) -> u32 {
133 match self {
134 Prescaler::NotDivided => 1,
135 Prescaler::DividedBy2 => 2,
136 Prescaler::DividedBy4 => 4,
137 Prescaler::DividedBy6 => 6,
138 Prescaler::DividedBy8 => 8,
139 Prescaler::DividedBy10 => 10,
140 Prescaler::DividedBy12 => 12,
141 Prescaler::DividedBy16 => 16,
142 Prescaler::DividedBy32 => 32,
143 Prescaler::DividedBy64 => 64,
144 Prescaler::DividedBy128 => 128,
145 Prescaler::DividedBy256 => 256,
146 }
147 }
148
149 fn presc(&self) -> Presc {
150 match self {
151 Prescaler::NotDivided => Presc::DIV1,
152 Prescaler::DividedBy2 => Presc::DIV2,
153 Prescaler::DividedBy4 => Presc::DIV4,
154 Prescaler::DividedBy6 => Presc::DIV6,
155 Prescaler::DividedBy8 => Presc::DIV8,
156 Prescaler::DividedBy10 => Presc::DIV10,
157 Prescaler::DividedBy12 => Presc::DIV12,
158 Prescaler::DividedBy16 => Presc::DIV16,
159 Prescaler::DividedBy32 => Presc::DIV32,
160 Prescaler::DividedBy64 => Presc::DIV64,
161 Prescaler::DividedBy128 => Presc::DIV128,
162 Prescaler::DividedBy256 => Presc::DIV256,
163 }
164 }
165}
166
167pub trait SealedInstance {
168 #[allow(unused)]
169 fn regs() -> crate::pac::adc::Adc4;
170}
171
172pub trait Instance: SealedInstance + crate::Peripheral<P = Self> + crate::rcc::RccPeripheral {
173 type Interrupt: crate::interrupt::typelevel::Interrupt;
174}
175
176pub struct Adc4<'d, T: Instance> {
177 #[allow(unused)]
178 adc: crate::PeripheralRef<'d, T>,
179}
180
181#[derive(Debug)]
182pub enum Adc4Error {
183 InvalidSequence,
184 DMAError,
185}
186
187impl<'d, T: Instance> Adc4<'d, T> {
188 /// Create a new ADC driver.
189 pub fn new(adc: impl Peripheral<P = T> + 'd) -> Self {
190 embassy_hal_internal::into_ref!(adc);
191 rcc::enable_and_reset::<T>();
192 let prescaler = Prescaler::from_ker_ck(T::frequency());
193
194 T::regs().ccr().modify(|w| w.set_presc(prescaler.presc()));
195
196 let frequency = Hertz(T::frequency().0 / prescaler.divisor());
197 info!("ADC4 frequency set to {} Hz", frequency.0);
198
199 if frequency > MAX_ADC_CLK_FREQ {
200 panic!("Maximal allowed frequency for ADC4 is {} MHz and it varies with different packages, refer to ST docs for more information.", MAX_ADC_CLK_FREQ.0 / 1_000_000 );
201 }
202
203 let mut s = Self { adc };
204
205 s.power_up();
206
207 s.calibrate();
208 blocking_delay_us(1);
209
210 s.enable();
211 s.configure();
212
213 s
214 }
215
216 fn power_up(&mut self) {
217 T::regs().isr().modify(|w| {
218 w.set_ldordy(true);
219 });
220 T::regs().cr().modify(|w| {
221 w.set_advregen(true);
222 });
223 while !T::regs().isr().read().ldordy() {}
224
225 T::regs().isr().modify(|w| {
226 w.set_ldordy(true);
227 });
228 }
229
230 fn calibrate(&mut self) {
231 T::regs().cr().modify(|w| w.set_adcal(true));
232 while T::regs().cr().read().adcal() {}
233 T::regs().isr().modify(|w| w.set_eocal(true));
234 }
235
236 fn enable(&mut self) {
237 T::regs().isr().write(|w| w.set_adrdy(true));
238 T::regs().cr().modify(|w| w.set_aden(true));
239 while !T::regs().isr().read().adrdy() {}
240 T::regs().isr().write(|w| w.set_adrdy(true));
241 }
242
243 fn configure(&mut self) {
244 // single conversion mode, software trigger
245 T::regs().cfgr1().modify(|w| {
246 w.set_cont(false);
247 w.set_discen(false);
248 w.set_exten(Adc4Exten::DISABLED);
249 w.set_chselrmod(false);
250 });
251
252 // only use one channel at the moment
253 T::regs().smpr().modify(|w| {
254 for i in 0..24 {
255 w.set_smpsel(i, false);
256 }
257 });
258 }
259
260 /// Enable reading the voltage reference internal channel.
261 pub fn enable_vrefint(&self) -> VrefInt {
262 T::regs().ccr().modify(|w| {
263 w.set_vrefen(true);
264 });
265
266 VrefInt {}
267 }
268
269 /// Enable reading the temperature internal channel.
270 pub fn enable_temperature(&self) -> Temperature {
271 T::regs().ccr().modify(|w| {
272 w.set_vsensesel(true);
273 });
274
275 Temperature {}
276 }
277
278 /// Enable reading the vbat internal channel.
279 pub fn enable_vbat(&self) -> Vbat {
280 T::regs().ccr().modify(|w| {
281 w.set_vbaten(true);
282 });
283
284 Vbat {}
285 }
286
287 /// Enable reading the vbat internal channel.
288 pub fn enable_vcore(&self) -> Vcore {
289 Vcore {}
290 }
291
292 /// Enable reading the vbat internal channel.
293 pub fn enable_dac_channel(&self, dac: DacChannel) -> Dac {
294 let mux;
295 match dac {
296 DacChannel::OUT1 => mux = false,
297 DacChannel::OUT2 => mux = true,
298 }
299 T::regs().or().modify(|w| w.set_chn21sel(mux));
300 Dac {}
301 }
302
303 /// Set the ADC sample time.
304 pub fn set_sample_time(&mut self, sample_time: SampleTime) {
305 T::regs().smpr().modify(|w| {
306 w.set_smp(0, sample_time);
307 });
308 }
309
310 /// Get the ADC sample time.
311 pub fn sample_time(&self) -> SampleTime {
312 T::regs().smpr().read().smp(0)
313 }
314
315 /// Set the ADC resolution.
316 pub fn set_resolution(&mut self, resolution: Resolution) {
317 T::regs().cfgr1().modify(|w| w.set_res(resolution.into()));
318 }
319
320 /// Set hardware averaging.
321 pub fn set_averaging(&mut self, averaging: Averaging) {
322 let (enable, samples, right_shift) = match averaging {
323 Averaging::Disabled => (false, Adc4OversamplingRatio::OVERSAMPLE2X, 0),
324 Averaging::Samples2 => (true, Adc4OversamplingRatio::OVERSAMPLE2X, 1),
325 Averaging::Samples4 => (true, Adc4OversamplingRatio::OVERSAMPLE4X, 2),
326 Averaging::Samples8 => (true, Adc4OversamplingRatio::OVERSAMPLE8X, 3),
327 Averaging::Samples16 => (true, Adc4OversamplingRatio::OVERSAMPLE16X, 4),
328 Averaging::Samples32 => (true, Adc4OversamplingRatio::OVERSAMPLE32X, 5),
329 Averaging::Samples64 => (true, Adc4OversamplingRatio::OVERSAMPLE64X, 6),
330 Averaging::Samples128 => (true, Adc4OversamplingRatio::OVERSAMPLE128X, 7),
331 Averaging::Samples256 => (true, Adc4OversamplingRatio::OVERSAMPLE256X, 8),
332 };
333
334 T::regs().cfgr2().modify(|w| {
335 w.set_ovsr(samples);
336 w.set_ovss(right_shift);
337 w.set_ovse(enable)
338 })
339 }
340
341 /// Read an ADC channel.
342 pub fn blocking_read(&mut self, channel: &mut impl AdcChannel<T>) -> u16 {
343 channel.setup();
344
345 // Select channel
346 T::regs().chselrmod0().write_value(Adc4Chselrmod0(0_u32));
347 T::regs().chselrmod0().modify(|w| {
348 w.set_chsel(channel.channel() as usize, true);
349 });
350
351 // Reset interrupts
352 T::regs().isr().modify(|reg| {
353 reg.set_eos(true);
354 reg.set_eoc(true);
355 });
356
357 // Start conversion
358 T::regs().cr().modify(|reg| {
359 reg.set_adstart(true);
360 });
361
362 while !T::regs().isr().read().eos() {
363 // spin
364 }
365
366 T::regs().dr().read().0 as u16
367 }
368
369 /// Read one or multiple ADC channels using DMA.
370 ///
371 /// `sequence` iterator and `readings` must have the same length.
372 /// The channels in `sequence` must be in ascending order.
373 ///
374 /// Example
375 /// ```rust,ignore
376 /// use embassy_stm32::adc::adc4;
377 /// use embassy_stm32::adc::AdcChannel;
378 ///
379 /// let mut adc4 = adc4::Adc4::new(p.ADC4);
380 /// let mut adc4_pin1 = p.PC1;
381 /// let mut adc4_pin2 = p.PC0;
382 /// let mut degraded41 = adc4_pin1.degrade_adc();
383 /// let mut degraded42 = adc4_pin2.degrade_adc();
384 /// let mut measurements = [0u16; 2];
385 /// // not that the channels must be in ascending order
386 /// adc4.read(
387 /// &mut p.GPDMA1_CH1,
388 /// [
389 /// &mut degraded42,
390 /// &mut degraded41,
391 /// ]
392 /// .into_iter(),
393 /// &mut measurements,
394 /// ).await.unwrap();
395 /// ```
396 pub async fn read(
397 &mut self,
398 rx_dma: &mut impl RxDma4<T>,
399 sequence: impl ExactSizeIterator<Item = &mut AnyAdcChannel<T>>,
400 readings: &mut [u16],
401 ) -> Result<(), Adc4Error> {
402 assert!(sequence.len() != 0, "Asynchronous read sequence cannot be empty");
403 assert!(
404 sequence.len() == readings.len(),
405 "Sequence length must be equal to readings length"
406 );
407
408 // Ensure no conversions are ongoing
409 Self::cancel_conversions();
410
411 T::regs().isr().modify(|reg| {
412 reg.set_ovr(true);
413 reg.set_eos(true);
414 reg.set_eoc(true);
415 });
416
417 T::regs().cfgr1().modify(|reg| {
418 reg.set_dmaen(true);
419 reg.set_dmacfg(Adc4Dmacfg::ONESHOT);
420 reg.set_chselrmod(false);
421 });
422
423 // Verify and activate sequence
424 let mut prev_channel: i16 = -1;
425 T::regs().chselrmod0().write_value(Adc4Chselrmod0(0_u32));
426 for channel in sequence {
427 let channel_num = channel.channel;
428 if channel_num as i16 <= prev_channel {
429 return Err(Adc4Error::InvalidSequence);
430 };
431 prev_channel = channel_num as i16;
432
433 T::regs().chselrmod0().modify(|w| {
434 w.set_chsel(channel.channel as usize, true);
435 });
436 }
437
438 let request = rx_dma.request();
439 let transfer = unsafe {
440 Transfer::new_read(
441 rx_dma,
442 request,
443 T::regs().dr().as_ptr() as *mut u16,
444 readings,
445 Default::default(),
446 )
447 };
448
449 // Start conversion
450 T::regs().cr().modify(|reg| {
451 reg.set_adstart(true);
452 });
453
454 transfer.await;
455
456 // Ensure conversions are finished.
457 Self::cancel_conversions();
458
459 // Reset configuration.
460 T::regs().cfgr1().modify(|reg| {
461 reg.set_dmaen(false);
462 });
463
464 if T::regs().isr().read().ovr() {
465 Err(Adc4Error::DMAError)
466 } else {
467 Ok(())
468 }
469 }
470
471 fn cancel_conversions() {
472 if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() {
473 T::regs().cr().modify(|reg| {
474 reg.set_adstp(true);
475 });
476 while T::regs().cr().read().adstart() {}
477 }
478 }
479}
diff --git a/embassy-stm32/src/adc/v4.rs b/embassy-stm32/src/adc/v4.rs
index 63b5b58ea..46f9c7ac7 100644
--- a/embassy-stm32/src/adc/v4.rs
+++ b/embassy-stm32/src/adc/v4.rs
@@ -1,5 +1,7 @@
1#[cfg(not(stm32u5))]
2use pac::adc::vals::{Adcaldif, Boost};
1#[allow(unused)] 3#[allow(unused)]
2use pac::adc::vals::{Adcaldif, Adstp, Boost, Difsel, Dmngt, Exten, Pcsel}; 4use pac::adc::vals::{Adstp, Difsel, Dmngt, Exten, Pcsel};
3use pac::adccommon::vals::Presc; 5use pac::adccommon::vals::Presc;
4 6
5use super::{ 7use super::{
@@ -19,6 +21,8 @@ pub const VREF_CALIB_MV: u32 = 3300;
19const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(60); 21const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(60);
20#[cfg(stm32h7)] 22#[cfg(stm32h7)]
21const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(50); 23const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(50);
24#[cfg(stm32u5)]
25const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55);
22 26
23#[cfg(stm32g4)] 27#[cfg(stm32g4)]
24const VREF_CHANNEL: u8 = 18; 28const VREF_CHANNEL: u8 = 18;
@@ -31,8 +35,16 @@ const VREF_CHANNEL: u8 = 19;
31const TEMP_CHANNEL: u8 = 18; 35const TEMP_CHANNEL: u8 = 18;
32 36
33// TODO this should be 14 for H7a/b/35 37// TODO this should be 14 for H7a/b/35
38#[cfg(not(stm32u5))]
34const VBAT_CHANNEL: u8 = 17; 39const VBAT_CHANNEL: u8 = 17;
35 40
41#[cfg(stm32u5)]
42const VREF_CHANNEL: u8 = 0;
43#[cfg(stm32u5)]
44const TEMP_CHANNEL: u8 = 19;
45#[cfg(stm32u5)]
46const VBAT_CHANNEL: u8 = 18;
47
36// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs 48// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs
37/// Internal voltage reference channel. 49/// Internal voltage reference channel.
38pub struct VrefInt; 50pub struct VrefInt;
@@ -209,6 +221,7 @@ impl<'d, T: Instance> Adc<'d, T> {
209 221
210 fn calibrate(&mut self) { 222 fn calibrate(&mut self) {
211 T::regs().cr().modify(|w| { 223 T::regs().cr().modify(|w| {
224 #[cfg(not(adc_u5))]
212 w.set_adcaldif(Adcaldif::SINGLEENDED); 225 w.set_adcaldif(Adcaldif::SINGLEENDED);
213 w.set_adcallin(true); 226 w.set_adcallin(true);
214 }); 227 });
@@ -446,7 +459,7 @@ impl<'d, T: Instance> Adc<'d, T> {
446 459
447 Self::set_channel_sample_time(channel, sample_time); 460 Self::set_channel_sample_time(channel, sample_time);
448 461
449 #[cfg(stm32h7)] 462 #[cfg(any(stm32h7, stm32u5))]
450 { 463 {
451 T::regs().cfgr2().modify(|w| w.set_lshift(0)); 464 T::regs().cfgr2().modify(|w| w.set_lshift(0));
452 T::regs() 465 T::regs()
diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs
index 857090303..d04199d05 100644
--- a/embassy-stm32/src/lib.rs
+++ b/embassy-stm32/src/lib.rs
@@ -238,6 +238,10 @@ pub struct Config {
238 #[cfg(any(stm32l4, stm32l5, stm32u5))] 238 #[cfg(any(stm32l4, stm32l5, stm32u5))]
239 pub enable_independent_io_supply: bool, 239 pub enable_independent_io_supply: bool,
240 240
241 /// On the U5 series all analog peripherals are powered by a separate supply.
242 #[cfg(stm32u5)]
243 pub enable_independent_analog_supply: bool,
244
241 /// BDMA interrupt priority. 245 /// BDMA interrupt priority.
242 /// 246 ///
243 /// Defaults to P0 (highest). 247 /// Defaults to P0 (highest).
@@ -277,6 +281,8 @@ impl Default for Config {
277 enable_debug_during_sleep: true, 281 enable_debug_during_sleep: true,
278 #[cfg(any(stm32l4, stm32l5, stm32u5))] 282 #[cfg(any(stm32l4, stm32l5, stm32u5))]
279 enable_independent_io_supply: true, 283 enable_independent_io_supply: true,
284 #[cfg(stm32u5)]
285 enable_independent_analog_supply: true,
280 #[cfg(bdma)] 286 #[cfg(bdma)]
281 bdma_interrupt_priority: Priority::P0, 287 bdma_interrupt_priority: Priority::P0,
282 #[cfg(dma)] 288 #[cfg(dma)]
@@ -527,6 +533,20 @@ fn init_hw(config: Config) -> Peripherals {
527 crate::pac::PWR.svmcr().modify(|w| { 533 crate::pac::PWR.svmcr().modify(|w| {
528 w.set_io2sv(config.enable_independent_io_supply); 534 w.set_io2sv(config.enable_independent_io_supply);
529 }); 535 });
536 if config.enable_independent_analog_supply {
537 crate::pac::PWR.svmcr().modify(|w| {
538 w.set_avm1en(true);
539 });
540 while !crate::pac::PWR.svmsr().read().vdda1rdy() {}
541 crate::pac::PWR.svmcr().modify(|w| {
542 w.set_asv(true);
543 });
544 } else {
545 crate::pac::PWR.svmcr().modify(|w| {
546 w.set_avm1en(false);
547 w.set_avm2en(false);
548 });
549 }
530 } 550 }
531 551
532 // dead battery functionality is still present on these 552 // dead battery functionality is still present on these
diff --git a/examples/stm32u5/src/bin/adc.rs b/examples/stm32u5/src/bin/adc.rs
new file mode 100644
index 000000000..6ba21cc63
--- /dev/null
+++ b/examples/stm32u5/src/bin/adc.rs
@@ -0,0 +1,109 @@
1#![no_std]
2#![no_main]
3
4use defmt::*;
5use embassy_stm32::adc;
6use embassy_stm32::adc::{adc4, AdcChannel};
7use {defmt_rtt as _, panic_probe as _};
8
9#[embassy_executor::main]
10async fn main(_spawner: embassy_executor::Spawner) {
11 let config = embassy_stm32::Config::default();
12
13 let mut p = embassy_stm32::init(config);
14
15 // **** ADC1 init ****
16 let mut adc1 = adc::Adc::new(p.ADC1);
17 let mut adc1_pin1 = p.PA3; // A0 on nucleo u5a5
18 let mut adc1_pin2 = p.PA2; // A1
19 adc1.set_resolution(adc::Resolution::BITS14);
20 adc1.set_averaging(adc::Averaging::Samples1024);
21 adc1.set_sample_time(adc::SampleTime::CYCLES160_5);
22 let max1 = adc::resolution_to_max_count(adc::Resolution::BITS14);
23
24 // **** ADC2 init ****
25 let mut adc2 = adc::Adc::new(p.ADC2);
26 let mut adc2_pin1 = p.PC3; // A2
27 let mut adc2_pin2 = p.PB0; // A3
28 adc2.set_resolution(adc::Resolution::BITS14);
29 adc2.set_averaging(adc::Averaging::Samples1024);
30 adc2.set_sample_time(adc::SampleTime::CYCLES160_5);
31 let max2 = adc::resolution_to_max_count(adc::Resolution::BITS14);
32
33 // **** ADC4 init ****
34 let mut adc4 = adc4::Adc4::new(p.ADC4);
35 let mut adc4_pin1 = p.PC1; // A4
36 let mut adc4_pin2 = p.PC0; // A5
37 adc4.set_resolution(adc4::Resolution::BITS12);
38 adc4.set_averaging(adc4::Averaging::Samples256);
39 adc4.set_sample_time(adc4::SampleTime::CYCLES1_5);
40 let max4 = adc4::resolution_to_max_count(adc4::Resolution::BITS12);
41
42 // **** ADC1 blocking read ****
43 let raw: u16 = adc1.blocking_read(&mut adc1_pin1);
44 let volt: f32 = 3.3 * raw as f32 / max1 as f32;
45 info!("Read adc1 pin 1 {}", volt);
46
47 let raw: u16 = adc1.blocking_read(&mut adc1_pin2);
48 let volt: f32 = 3.3 * raw as f32 / max1 as f32;
49 info!("Read adc1 pin 2 {}", volt);
50
51 // **** ADC2 blocking read ****
52 let raw: u16 = adc2.blocking_read(&mut adc2_pin1);
53 let volt: f32 = 3.3 * raw as f32 / max2 as f32;
54 info!("Read adc2 pin 1 {}", volt);
55
56 let raw: u16 = adc2.blocking_read(&mut adc2_pin2);
57 let volt: f32 = 3.3 * raw as f32 / max2 as f32;
58 info!("Read adc2 pin 2 {}", volt);
59
60 // **** ADC4 blocking read ****
61 let raw: u16 = adc4.blocking_read(&mut adc4_pin1);
62 let volt: f32 = 3.3 * raw as f32 / max4 as f32;
63 info!("Read adc4 pin 1 {}", volt);
64
65 let raw: u16 = adc4.blocking_read(&mut adc4_pin2);
66 let volt: f32 = 3.3 * raw as f32 / max4 as f32;
67 info!("Read adc4 pin 2 {}", volt);
68
69 // **** ADC1 async read ****
70 let mut degraded11 = adc1_pin1.degrade_adc();
71 let mut degraded12 = adc1_pin2.degrade_adc();
72 let mut measurements = [0u16; 2];
73
74 adc1.read(
75 &mut p.GPDMA1_CH0,
76 [
77 (&mut degraded11, adc::SampleTime::CYCLES160_5),
78 (&mut degraded12, adc::SampleTime::CYCLES160_5),
79 ]
80 .into_iter(),
81 &mut measurements,
82 )
83 .await;
84 let volt1: f32 = 3.3 * measurements[0] as f32 / max1 as f32;
85 let volt2: f32 = 3.3 * measurements[1] as f32 / max1 as f32;
86
87 info!("Async read 1 pin 1 {}", volt1);
88 info!("Async read 1 pin 2 {}", volt2);
89
90 // **** ADC2 does not support async read ****
91
92 // **** ADC4 async read ****
93 let mut degraded41 = adc4_pin1.degrade_adc();
94 let mut degraded42 = adc4_pin2.degrade_adc();
95 let mut measurements = [0u16; 2];
96
97 // The channels must be in ascending order and can't repeat for ADC4
98 adc4.read(
99 &mut p.GPDMA1_CH1,
100 [&mut degraded42, &mut degraded41].into_iter(),
101 &mut measurements,
102 )
103 .await
104 .unwrap();
105 let volt2: f32 = 3.3 * measurements[0] as f32 / max4 as f32;
106 let volt1: f32 = 3.3 * measurements[1] as f32 / max4 as f32;
107 info!("Async read 4 pin 1 {}", volt1);
108 info!("Async read 4 pin 2 {}", volt2);
109}