adc.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. fn set_continuous_mode(&mut self, continuous: bool) {
  307. self.rb.cr2.modify(|_, w| w.cont().bit(continuous));
  308. }
  309. fn set_discontinuous_mode(&mut self, channels_count: Option<u8>) {
  310. self.rb.cr1.modify(|_, w| match channels_count {
  311. Some(count) => w.discen().set_bit().discnum().bits(count),
  312. None => w.discen().clear_bit(),
  313. });
  314. }
  315. /**
  316. Performs an ADC conversion
  317. NOTE: Conversions can be started by writing a 1 to the ADON
  318. bit in the `CR2` while it is already 1, and no other bits
  319. are being written in the same operation. This means that
  320. the EOC bit *might* be set already when entering this function
  321. which can cause a read of stale values
  322. The check for `cr2.swstart.bit_is_set` *should* fix it, but
  323. does not. Therefore, ensure you do not do any no-op modifications
  324. to `cr2` just before calling this function
  325. */
  326. fn convert(&mut self, chan: u8) -> u16 {
  327. // Dummy read in case something accidentally triggered
  328. // a conversion by writing to CR2 without changing any
  329. // of the bits
  330. self.rb.dr.read().data().bits();
  331. self.set_channel_sample_time(chan, self.sample_time);
  332. self.rb.sqr3.modify(|_, w| unsafe { w.sq1().bits(chan) });
  333. // ADC start conversion of regular sequence
  334. self.rb.cr2.modify(|_, w|
  335. w
  336. .swstart().set_bit()
  337. .align().bit(self.align.into())
  338. );
  339. while self.rb.cr2.read().swstart().bit_is_set() {}
  340. // ADC wait for conversion results
  341. while self.rb.sr.read().eoc().bit_is_clear() {}
  342. let res = self.rb.dr.read().data().bits();
  343. res
  344. }
  345. /// Powers down the ADC, disables the ADC clock and releases the ADC Peripheral
  346. pub fn release(mut self, apb2: &mut APB2) -> $ADC {
  347. self.power_down();
  348. self.disable_clock(apb2);
  349. self.rb
  350. }
  351. }
  352. impl ChannelTimeSequence for Adc<$ADC> {
  353. #[inline(always)]
  354. fn set_channel_sample_time(&mut self, chan: u8, sample_time: SampleTime) {
  355. self.set_channel_sample_time(chan, sample_time);
  356. }
  357. #[inline(always)]
  358. fn set_regular_sequence (&mut self, channels: &[u8]) {
  359. self.set_regular_sequence(channels);
  360. }
  361. #[inline(always)]
  362. fn set_continuous_mode(&mut self, continuous: bool) {
  363. self.set_continuous_mode(continuous);
  364. }
  365. #[inline(always)]
  366. fn set_discontinuous_mode(&mut self, channels: Option<u8>) {
  367. self.set_discontinuous_mode(channels);
  368. }
  369. }
  370. impl<WORD, PIN> OneShot<$ADC, WORD, PIN> for Adc<$ADC>
  371. where
  372. WORD: From<u16>,
  373. PIN: Channel<$ADC, ID = u8>,
  374. {
  375. type Error = ();
  376. fn read(&mut self, _pin: &mut PIN) -> nb::Result<WORD, Self::Error> {
  377. let res = self.convert(PIN::channel());
  378. Ok(res.into())
  379. }
  380. }
  381. )+
  382. }
  383. }
  384. impl Adc<ADC1> {
  385. fn read_aux(&mut self, chan: u8) -> u16 {
  386. let tsv_off = if self.rb.cr2.read().tsvrefe().bit_is_clear() {
  387. self.rb.cr2.modify(|_, w| w.tsvrefe().set_bit());
  388. // The reference manual says that a stabilization time is needed after the powering the
  389. // sensor, this time can be found in the datasheets.
  390. // Here we are delaying for approximately 10us, considering 1.25 instructions per
  391. // cycle. Do we support a chip which needs more than 10us ?
  392. delay(self.clocks.sysclk().0 / 80_000);
  393. true
  394. } else {
  395. false
  396. };
  397. let val = self.convert(chan);
  398. if tsv_off {
  399. self.rb.cr2.modify(|_, w| w.tsvrefe().clear_bit());
  400. }
  401. val
  402. }
  403. /// Temperature sensor is connected to channel 16 on ADC1. This sensor can be used
  404. /// to measure ambient temperature of the device. However note that the returned
  405. /// value is not an absolute temperature value.
  406. ///
  407. /// In particular, according to section 11.10 from Reference Manual RM0008 Rev 20:
  408. /// "The temperature sensor output voltage changes linearly with temperature. The offset
  409. /// of this line varies from chip to chip due to process variation (up to 45 °C from one
  410. /// chip to another). The internal temperature sensor is more suited to applications
  411. /// that detect temperature variations instead of absolute temperatures. If accurate
  412. /// temperature readings are needed, an external temperature sensor part should be used."
  413. ///
  414. /// Formula to calculate temperature value is also taken from the section 11.10.
  415. pub fn read_temp(&mut self) -> i32 {
  416. /// According to section 5.3.18 "Temperature sensor characteristics"
  417. /// from STM32F1xx datasheets, TS constants values are as follows:
  418. /// AVG_SLOPE - average slope
  419. /// V_25 - temperature sensor ADC voltage at 25°C
  420. const AVG_SLOPE: i32 = 43;
  421. const V_25: i32 = 1430;
  422. let prev_cfg = self.save_cfg();
  423. // recommended ADC sampling for temperature sensor is 17.1 usec,
  424. // so use the following approximate settings
  425. // to support all ADC frequencies
  426. let sample_time = match self.clocks.adcclk().0 {
  427. 0..=1_200_000 => SampleTime::T_1,
  428. 1_200_001..=1_500_000 => SampleTime::T_7,
  429. 1_500_001..=2_400_000 => SampleTime::T_13,
  430. 2_400_001..=3_100_000 => SampleTime::T_28,
  431. 3_100_001..=4_000_000 => SampleTime::T_41,
  432. 4_000_001..=5_000_000 => SampleTime::T_55,
  433. 5_000_001..=14_000_000 => SampleTime::T_71,
  434. _ => SampleTime::T_239,
  435. };
  436. self.set_sample_time(sample_time);
  437. let val_temp: i32 = self.read_aux(16u8).into();
  438. let val_vref: i32 = self.read_aux(17u8).into();
  439. let v_sense = val_temp * 1200 / val_vref;
  440. self.restore_cfg(prev_cfg);
  441. (V_25 - v_sense) * 10 / AVG_SLOPE + 25
  442. }
  443. /// Internal reference voltage Vrefint is connected to channel 17 on ADC1.
  444. /// According to section 5.3.4 "Embedded reference voltage" from STM32F1xx
  445. /// datasheets, typical value of this reference voltage is 1200 mV.
  446. ///
  447. /// This value is useful when ADC readings need to be converted into voltages.
  448. /// For instance, reading from any ADC channel can be converted into voltage (mV)
  449. /// using the following formula:
  450. /// v_chan = adc.read(chan) * 1200 / adc.read_vref()
  451. pub fn read_vref(&mut self) -> u16 {
  452. self.read_aux(17u8)
  453. }
  454. }
  455. adc_hal! {
  456. ADC1: (adc1),
  457. }
  458. #[cfg(feature = "stm32f103")]
  459. adc_hal! {
  460. ADC2: (adc2),
  461. }
  462. #[cfg(all(feature = "stm32f103", feature = "high",))]
  463. adc_hal! {
  464. ADC3: (adc3),
  465. }
  466. pub struct AdcPayload<PINS, MODE> {
  467. adc: Adc<ADC1>,
  468. pins: PINS,
  469. _mode: PhantomData<MODE>,
  470. }
  471. pub trait ChannelTimeSequence {
  472. /// Set ADC sampling time for particular channel
  473. fn set_channel_sample_time(&mut self, chan: u8, sample_time: SampleTime);
  474. /// ADC Set a Regular Channel Conversion Sequence
  475. ///
  476. /// Define a sequence of channels to be converted as a regular group.
  477. fn set_regular_sequence(&mut self, channels: &[u8]);
  478. /// Set ADC continuous conversion
  479. ///
  480. /// When continuous conversion is enabled conversion does not stop at the last selected group channel but continues again from the first selected group channel.
  481. fn set_continuous_mode(&mut self, continuous: bool);
  482. /// Set ADC discontinuous mode
  483. ///
  484. /// It can be used to convert a short sequence of conversions (up to 8) which is a part of the regular sequence of conversions.
  485. fn set_discontinuous_mode(&mut self, channels_count: Option<u8>);
  486. }
  487. /// Set channel sequence and sample times for custom pins
  488. ///
  489. /// Example:
  490. /// ```rust, ignore
  491. /// pub struct AdcPins(PA0<Analog>, PA2<Analog>);
  492. /// impl SetChannels<AdcPins> for Adc<ADC1> {
  493. /// fn set_samples(&mut self) {
  494. /// self.set_channel_sample_time(0, adc::SampleTime::T_28);
  495. /// self.set_channel_sample_time(2, adc::SampleTime::T_28);
  496. /// }
  497. /// fn set_sequence(&mut self) {
  498. /// self.set_regular_sequence(&[0, 2, 0, 2]);
  499. /// // Optionally we can set continuous scan mode
  500. /// self.set_continuous_mode(true);
  501. /// // Also we can use discontinuous conversion (3 channels per conversion)
  502. /// self.set_discontinuous_mode(Some(3));
  503. /// }
  504. /// }
  505. /// ```
  506. pub trait SetChannels<PINS>: ChannelTimeSequence {
  507. fn set_samples(&mut self);
  508. fn set_sequence(&mut self);
  509. }
  510. pub type AdcDma<PINS, MODE> = RxDma<AdcPayload<PINS, MODE>, C1>;
  511. impl<PINS, MODE> Receive for AdcDma<PINS, MODE> {
  512. type RxChannel = C1;
  513. type TransmittedWord = u16;
  514. }
  515. impl<PINS> TransferPayload for AdcDma<PINS, Continuous> {
  516. fn start(&mut self) {
  517. self.channel.start();
  518. self.payload.adc.rb.cr2.modify(|_, w| w.cont().set_bit());
  519. self.payload.adc.rb.cr2.modify(|_, w| w.adon().set_bit());
  520. }
  521. fn stop(&mut self) {
  522. self.channel.stop();
  523. self.payload.adc.rb.cr2.modify(|_, w| w.cont().clear_bit());
  524. }
  525. }
  526. impl<PINS> TransferPayload for AdcDma<PINS, Scan> {
  527. fn start(&mut self) {
  528. self.channel.start();
  529. self.payload.adc.rb.cr2.modify(|_, w| w.adon().set_bit());
  530. }
  531. fn stop(&mut self) {
  532. self.channel.stop();
  533. }
  534. }
  535. impl Adc<ADC1> {
  536. pub fn with_dma<PIN>(mut self, pins: PIN, dma_ch: C1) -> AdcDma<PIN, Continuous>
  537. where
  538. PIN: Channel<ADC1, ID = u8>,
  539. {
  540. self.rb.cr1.modify(|_, w| w.discen().clear_bit());
  541. self.rb.cr2.modify(|_, w| w.align().bit(self.align.into()));
  542. self.set_channel_sample_time(PIN::channel(), self.sample_time);
  543. self.rb
  544. .sqr3
  545. .modify(|_, w| unsafe { w.sq1().bits(PIN::channel()) });
  546. self.rb.cr2.modify(|_, w| w.dma().set_bit());
  547. let payload = AdcPayload {
  548. adc: self,
  549. pins,
  550. _mode: PhantomData,
  551. };
  552. RxDma {
  553. payload,
  554. channel: dma_ch,
  555. }
  556. }
  557. pub fn with_scan_dma<PINS>(mut self, pins: PINS, dma_ch: C1) -> AdcDma<PINS, Scan>
  558. where
  559. Self: SetChannels<PINS>,
  560. {
  561. self.rb.cr2.modify(|_, w| {
  562. w.adon()
  563. .clear_bit()
  564. .dma()
  565. .clear_bit()
  566. .cont()
  567. .clear_bit()
  568. .align()
  569. .bit(self.align.into())
  570. });
  571. self.rb
  572. .cr1
  573. .modify(|_, w| w.scan().set_bit().discen().clear_bit());
  574. self.set_samples();
  575. self.set_sequence();
  576. self.rb
  577. .cr2
  578. .modify(|_, w| w.dma().set_bit().adon().set_bit());
  579. let payload = AdcPayload {
  580. adc: self,
  581. pins,
  582. _mode: PhantomData,
  583. };
  584. RxDma {
  585. payload,
  586. channel: dma_ch,
  587. }
  588. }
  589. }
  590. impl<PINS> AdcDma<PINS, Continuous>
  591. where
  592. Self: TransferPayload,
  593. {
  594. pub fn split(mut self) -> (Adc<ADC1>, PINS, C1) {
  595. self.stop();
  596. let AdcDma { payload, channel } = self;
  597. payload.adc.rb.cr2.modify(|_, w| w.dma().clear_bit());
  598. payload.adc.rb.cr1.modify(|_, w| w.discen().set_bit());
  599. (payload.adc, payload.pins, channel)
  600. }
  601. }
  602. impl<PINS> AdcDma<PINS, Scan>
  603. where
  604. Self: TransferPayload,
  605. {
  606. pub fn split(mut self) -> (Adc<ADC1>, PINS, C1) {
  607. self.stop();
  608. let AdcDma { payload, channel } = self;
  609. payload.adc.rb.cr2.modify(|_, w| w.dma().clear_bit());
  610. payload.adc.rb.cr1.modify(|_, w| w.discen().set_bit());
  611. payload.adc.rb.cr1.modify(|_, w| w.scan().clear_bit());
  612. (payload.adc, payload.pins, channel)
  613. }
  614. }
  615. impl<B, PINS, MODE> crate::dma::CircReadDma<B, u16> for AdcDma<PINS, MODE>
  616. where
  617. Self: TransferPayload,
  618. B: as_slice::AsMutSlice<Element = u16>,
  619. {
  620. fn circ_read(mut self, buffer: &'static mut [B; 2]) -> CircBuffer<B, Self> {
  621. {
  622. let buffer = buffer[0].as_mut_slice();
  623. self.channel
  624. .set_peripheral_address(unsafe { &(*ADC1::ptr()).dr as *const _ as u32 }, false);
  625. self.channel
  626. .set_memory_address(buffer.as_ptr() as u32, true);
  627. self.channel.set_transfer_length(buffer.len() * 2);
  628. atomic::compiler_fence(Ordering::Release);
  629. self.channel.ch().cr.modify(|_, w| {
  630. w.mem2mem()
  631. .clear_bit()
  632. .pl()
  633. .medium()
  634. .msize()
  635. .bits16()
  636. .psize()
  637. .bits16()
  638. .circ()
  639. .set_bit()
  640. .dir()
  641. .clear_bit()
  642. });
  643. }
  644. self.start();
  645. CircBuffer::new(buffer, self)
  646. }
  647. }
  648. impl<B, PINS, MODE> crate::dma::ReadDma<B, u16> for AdcDma<PINS, MODE>
  649. where
  650. Self: TransferPayload,
  651. B: as_slice::AsMutSlice<Element = u16>,
  652. {
  653. fn read(mut self, buffer: &'static mut B) -> Transfer<W, &'static mut B, Self> {
  654. {
  655. let buffer = buffer.as_mut_slice();
  656. self.channel
  657. .set_peripheral_address(unsafe { &(*ADC1::ptr()).dr as *const _ as u32 }, false);
  658. self.channel
  659. .set_memory_address(buffer.as_ptr() as u32, true);
  660. self.channel.set_transfer_length(buffer.len());
  661. }
  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. }