timer.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /*!
  2. # Timer
  3. ## Alternate function remapping
  4. This is a list of the remap settings you can use to assign pins to PWM channels
  5. and the QEI peripherals
  6. ### TIM1
  7. Not available on STM32F101.
  8. | Channel | Tim1NoRemap | Tim1FullRemap |
  9. |:---:|:-----------:|:-------------:|
  10. | CH1 | PA8 | PE9 |
  11. | CH2 | PA9 | PE11 |
  12. | CH3 | PA10 | PE13 |
  13. | CH4 | PA11 | PE14 |
  14. ### TIM2
  15. | Channel | Tim2NoRemap | Tim2PartialRemap1 | Tim2PartialRemap2 | Tim2FullRemap |
  16. |:---:|:-----------:|:-----------------:|:-----------------:|:-------------:|
  17. | CH1 | PA0 | PA15 | PA0 | PA15 |
  18. | CH2 | PA1 | PB3 | PA1 | PB3 |
  19. | CH3 | PA2 | PA2 | PB10 | PB10 |
  20. | CH4 | PA3 | PA3 | PB11 | PB11 |
  21. ### TIM3
  22. | Channel | Tim3NoRemap | Tim3PartialRemap | Tim3FullRemap |
  23. |:---:|:-----------:|:----------------:|:-------------:|
  24. | CH1 | PA6 | PB4 | PC6 |
  25. | CH2 | PA7 | PB5 | PC7 |
  26. | CH3 | PB0 | PB0 | PC8 |
  27. | CH4 | PB1 | PB1 | PC9 |
  28. ### TIM4
  29. Not available on low density devices.
  30. | Channel | Tim4NoRemap | Tim4Remap |
  31. |:---:|:-----------:|:---------:|
  32. | CH1 | PB6 | PD12 |
  33. | CH2 | PB7 | PD13 |
  34. | CH3 | PB8 | PD14 |
  35. | CH4 | PB9 | PD15 |
  36. */
  37. use crate::hal::timer::{CountDown, Periodic};
  38. #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
  39. use crate::pac::TIM1;
  40. #[cfg(feature = "medium")]
  41. use crate::pac::TIM4;
  42. #[cfg(any(feature = "high", feature = "connectivity"))]
  43. use crate::pac::TIM5;
  44. #[cfg(any(feature = "stm32f100", feature = "high", feature = "connectivity",))]
  45. use crate::pac::TIM6;
  46. #[cfg(any(
  47. all(feature = "high", any(feature = "stm32f101", feature = "stm32f103",),),
  48. any(feature = "stm32f100", feature = "connectivity",)
  49. ))]
  50. use crate::pac::TIM7;
  51. #[cfg(all(feature = "stm32f103", feature = "high",))]
  52. use crate::pac::TIM8;
  53. use crate::pac::{DBGMCU as DBG, TIM2, TIM3};
  54. #[cfg(feature = "stm32f100")]
  55. use crate::pac::{TIM15, TIM16, TIM17};
  56. #[cfg(not(feature = "stm32f101"))]
  57. use crate::rcc::APB2;
  58. use crate::rcc::{sealed::RccBus, Clocks, Enable, GetBusFreq, Reset, APB1};
  59. use cast::{u16, u32, u64};
  60. use cortex_m::peripheral::syst::SystClkSource;
  61. use cortex_m::peripheral::SYST;
  62. use void::Void;
  63. use crate::time::Hertz;
  64. /// Interrupt events
  65. pub enum Event {
  66. /// Timer timed out / count down ended
  67. Update,
  68. }
  69. pub struct Timer<TIM> {
  70. pub(crate) tim: TIM,
  71. pub(crate) clk: Hertz,
  72. }
  73. pub struct CountDownTimer<TIM> {
  74. tim: TIM,
  75. clk: Hertz,
  76. }
  77. pub(crate) mod sealed {
  78. pub trait Remap {
  79. type Periph;
  80. const REMAP: u8;
  81. }
  82. pub trait Ch1<REMAP> {}
  83. pub trait Ch2<REMAP> {}
  84. pub trait Ch3<REMAP> {}
  85. pub trait Ch4<REMAP> {}
  86. }
  87. macro_rules! remap {
  88. ($($name:ident: ($TIMX:ident, $state:literal, $P1:ident, $P2:ident, $P3:ident, $P4:ident),)+) => {
  89. $(
  90. pub struct $name;
  91. impl sealed::Remap for $name {
  92. type Periph = $TIMX;
  93. const REMAP: u8 = $state;
  94. }
  95. impl<MODE> sealed::Ch1<$name> for $P1<MODE> {}
  96. impl<MODE> sealed::Ch2<$name> for $P2<MODE> {}
  97. impl<MODE> sealed::Ch3<$name> for $P3<MODE> {}
  98. impl<MODE> sealed::Ch4<$name> for $P4<MODE> {}
  99. )+
  100. }
  101. }
  102. use crate::gpio::gpioa::{PA0, PA1, PA15, PA2, PA3, PA6, PA7};
  103. use crate::gpio::gpiob::{PB0, PB1, PB10, PB11, PB3, PB4, PB5};
  104. use crate::gpio::gpioc::{PC6, PC7, PC8, PC9};
  105. #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
  106. use crate::gpio::{
  107. gpioa::{PA10, PA11, PA8, PA9},
  108. gpioe::{PE11, PE13, PE14, PE9},
  109. };
  110. #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
  111. remap!(
  112. Tim1NoRemap: (TIM1, 0b00, PA8, PA9, PA10, PA11),
  113. //Tim1PartialRemap: (TIM1, 0b01, PA8, PA9, PA10, PA11),
  114. Tim1FullRemap: (TIM1, 0b11, PE9, PE11, PE13, PE14),
  115. );
  116. remap!(
  117. Tim2NoRemap: (TIM2, 0b00, PA0, PA1, PA2, PA3),
  118. Tim2PartialRemap1: (TIM2, 0b01, PA15, PB3, PA2, PA3),
  119. Tim2PartialRemap2: (TIM2, 0b10, PA0, PA1, PB10, PB11),
  120. Tim2FullRemap: (TIM2, 0b11, PA15, PB3, PB10, PB11),
  121. Tim3NoRemap: (TIM3, 0b00, PA6, PA7, PB0, PB1),
  122. Tim3PartialRemap: (TIM3, 0b10, PB4, PB5, PB0, PB1),
  123. Tim3FullRemap: (TIM3, 0b11, PC6, PC7, PC8, PC9),
  124. );
  125. #[cfg(feature = "medium")]
  126. use crate::gpio::{
  127. gpiob::{PB6, PB7, PB8, PB9},
  128. gpiod::{PD12, PD13, PD14, PD15},
  129. };
  130. #[cfg(feature = "medium")]
  131. remap!(
  132. Tim4NoRemap: (TIM4, 0b00, PB6, PB7, PB8, PB9),
  133. Tim4Remap: (TIM4, 0b01, PD12, PD13, PD14, PD15),
  134. );
  135. impl Timer<SYST> {
  136. pub fn syst(mut syst: SYST, clocks: &Clocks) -> Self {
  137. syst.set_clock_source(SystClkSource::Core);
  138. Self {
  139. tim: syst,
  140. clk: clocks.hclk(),
  141. }
  142. }
  143. pub fn start_count_down<T>(self, timeout: T) -> CountDownTimer<SYST>
  144. where
  145. T: Into<Hertz>,
  146. {
  147. let Self { tim, clk } = self;
  148. let mut timer = CountDownTimer { tim, clk };
  149. timer.start(timeout);
  150. timer
  151. }
  152. pub fn release(self) -> SYST {
  153. self.tim
  154. }
  155. }
  156. impl CountDownTimer<SYST> {
  157. /// Starts listening for an `event`
  158. pub fn listen(&mut self, event: Event) {
  159. match event {
  160. Event::Update => self.tim.enable_interrupt(),
  161. }
  162. }
  163. /// Stops listening for an `event`
  164. pub fn unlisten(&mut self, event: Event) {
  165. match event {
  166. Event::Update => self.tim.disable_interrupt(),
  167. }
  168. }
  169. /// Resets the counter
  170. pub fn reset(&mut self) {
  171. // According to the Cortex-M3 Generic User Guide, the interrupt request is only generated
  172. // when the counter goes from 1 to 0, so writing zero should not trigger an interrupt
  173. self.tim.clear_current();
  174. }
  175. /// Returns the number of microseconds since the last update event.
  176. /// *NOTE:* This method is not a very good candidate to keep track of time, because
  177. /// it is very easy to lose an update event.
  178. pub fn micros_since(&self) -> u32 {
  179. let reload_value = SYST::get_reload();
  180. let timer_clock = u64(self.clk.0);
  181. let ticks = u64(reload_value - SYST::get_current());
  182. // It is safe to make this cast since the maximum ticks is (2^24 - 1) and the minimum sysclk
  183. // is 4Mhz, which gives a maximum period of ~4.2 seconds which is < (2^32 - 1) microseconds
  184. u32(1_000_000 * ticks / timer_clock).unwrap()
  185. }
  186. /// Stops the timer
  187. pub fn stop(mut self) -> Timer<SYST> {
  188. self.tim.disable_counter();
  189. let Self { tim, clk } = self;
  190. Timer { tim, clk }
  191. }
  192. /// Releases the SYST
  193. pub fn release(self) -> SYST {
  194. self.stop().release()
  195. }
  196. }
  197. impl CountDown for CountDownTimer<SYST> {
  198. type Time = Hertz;
  199. fn start<T>(&mut self, timeout: T)
  200. where
  201. T: Into<Hertz>,
  202. {
  203. let rvr = self.clk.0 / timeout.into().0 - 1;
  204. assert!(rvr < (1 << 24));
  205. self.tim.set_reload(rvr);
  206. self.tim.clear_current();
  207. self.tim.enable_counter();
  208. }
  209. fn wait(&mut self) -> nb::Result<(), Void> {
  210. if self.tim.has_wrapped() {
  211. Ok(())
  212. } else {
  213. Err(nb::Error::WouldBlock)
  214. }
  215. }
  216. }
  217. impl Periodic for CountDownTimer<SYST> {}
  218. macro_rules! hal {
  219. ($($TIMX:ident: ($timX:ident, $APBx:ident, $dbg_timX_stop:ident$(,$master_timbase:ident)*),)+) => {
  220. $(
  221. impl Timer<$TIMX> {
  222. /// Initialize timer
  223. pub fn $timX(tim: $TIMX, clocks: &Clocks, apb: &mut $APBx) -> Self {
  224. // enable and reset peripheral to a clean slate state
  225. $TIMX::enable(apb);
  226. $TIMX::reset(apb);
  227. Self { tim, clk: <$TIMX as RccBus>::Bus::get_timer_frequency(&clocks) }
  228. }
  229. /// Starts timer in count down mode at a given frequency
  230. pub fn start_count_down<T>(self, timeout: T) -> CountDownTimer<$TIMX>
  231. where
  232. T: Into<Hertz>,
  233. {
  234. let Self { tim, clk } = self;
  235. let mut timer = CountDownTimer { tim, clk };
  236. timer.start(timeout);
  237. timer
  238. }
  239. $(
  240. /// Starts timer in count down mode at a given frequency and additionally configures the timers master mode
  241. pub fn start_master<T>(self, timeout: T, mode: crate::pac::$master_timbase::cr2::MMS_A) -> CountDownTimer<$TIMX>
  242. where
  243. T: Into<Hertz>,
  244. {
  245. let Self { tim, clk } = self;
  246. let mut timer = CountDownTimer { tim, clk };
  247. timer.tim.cr2.modify(|_,w| w.mms().variant(mode));
  248. timer.start(timeout);
  249. timer
  250. }
  251. )?
  252. /// Resets timer peripheral
  253. #[inline(always)]
  254. pub fn clocking_reset(&mut self, apb: &mut <$TIMX as RccBus>::Bus) {
  255. $TIMX::reset(apb);
  256. }
  257. /// Stopping timer in debug mode can cause troubles when sampling the signal
  258. #[inline(always)]
  259. pub fn stop_in_debug(&mut self, dbg: &mut DBG, state: bool) {
  260. dbg.cr.modify(|_, w| w.$dbg_timX_stop().bit(state));
  261. }
  262. /// Releases the TIM Peripheral
  263. pub fn release(self) -> $TIMX {
  264. self.tim
  265. }
  266. }
  267. impl CountDownTimer<$TIMX> {
  268. /// Starts listening for an `event`
  269. pub fn listen(&mut self, event: Event) {
  270. match event {
  271. Event::Update => self.tim.dier.write(|w| w.uie().set_bit()),
  272. }
  273. }
  274. /// Stops listening for an `event`
  275. pub fn unlisten(&mut self, event: Event) {
  276. match event {
  277. Event::Update => self.tim.dier.write(|w| w.uie().clear_bit()),
  278. }
  279. }
  280. /// Stops the timer
  281. pub fn stop(self) -> Timer<$TIMX> {
  282. self.tim.cr1.modify(|_, w| w.cen().clear_bit());
  283. let Self { tim, clk } = self;
  284. Timer { tim, clk }
  285. }
  286. /// Clears Update Interrupt Flag
  287. pub fn clear_update_interrupt_flag(&mut self) {
  288. self.tim.sr.modify(|_, w| w.uif().clear_bit());
  289. }
  290. /// Releases the TIM Peripheral
  291. pub fn release(self) -> $TIMX {
  292. self.stop().release()
  293. }
  294. /// Returns the number of microseconds since the last update event.
  295. /// *NOTE:* This method is not a very good candidate to keep track of time, because
  296. /// it is very easy to lose an update event.
  297. pub fn micros_since(&self) -> u32 {
  298. let timer_clock = self.clk.0;
  299. let psc = u32(self.tim.psc.read().psc().bits());
  300. // freq_divider is always bigger than 0, since (psc + 1) is always less than
  301. // timer_clock
  302. let freq_divider = u64(timer_clock / (psc + 1));
  303. let cnt = u64(self.tim.cnt.read().cnt().bits());
  304. // It is safe to make this cast, because the maximum timer period in this HAL is
  305. // 1s (1Hz), then 1 second < (2^32 - 1) microseconds
  306. u32(1_000_000 * cnt / freq_divider).unwrap()
  307. }
  308. /// Resets the counter
  309. pub fn reset(&mut self) {
  310. // Sets the URS bit to prevent an interrupt from being triggered by
  311. // the UG bit
  312. self.tim.cr1.modify(|_, w| w.urs().set_bit());
  313. self.tim.egr.write(|w| w.ug().set_bit());
  314. self.tim.cr1.modify(|_, w| w.urs().clear_bit());
  315. }
  316. }
  317. impl CountDown for CountDownTimer<$TIMX> {
  318. type Time = Hertz;
  319. fn start<T>(&mut self, timeout: T)
  320. where
  321. T: Into<Hertz>,
  322. {
  323. // pause
  324. self.tim.cr1.modify(|_, w| w.cen().clear_bit());
  325. let (psc, arr) = compute_arr_presc(timeout.into().0, self.clk.0);
  326. self.tim.psc.write(|w| w.psc().bits(psc) );
  327. // TODO: Remove this `allow` once this field is made safe for stm32f100
  328. #[allow(unused_unsafe)]
  329. self.tim.arr.write(|w| unsafe { w.arr().bits(arr) });
  330. // Trigger an update event to load the prescaler value to the clock
  331. self.reset();
  332. // start counter
  333. self.tim.cr1.modify(|_, w| w.cen().set_bit());
  334. }
  335. fn wait(&mut self) -> nb::Result<(), Void> {
  336. if self.tim.sr.read().uif().bit_is_clear() {
  337. Err(nb::Error::WouldBlock)
  338. } else {
  339. self.clear_update_interrupt_flag();
  340. Ok(())
  341. }
  342. }
  343. }
  344. impl Periodic for CountDownTimer<$TIMX> {}
  345. )+
  346. }
  347. }
  348. #[inline(always)]
  349. fn compute_arr_presc(freq: u32, clock: u32) -> (u16, u16) {
  350. let ticks = clock / freq;
  351. let psc = u16((ticks - 1) / (1 << 16)).unwrap();
  352. let arr = u16(ticks / u32(psc + 1)).unwrap();
  353. (psc, arr)
  354. }
  355. hal! {
  356. TIM2: (tim2, APB1, dbg_tim2_stop, tim2),
  357. TIM3: (tim3, APB1, dbg_tim3_stop, tim2),
  358. }
  359. #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity",))]
  360. hal! {
  361. TIM1: (tim1, APB2, dbg_tim1_stop, tim1),
  362. }
  363. #[cfg(any(feature = "stm32f100", feature = "high", feature = "connectivity",))]
  364. hal! {
  365. TIM6: (tim6, APB1, dbg_tim6_stop, tim6),
  366. }
  367. #[cfg(any(
  368. all(feature = "high", any(feature = "stm32f101", feature = "stm32f103",),),
  369. any(feature = "stm32f100", feature = "connectivity",)
  370. ))]
  371. hal! {
  372. TIM7: (tim7, APB1, dbg_tim7_stop, tim6),
  373. }
  374. #[cfg(feature = "stm32f100")]
  375. hal! {
  376. TIM15: (tim15, APB2, dbg_tim15_stop),
  377. TIM16: (tim16, APB2, dbg_tim16_stop),
  378. TIM17: (tim17, APB2, dbg_tim17_stop),
  379. }
  380. #[cfg(feature = "medium")]
  381. hal! {
  382. TIM4: (tim4, APB1, dbg_tim4_stop, tim2),
  383. }
  384. #[cfg(any(feature = "high", feature = "connectivity"))]
  385. hal! {
  386. TIM5: (tim5, APB1, dbg_tim5_stop, tim2),
  387. }
  388. #[cfg(all(feature = "stm32f103", feature = "high",))]
  389. hal! {
  390. TIM8: (tim8, APB2, dbg_tim8_stop, tim1),
  391. }
  392. //TODO: restore these timers once stm32-rs has been updated
  393. /*
  394. * dbg_tim(12-13)_stop fields missing from 103 xl in stm32-rs
  395. * dbg_tim(9-10)_stop fields missing from 101 xl in stm32-rs
  396. #[cfg(any(
  397. feature = "xl",
  398. all(
  399. feature = "stm32f100",
  400. feature = "high",
  401. )))]
  402. hal! {
  403. TIM12: (tim12, dbg_tim12_stop),
  404. TIM13: (tim13, dbg_tim13_stop),
  405. TIM14: (tim14, dbg_tim14_stop),
  406. }
  407. #[cfg(feature = "xl")]
  408. hal! {
  409. TIM9: (tim9, dbg_tim9_stop),
  410. TIM10: (tim10, dbg_tim10_stop),
  411. TIM11: (tim11, dbg_tim11_stop),
  412. }
  413. */