adc.rs 25 KB

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