timer.rs 15 KB

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