adc.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. //! # API for the Analog to Digital converter
  2. use core::marker::PhantomData;
  3. use embedded_hal::adc::{Channel, OneShot};
  4. use crate::dma::{dma1::C1, CircBuffer, Receive, RxDma, Transfer, TransferPayload, W};
  5. use crate::gpio::Analog;
  6. use crate::gpio::{gpioa, gpiob, gpioc};
  7. use crate::rcc::{Clocks, Enable, Reset, APB2};
  8. use core::sync::atomic::{self, Ordering};
  9. use cortex_m::asm::delay;
  10. use embedded_dma::StaticWriteBuffer;
  11. use crate::pac::ADC1;
  12. #[cfg(feature = "stm32f103")]
  13. use crate::pac::ADC2;
  14. #[cfg(all(feature = "stm32f103", feature = "high",))]
  15. use crate::pac::ADC3;
  16. /// Continuous mode
  17. pub struct Continuous;
  18. /// Scan mode
  19. pub struct Scan;
  20. /// ADC configuration
  21. pub struct Adc<ADC> {
  22. rb: ADC,
  23. sample_time: SampleTime,
  24. align: Align,
  25. clocks: Clocks,
  26. }
  27. #[derive(Clone, Copy, Debug, PartialEq)]
  28. #[allow(non_camel_case_types)]
  29. /// ADC sampling time
  30. ///
  31. /// Options for the sampling time, each is T + 0.5 ADC clock cycles.
  32. pub enum SampleTime {
  33. /// 1.5 cycles sampling time
  34. T_1,
  35. /// 7.5 cycles sampling time
  36. T_7,
  37. /// 13.5 cycles sampling time
  38. T_13,
  39. /// 28.5 cycles sampling time
  40. T_28,
  41. /// 41.5 cycles sampling time
  42. T_41,
  43. /// 55.5 cycles sampling time
  44. T_55,
  45. /// 71.5 cycles sampling time
  46. T_71,
  47. /// 239.5 cycles sampling time
  48. T_239,
  49. }
  50. impl Default for SampleTime {
  51. /// Get the default sample time (currently 28.5 cycles)
  52. fn default() -> Self {
  53. SampleTime::T_28
  54. }
  55. }
  56. impl From<SampleTime> for u8 {
  57. fn from(val: SampleTime) -> Self {
  58. use SampleTime::*;
  59. match val {
  60. T_1 => 0,
  61. T_7 => 1,
  62. T_13 => 2,
  63. T_28 => 3,
  64. T_41 => 4,
  65. T_55 => 5,
  66. T_71 => 6,
  67. T_239 => 7,
  68. }
  69. }
  70. }
  71. #[derive(Clone, Copy, Debug, PartialEq)]
  72. /// ADC data register alignment
  73. pub enum Align {
  74. /// Right alignment of output data
  75. Right,
  76. /// Left alignment of output data
  77. Left,
  78. }
  79. impl Default for Align {
  80. /// Default: right alignment
  81. fn default() -> Self {
  82. Align::Right
  83. }
  84. }
  85. impl From<Align> for bool {
  86. fn from(val: Align) -> Self {
  87. match val {
  88. Align::Right => false,
  89. Align::Left => true,
  90. }
  91. }
  92. }
  93. macro_rules! adc_pins {
  94. ($ADC:ident, $($pin:ty => $chan:expr),+ $(,)*) => {
  95. $(
  96. impl Channel<$ADC> for $pin {
  97. type ID = u8;
  98. fn channel() -> u8 { $chan }
  99. }
  100. )+
  101. };
  102. }
  103. adc_pins!(ADC1,
  104. gpioa::PA0<Analog> => 0_u8,
  105. gpioa::PA1<Analog> => 1_u8,
  106. gpioa::PA2<Analog> => 2_u8,
  107. gpioa::PA3<Analog> => 3_u8,
  108. gpioa::PA4<Analog> => 4_u8,
  109. gpioa::PA5<Analog> => 5_u8,
  110. gpioa::PA6<Analog> => 6_u8,
  111. gpioa::PA7<Analog> => 7_u8,
  112. gpiob::PB0<Analog> => 8_u8,
  113. gpiob::PB1<Analog> => 9_u8,
  114. gpioc::PC0<Analog> => 10_u8,
  115. gpioc::PC1<Analog> => 11_u8,
  116. gpioc::PC2<Analog> => 12_u8,
  117. gpioc::PC3<Analog> => 13_u8,
  118. gpioc::PC4<Analog> => 14_u8,
  119. gpioc::PC5<Analog> => 15_u8,
  120. );
  121. #[cfg(any(feature = "stm32f103",))]
  122. adc_pins!(ADC2,
  123. gpioa::PA0<Analog> => 0_u8,
  124. gpioa::PA1<Analog> => 1_u8,
  125. gpioa::PA2<Analog> => 2_u8,
  126. gpioa::PA3<Analog> => 3_u8,
  127. gpioa::PA4<Analog> => 4_u8,
  128. gpioa::PA5<Analog> => 5_u8,
  129. gpioa::PA6<Analog> => 6_u8,
  130. gpioa::PA7<Analog> => 7_u8,
  131. gpiob::PB0<Analog> => 8_u8,
  132. gpiob::PB1<Analog> => 9_u8,
  133. gpioc::PC0<Analog> => 10_u8,
  134. gpioc::PC1<Analog> => 11_u8,
  135. gpioc::PC2<Analog> => 12_u8,
  136. gpioc::PC3<Analog> => 13_u8,
  137. gpioc::PC4<Analog> => 14_u8,
  138. gpioc::PC5<Analog> => 15_u8,
  139. );
  140. /// Stored ADC config can be restored using the `Adc::restore_cfg` method
  141. #[derive(Copy, Clone, Debug, PartialEq, Default)]
  142. pub struct StoredConfig(SampleTime, Align);
  143. macro_rules! adc_hal {
  144. ($(
  145. $ADC:ident: ($adc:ident),
  146. )+) => {
  147. $(
  148. impl Adc<$ADC> {
  149. /// Init a new Adc
  150. ///
  151. /// Sets all configurable parameters to one-shot defaults,
  152. /// performs a boot-time calibration.
  153. pub fn $adc(adc: $ADC, apb2: &mut APB2, clocks: Clocks) -> Self {
  154. let mut s = Self {
  155. rb: adc,
  156. sample_time: SampleTime::default(),
  157. align: Align::default(),
  158. clocks,
  159. };
  160. s.enable_clock(apb2);
  161. s.power_down();
  162. s.reset(apb2);
  163. s.setup_oneshot();
  164. s.power_up();
  165. // The manual states that we need to wait two ADC clocks cycles after power-up
  166. // before starting calibration, we already delayed in the power-up process, but
  167. // if the adc clock is too low that was not enough.
  168. if s.clocks.adcclk().0 < 2_500_000 {
  169. let two_adc_cycles = s.clocks.sysclk().0 / s.clocks.adcclk().0 *2;
  170. let already_delayed = s.clocks.sysclk().0 / 800_000;
  171. if two_adc_cycles > already_delayed {
  172. delay(two_adc_cycles - already_delayed);
  173. }
  174. }
  175. s.calibrate();
  176. s
  177. }
  178. /// Save current ADC config
  179. pub fn save_cfg(&mut self) -> StoredConfig {
  180. StoredConfig(self.sample_time, self.align)
  181. }
  182. /// Restore saved ADC config
  183. pub fn restore_cfg(&mut self, cfg: StoredConfig) {
  184. self.sample_time = cfg.0;
  185. self.align = cfg.1;
  186. }
  187. /// Reset the ADC config to default, return existing config
  188. pub fn default_cfg(&mut self) -> StoredConfig {
  189. let cfg = self.save_cfg();
  190. self.sample_time = SampleTime::default();
  191. self.align = Align::default();
  192. cfg
  193. }
  194. /// Set ADC sampling time
  195. ///
  196. /// Options can be found in [SampleTime](crate::adc::SampleTime).
  197. pub fn set_sample_time(&mut self, t_samp: SampleTime) {
  198. self.sample_time = t_samp;
  199. }
  200. /// Set the Adc result alignment
  201. ///
  202. /// Options can be found in [Align](crate::adc::Align).
  203. pub fn set_align(&mut self, align: Align) {
  204. self.align = align;
  205. }
  206. /// Returns the largest possible sample value for the current settings
  207. pub fn max_sample(&self) -> u16 {
  208. match self.align {
  209. Align::Left => u16::max_value(),
  210. Align::Right => (1 << 12) - 1,
  211. }
  212. }
  213. #[inline(always)]
  214. pub fn set_external_trigger(&mut self, trigger: crate::pac::$adc::cr2::EXTSEL_A) {
  215. self.rb.cr2.modify(|_, w| w.extsel().variant(trigger))
  216. }
  217. fn power_up(&mut self) {
  218. self.rb.cr2.modify(|_, w| w.adon().set_bit());
  219. // The reference manual says that a stabilization time is needed after power_up,
  220. // this time can be found in the datasheets.
  221. // Here we are delaying for approximately 1us, considering 1.25 instructions per
  222. // cycle. Do we support a chip which needs more than 1us ?
  223. delay(self.clocks.sysclk().0 / 800_000);
  224. }
  225. fn power_down(&mut self) {
  226. self.rb.cr2.modify(|_, w| w.adon().clear_bit());
  227. }
  228. fn reset(&mut self, apb2: &mut APB2) {
  229. $ADC::reset(apb2);
  230. }
  231. fn enable_clock(&mut self, apb2: &mut APB2) {
  232. $ADC::enable(apb2);
  233. }
  234. fn disable_clock(&mut self, apb2: &mut APB2) {
  235. $ADC::disable(apb2);
  236. }
  237. fn calibrate(&mut self) {
  238. /* reset calibration */
  239. self.rb.cr2.modify(|_, w| w.rstcal().set_bit());
  240. while self.rb.cr2.read().rstcal().bit_is_set() {}
  241. /* calibrate */
  242. self.rb.cr2.modify(|_, w| w.cal().set_bit());
  243. while self.rb.cr2.read().cal().bit_is_set() {}
  244. }
  245. fn setup_oneshot(&mut self) {
  246. self.rb.cr2.modify(|_, w| w
  247. .cont().clear_bit()
  248. .exttrig().set_bit()
  249. .extsel().bits(0b111)
  250. );
  251. self.rb.cr1.modify(|_, w| w
  252. .scan().clear_bit()
  253. .discen().set_bit()
  254. );
  255. self.rb.sqr1.modify(|_, w| w.l().bits(0b0));
  256. }
  257. fn set_channel_sample_time(&mut self, chan: u8, sample_time: SampleTime) {
  258. let sample_time = sample_time.into();
  259. match chan {
  260. 0 => self.rb.smpr2.modify(|_, w| w.smp0().bits(sample_time)),
  261. 1 => self.rb.smpr2.modify(|_, w| w.smp1().bits(sample_time)),
  262. 2 => self.rb.smpr2.modify(|_, w| w.smp2().bits(sample_time)),
  263. 3 => self.rb.smpr2.modify(|_, w| w.smp3().bits(sample_time)),
  264. 4 => self.rb.smpr2.modify(|_, w| w.smp4().bits(sample_time)),
  265. 5 => self.rb.smpr2.modify(|_, w| w.smp5().bits(sample_time)),
  266. 6 => self.rb.smpr2.modify(|_, w| w.smp6().bits(sample_time)),
  267. 7 => self.rb.smpr2.modify(|_, w| w.smp7().bits(sample_time)),
  268. 8 => self.rb.smpr2.modify(|_, w| w.smp8().bits(sample_time)),
  269. 9 => self.rb.smpr2.modify(|_, w| w.smp9().bits(sample_time)),
  270. 10 => self.rb.smpr1.modify(|_, w| w.smp10().bits(sample_time)),
  271. 11 => self.rb.smpr1.modify(|_, w| w.smp11().bits(sample_time)),
  272. 12 => self.rb.smpr1.modify(|_, w| w.smp12().bits(sample_time)),
  273. 13 => self.rb.smpr1.modify(|_, w| w.smp13().bits(sample_time)),
  274. 14 => self.rb.smpr1.modify(|_, w| w.smp14().bits(sample_time)),
  275. 15 => self.rb.smpr1.modify(|_, w| w.smp15().bits(sample_time)),
  276. 16 => self.rb.smpr1.modify(|_, w| w.smp16().bits(sample_time)),
  277. 17 => self.rb.smpr1.modify(|_, w| w.smp17().bits(sample_time)),
  278. _ => unreachable!(),
  279. }
  280. }
  281. fn set_regular_sequence (&mut self, channels: &[u8]) {
  282. let len = channels.len();
  283. let bits = channels.iter().take(6).enumerate().fold(0u32, |s, (i, c)|
  284. s | ((*c as u32) << (i * 5))
  285. );
  286. self.rb.sqr3.write(|w| unsafe { w
  287. .bits( bits )
  288. });
  289. if len > 6 {
  290. let bits = channels.iter().skip(6).take(6).enumerate().fold(0u32, |s, (i, c)|
  291. s | ((*c as u32) << (i * 5))
  292. );
  293. self.rb.sqr2.write(|w| unsafe { w
  294. .bits( bits )
  295. });
  296. }
  297. if len > 12 {
  298. let bits = channels.iter().skip(12).take(4).enumerate().fold(0u32, |s, (i, c)|
  299. s | ((*c as u32) << (i * 5))
  300. );
  301. self.rb.sqr1.write(|w| unsafe { w
  302. .bits( bits )
  303. });
  304. }
  305. self.rb.sqr1.modify(|_, w| w.l().bits((len-1) as u8));
  306. }
  307. fn set_continuous_mode(&mut self, continuous: bool) {
  308. self.rb.cr2.modify(|_, w| w.cont().bit(continuous));
  309. }
  310. fn set_discontinuous_mode(&mut self, channels_count: Option<u8>) {
  311. self.rb.cr1.modify(|_, w| match channels_count {
  312. Some(count) => w.discen().set_bit().discnum().bits(count),
  313. None => w.discen().clear_bit(),
  314. });
  315. }
  316. /**
  317. Performs an ADC conversion
  318. NOTE: Conversions can be started by writing a 1 to the ADON
  319. bit in the `CR2` while it is already 1, and no other bits
  320. are being written in the same operation. This means that
  321. the EOC bit *might* be set already when entering this function
  322. which can cause a read of stale values
  323. The check for `cr2.swstart.bit_is_set` *should* fix it, but
  324. does not. Therefore, ensure you do not do any no-op modifications
  325. to `cr2` just before calling this function
  326. */
  327. fn convert(&mut self, chan: u8) -> u16 {
  328. // Dummy read in case something accidentally triggered
  329. // a conversion by writing to CR2 without changing any
  330. // of the bits
  331. self.rb.dr.read().data().bits();
  332. self.set_channel_sample_time(chan, self.sample_time);
  333. self.rb.sqr3.modify(|_, w| unsafe { w.sq1().bits(chan) });
  334. // ADC start conversion of regular sequence
  335. self.rb.cr2.modify(|_, w|
  336. w
  337. .swstart().set_bit()
  338. .align().bit(self.align.into())
  339. );
  340. while self.rb.cr2.read().swstart().bit_is_set() {}
  341. // ADC wait for conversion results
  342. while self.rb.sr.read().eoc().bit_is_clear() {}
  343. let res = self.rb.dr.read().data().bits();
  344. res
  345. }
  346. /// Powers down the ADC, disables the ADC clock and releases the ADC Peripheral
  347. pub fn release(mut self, apb2: &mut APB2) -> $ADC {
  348. self.power_down();
  349. self.disable_clock(apb2);
  350. self.rb
  351. }
  352. }
  353. impl ChannelTimeSequence for Adc<$ADC> {
  354. #[inline(always)]
  355. fn set_channel_sample_time(&mut self, chan: u8, sample_time: SampleTime) {
  356. self.set_channel_sample_time(chan, sample_time);
  357. }
  358. #[inline(always)]
  359. fn set_regular_sequence (&mut self, channels: &[u8]) {
  360. self.set_regular_sequence(channels);
  361. }
  362. #[inline(always)]
  363. fn set_continuous_mode(&mut self, continuous: bool) {
  364. self.set_continuous_mode(continuous);
  365. }
  366. #[inline(always)]
  367. fn set_discontinuous_mode(&mut self, channels: Option<u8>) {
  368. self.set_discontinuous_mode(channels);
  369. }
  370. }
  371. impl<WORD, PIN> OneShot<$ADC, WORD, PIN> for Adc<$ADC>
  372. where
  373. WORD: From<u16>,
  374. PIN: Channel<$ADC, ID = u8>,
  375. {
  376. type Error = ();
  377. fn read(&mut self, _pin: &mut PIN) -> nb::Result<WORD, Self::Error> {
  378. let res = self.convert(PIN::channel());
  379. Ok(res.into())
  380. }
  381. }
  382. )+
  383. }
  384. }
  385. impl Adc<ADC1> {
  386. fn read_aux(&mut self, chan: u8) -> u16 {
  387. let tsv_off = if self.rb.cr2.read().tsvrefe().bit_is_clear() {
  388. self.rb.cr2.modify(|_, w| w.tsvrefe().set_bit());
  389. // The reference manual says that a stabilization time is needed after the powering the
  390. // sensor, this time can be found in the datasheets.
  391. // Here we are delaying for approximately 10us, considering 1.25 instructions per
  392. // cycle. Do we support a chip which needs more than 10us ?
  393. delay(self.clocks.sysclk().0 / 80_000);
  394. true
  395. } else {
  396. false
  397. };
  398. let val = self.convert(chan);
  399. if tsv_off {
  400. self.rb.cr2.modify(|_, w| w.tsvrefe().clear_bit());
  401. }
  402. val
  403. }
  404. /// Temperature sensor is connected to channel 16 on ADC1. This sensor can be used
  405. /// to measure ambient temperature of the device. However note that the returned
  406. /// value is not an absolute temperature value.
  407. ///
  408. /// In particular, according to section 11.10 from Reference Manual RM0008 Rev 20:
  409. /// "The temperature sensor output voltage changes linearly with temperature. The offset
  410. /// of this line varies from chip to chip due to process variation (up to 45 °C from one
  411. /// chip to another). The internal temperature sensor is more suited to applications
  412. /// that detect temperature variations instead of absolute temperatures. If accurate
  413. /// temperature readings are needed, an external temperature sensor part should be used."
  414. ///
  415. /// Formula to calculate temperature value is also taken from the section 11.10.
  416. pub fn read_temp(&mut self) -> i32 {
  417. /// According to section 5.3.18 "Temperature sensor characteristics"
  418. /// from STM32F1xx datasheets, TS constants values are as follows:
  419. /// AVG_SLOPE - average slope
  420. /// V_25 - temperature sensor ADC voltage at 25°C
  421. const AVG_SLOPE: i32 = 43;
  422. const V_25: i32 = 1430;
  423. let prev_cfg = self.save_cfg();
  424. // recommended ADC sampling for temperature sensor is 17.1 usec,
  425. // so use the following approximate settings
  426. // to support all ADC frequencies
  427. let sample_time = match self.clocks.adcclk().0 {
  428. 0..=1_200_000 => SampleTime::T_1,
  429. 1_200_001..=1_500_000 => SampleTime::T_7,
  430. 1_500_001..=2_400_000 => SampleTime::T_13,
  431. 2_400_001..=3_100_000 => SampleTime::T_28,
  432. 3_100_001..=4_000_000 => SampleTime::T_41,
  433. 4_000_001..=5_000_000 => SampleTime::T_55,
  434. 5_000_001..=14_000_000 => SampleTime::T_71,
  435. _ => SampleTime::T_239,
  436. };
  437. self.set_sample_time(sample_time);
  438. let val_temp: i32 = self.read_aux(16u8).into();
  439. let val_vref: i32 = self.read_aux(17u8).into();
  440. let v_sense = val_temp * 1200 / val_vref;
  441. self.restore_cfg(prev_cfg);
  442. (V_25 - v_sense) * 10 / AVG_SLOPE + 25
  443. }
  444. /// Internal reference voltage Vrefint is connected to channel 17 on ADC1.
  445. /// According to section 5.3.4 "Embedded reference voltage" from STM32F1xx
  446. /// datasheets, typical value of this reference voltage is 1200 mV.
  447. ///
  448. /// This value is useful when ADC readings need to be converted into voltages.
  449. /// For instance, reading from any ADC channel can be converted into voltage (mV)
  450. /// using the following formula:
  451. /// v_chan = adc.read(chan) * 1200 / adc.read_vref()
  452. pub fn read_vref(&mut self) -> u16 {
  453. self.read_aux(17u8)
  454. }
  455. }
  456. adc_hal! {
  457. ADC1: (adc1),
  458. }
  459. #[cfg(feature = "stm32f103")]
  460. adc_hal! {
  461. ADC2: (adc2),
  462. }
  463. #[cfg(all(feature = "stm32f103", feature = "high",))]
  464. adc_hal! {
  465. ADC3: (adc3),
  466. }
  467. pub struct AdcPayload<PINS, MODE> {
  468. adc: Adc<ADC1>,
  469. pins: PINS,
  470. _mode: PhantomData<MODE>,
  471. }
  472. pub trait ChannelTimeSequence {
  473. /// Set ADC sampling time for particular channel
  474. fn set_channel_sample_time(&mut self, chan: u8, sample_time: SampleTime);
  475. /// ADC Set a Regular Channel Conversion Sequence
  476. ///
  477. /// Define a sequence of channels to be converted as a regular group.
  478. fn set_regular_sequence(&mut self, channels: &[u8]);
  479. /// Set ADC continuous conversion
  480. ///
  481. /// When continuous conversion is enabled conversion does not stop at the last selected group channel but continues again from the first selected group channel.
  482. fn set_continuous_mode(&mut self, continuous: bool);
  483. /// Set ADC discontinuous mode
  484. ///
  485. /// It can be used to convert a short sequence of conversions (up to 8) which is a part of the regular sequence of conversions.
  486. fn set_discontinuous_mode(&mut self, channels_count: Option<u8>);
  487. }
  488. /// Set channel sequence and sample times for custom pins
  489. ///
  490. /// Example:
  491. /// ```rust, ignore
  492. /// pub struct AdcPins(PA0<Analog>, PA2<Analog>);
  493. /// impl SetChannels<AdcPins> for Adc<ADC1> {
  494. /// fn set_samples(&mut self) {
  495. /// self.set_channel_sample_time(0, adc::SampleTime::T_28);
  496. /// self.set_channel_sample_time(2, adc::SampleTime::T_28);
  497. /// }
  498. /// fn set_sequence(&mut self) {
  499. /// self.set_regular_sequence(&[0, 2, 0, 2]);
  500. /// // Optionally we can set continuous scan mode
  501. /// self.set_continuous_mode(true);
  502. /// // Also we can use discontinuous conversion (3 channels per conversion)
  503. /// self.set_discontinuous_mode(Some(3));
  504. /// }
  505. /// }
  506. /// ```
  507. pub trait SetChannels<PINS>: ChannelTimeSequence {
  508. fn set_samples(&mut self);
  509. fn set_sequence(&mut self);
  510. }
  511. pub type AdcDma<PINS, MODE> = RxDma<AdcPayload<PINS, MODE>, C1>;
  512. impl<PINS, MODE> Receive for AdcDma<PINS, MODE> {
  513. type RxChannel = C1;
  514. type TransmittedWord = u16;
  515. }
  516. impl<PINS> TransferPayload for AdcDma<PINS, Continuous> {
  517. fn start(&mut self) {
  518. self.channel.start();
  519. self.payload.adc.rb.cr2.modify(|_, w| w.cont().set_bit());
  520. self.payload.adc.rb.cr2.modify(|_, w| w.adon().set_bit());
  521. }
  522. fn stop(&mut self) {
  523. self.channel.stop();
  524. self.payload.adc.rb.cr2.modify(|_, w| w.cont().clear_bit());
  525. }
  526. }
  527. impl<PINS> TransferPayload for AdcDma<PINS, Scan> {
  528. fn start(&mut self) {
  529. self.channel.start();
  530. self.payload.adc.rb.cr2.modify(|_, w| w.adon().set_bit());
  531. }
  532. fn stop(&mut self) {
  533. self.channel.stop();
  534. }
  535. }
  536. impl Adc<ADC1> {
  537. pub fn with_dma<PIN>(mut self, pins: PIN, dma_ch: C1) -> AdcDma<PIN, Continuous>
  538. where
  539. PIN: Channel<ADC1, ID = u8>,
  540. {
  541. self.rb.cr1.modify(|_, w| w.discen().clear_bit());
  542. self.rb.cr2.modify(|_, w| w.align().bit(self.align.into()));
  543. self.set_channel_sample_time(PIN::channel(), self.sample_time);
  544. self.rb
  545. .sqr3
  546. .modify(|_, w| unsafe { w.sq1().bits(PIN::channel()) });
  547. self.rb.cr2.modify(|_, w| w.dma().set_bit());
  548. let payload = AdcPayload {
  549. adc: self,
  550. pins,
  551. _mode: PhantomData,
  552. };
  553. RxDma {
  554. payload,
  555. channel: dma_ch,
  556. }
  557. }
  558. pub fn with_scan_dma<PINS>(mut self, pins: PINS, dma_ch: C1) -> AdcDma<PINS, Scan>
  559. where
  560. Self: SetChannels<PINS>,
  561. {
  562. self.rb.cr2.modify(|_, w| {
  563. w.adon()
  564. .clear_bit()
  565. .dma()
  566. .clear_bit()
  567. .cont()
  568. .clear_bit()
  569. .align()
  570. .bit(self.align.into())
  571. });
  572. self.rb
  573. .cr1
  574. .modify(|_, w| w.scan().set_bit().discen().clear_bit());
  575. self.set_samples();
  576. self.set_sequence();
  577. self.rb
  578. .cr2
  579. .modify(|_, w| w.dma().set_bit().adon().set_bit());
  580. let payload = AdcPayload {
  581. adc: self,
  582. pins,
  583. _mode: PhantomData,
  584. };
  585. RxDma {
  586. payload,
  587. channel: dma_ch,
  588. }
  589. }
  590. }
  591. impl<PINS> AdcDma<PINS, Continuous>
  592. where
  593. Self: TransferPayload,
  594. {
  595. pub fn split(mut self) -> (Adc<ADC1>, PINS, C1) {
  596. self.stop();
  597. let AdcDma { payload, channel } = self;
  598. payload.adc.rb.cr2.modify(|_, w| w.dma().clear_bit());
  599. payload.adc.rb.cr1.modify(|_, w| w.discen().set_bit());
  600. (payload.adc, payload.pins, channel)
  601. }
  602. }
  603. impl<PINS> AdcDma<PINS, Scan>
  604. where
  605. Self: TransferPayload,
  606. {
  607. pub fn split(mut self) -> (Adc<ADC1>, PINS, C1) {
  608. self.stop();
  609. let AdcDma { payload, channel } = self;
  610. payload.adc.rb.cr2.modify(|_, w| w.dma().clear_bit());
  611. payload.adc.rb.cr1.modify(|_, w| w.discen().set_bit());
  612. payload.adc.rb.cr1.modify(|_, w| w.scan().clear_bit());
  613. (payload.adc, payload.pins, channel)
  614. }
  615. }
  616. impl<B, PINS, MODE> crate::dma::CircReadDma<B, u16> for AdcDma<PINS, MODE>
  617. where
  618. Self: TransferPayload,
  619. &'static mut [B; 2]: StaticWriteBuffer<Word = u16>,
  620. B: 'static,
  621. {
  622. fn circ_read(mut self, mut buffer: &'static mut [B; 2]) -> CircBuffer<B, Self> {
  623. // NOTE(unsafe) We own the buffer now and we won't call other `&mut` on it
  624. // until the end of the transfer.
  625. let (ptr, len) = unsafe { buffer.static_write_buffer() };
  626. self.channel
  627. .set_peripheral_address(unsafe { &(*ADC1::ptr()).dr as *const _ as u32 }, false);
  628. self.channel.set_memory_address(ptr as u32, true);
  629. self.channel.set_transfer_length(len);
  630. atomic::compiler_fence(Ordering::Release);
  631. self.channel.ch().cr.modify(|_, w| {
  632. w.mem2mem()
  633. .clear_bit()
  634. .pl()
  635. .medium()
  636. .msize()
  637. .bits16()
  638. .psize()
  639. .bits16()
  640. .circ()
  641. .set_bit()
  642. .dir()
  643. .clear_bit()
  644. });
  645. self.start();
  646. CircBuffer::new(buffer, self)
  647. }
  648. }
  649. impl<B, PINS, MODE> crate::dma::ReadDma<B, u16> for AdcDma<PINS, MODE>
  650. where
  651. Self: TransferPayload,
  652. B: StaticWriteBuffer<Word = u16>,
  653. {
  654. fn read(mut self, mut buffer: B) -> Transfer<W, B, Self> {
  655. // NOTE(unsafe) We own the buffer now and we won't call other `&mut` on it
  656. // until the end of the transfer.
  657. let (ptr, len) = unsafe { buffer.static_write_buffer() };
  658. self.channel
  659. .set_peripheral_address(unsafe { &(*ADC1::ptr()).dr as *const _ as u32 }, false);
  660. self.channel.set_memory_address(ptr as u32, true);
  661. self.channel.set_transfer_length(len);
  662. atomic::compiler_fence(Ordering::Release);
  663. self.channel.ch().cr.modify(|_, w| {
  664. w.mem2mem()
  665. .clear_bit()
  666. .pl()
  667. .medium()
  668. .msize()
  669. .bits16()
  670. .psize()
  671. .bits16()
  672. .circ()
  673. .clear_bit()
  674. .dir()
  675. .clear_bit()
  676. });
  677. self.start();
  678. Transfer::w(buffer, self)
  679. }
  680. }