rtc.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /*!
  2. Real time clock
  3. */
  4. use crate::pac::{RCC, RTC};
  5. use crate::backup_domain::BackupDomain;
  6. use crate::time::Hertz;
  7. use core::convert::Infallible;
  8. // The LSE runs at at 32 768 hertz unless an external clock is provided
  9. const LSE_HERTZ: u32 = 32_768;
  10. /**
  11. Real time clock
  12. A continuously running clock that counts seconds¹. It is part of the backup domain which means
  13. that the counter is not affected by system resets or standby mode. If Vbat is connected, it is
  14. not reset even if the rest of the device is powered off. This allows it to be used to wake the
  15. CPU when it is in low power mode.
  16. See [examples/rtc.rs] and [examples/blinky_rtc.rs] for usage examples.
  17. 1: Unless configured to another frequency using [select_frequency](struct.Rtc.html#method.select_frequency)
  18. [examples/rtc.rs]: https://github.com/stm32-rs/stm32f1xx-hal/blob/v0.7.0/examples/rtc.rs
  19. [examples/blinky_rtc.rs]: https://github.com/stm32-rs/stm32f1xx-hal/blob/v0.7.0/examples/blinky_rtc.rs
  20. */
  21. pub struct Rtc {
  22. regs: RTC,
  23. }
  24. impl Rtc {
  25. /**
  26. Initialises the RTC. The `BackupDomain` struct is created by
  27. `Rcc.bkp.constrain()`.
  28. The frequency is set to 1 Hz.
  29. Since the RTC is part of the backup domain, The RTC counter is not reset by normal resets or
  30. power cycles where (VBAT) still has power. Use [set_time](#method.set_time) if you want to
  31. reset the counter.
  32. */
  33. pub fn rtc(regs: RTC, bkp: &mut BackupDomain) -> Self {
  34. let mut result = Rtc { regs };
  35. Rtc::enable_rtc(bkp);
  36. // Set the prescaler to make it count up once every second.
  37. let prl = LSE_HERTZ - 1;
  38. assert!(prl < 1 << 20);
  39. result.perform_write(|s| {
  40. s.regs.prlh.write(|w| unsafe { w.bits(prl >> 16) });
  41. s.regs.prll.write(|w| unsafe { w.bits(prl as u16 as u32) });
  42. });
  43. result
  44. }
  45. /// Enables the RTC device with the lse as the clock
  46. fn enable_rtc(_bkp: &mut BackupDomain) {
  47. // NOTE: Safe RCC access because we are only accessing bdcr
  48. // and we have a &mut on BackupDomain
  49. let rcc = unsafe { &*RCC::ptr() };
  50. rcc.bdcr.modify(|_, w| {
  51. w
  52. // start the LSE oscillator
  53. .lseon()
  54. .set_bit()
  55. // Enable the RTC
  56. .rtcen()
  57. .set_bit()
  58. // Set the source of the RTC to LSE
  59. .rtcsel()
  60. .lse()
  61. })
  62. }
  63. /// Selects the frequency of the RTC Timer
  64. /// NOTE: Maximum frequency of 16384 Hz using the internal LSE
  65. pub fn select_frequency(&mut self, timeout: impl Into<Hertz>) {
  66. let frequency = timeout.into().0;
  67. // The manual says that the zero value for the prescaler is not recommended, thus the
  68. // minimum division factor is 2 (prescaler + 1)
  69. assert!(frequency <= LSE_HERTZ / 2);
  70. let prescaler = LSE_HERTZ / frequency - 1;
  71. self.perform_write(|s| {
  72. s.regs.prlh.write(|w| unsafe { w.bits(prescaler >> 16) });
  73. s.regs
  74. .prll
  75. .write(|w| unsafe { w.bits(prescaler as u16 as u32) });
  76. });
  77. }
  78. /// Set the current RTC counter value to the specified amount
  79. pub fn set_time(&mut self, counter_value: u32) {
  80. self.perform_write(|s| {
  81. s.regs
  82. .cnth
  83. .write(|w| unsafe { w.bits(counter_value >> 16) });
  84. s.regs
  85. .cntl
  86. .write(|w| unsafe { w.bits(counter_value as u16 as u32) });
  87. });
  88. }
  89. /**
  90. Sets the time at which an alarm will be triggered
  91. This also clears the alarm flag if it is set
  92. */
  93. pub fn set_alarm(&mut self, counter_value: u32) {
  94. // Set alarm time
  95. // See section 18.3.5 for explanation
  96. let alarm_value = counter_value - 1;
  97. // TODO: Remove this `allow` once these fields are made safe for stm32f100
  98. #[allow(unused_unsafe)]
  99. self.perform_write(|s| {
  100. s.regs
  101. .alrh
  102. .write(|w| unsafe { w.alrh().bits((alarm_value >> 16) as u16) });
  103. s.regs
  104. .alrl
  105. .write(|w| unsafe { w.alrl().bits(alarm_value as u16) });
  106. });
  107. self.clear_alarm_flag();
  108. }
  109. /// Enables the RTC interrupt to trigger when the counter reaches the alarm value. In addition,
  110. /// if the EXTI controller has been set up correctly, this function also enables the RTCALARM
  111. /// interrupt.
  112. pub fn listen_alarm(&mut self) {
  113. // Enable alarm interrupt
  114. self.perform_write(|s| {
  115. s.regs.crh.modify(|_, w| w.alrie().set_bit());
  116. })
  117. }
  118. /// Stops the RTC alarm from triggering the RTC and RTCALARM interrupts
  119. pub fn unlisten_alarm(&mut self) {
  120. // Disable alarm interrupt
  121. self.perform_write(|s| {
  122. s.regs.crh.modify(|_, w| w.alrie().clear_bit());
  123. })
  124. }
  125. /// Reads the current counter
  126. pub fn current_time(&self) -> u32 {
  127. // Wait for the APB1 interface to be ready
  128. while !self.regs.crl.read().rsf().bit() {}
  129. self.regs.cnth.read().bits() << 16 | self.regs.cntl.read().bits()
  130. }
  131. /// Enables triggering the RTC interrupt every time the RTC counter is increased
  132. pub fn listen_seconds(&mut self) {
  133. self.perform_write(|s| s.regs.crh.modify(|_, w| w.secie().set_bit()))
  134. }
  135. /// Disables the RTC second interrupt
  136. pub fn unlisten_seconds(&mut self) {
  137. self.perform_write(|s| s.regs.crh.modify(|_, w| w.secie().clear_bit()))
  138. }
  139. /// Clears the RTC second interrupt flag
  140. pub fn clear_second_flag(&mut self) {
  141. self.perform_write(|s| s.regs.crl.modify(|_, w| w.secf().clear_bit()))
  142. }
  143. /// Clears the RTC alarm interrupt flag
  144. pub fn clear_alarm_flag(&mut self) {
  145. self.perform_write(|s| s.regs.crl.modify(|_, w| w.alrf().clear_bit()))
  146. }
  147. /**
  148. Return `Ok(())` if the alarm flag is set, `Err(nb::WouldBlock)` otherwise.
  149. ```rust
  150. use nb::block;
  151. rtc.set_alarm(rtc.read_counts() + 5);
  152. // NOTE: Safe unwrap because Infallible can't be returned
  153. block!(rtc.wait_alarm()).unwrap();
  154. ```
  155. */
  156. pub fn wait_alarm(&mut self) -> nb::Result<(), Infallible> {
  157. if self.regs.crl.read().alrf().bit() {
  158. self.regs.crl.modify(|_, w| w.alrf().clear_bit());
  159. Ok(())
  160. } else {
  161. Err(nb::Error::WouldBlock)
  162. }
  163. }
  164. /**
  165. The RTC registers can not be written to at any time as documented on page
  166. 485 of the manual. Performing writes using this function ensures that
  167. the writes are done correctly.
  168. */
  169. fn perform_write(&mut self, func: impl Fn(&mut Self)) {
  170. // Wait for the last write operation to be done
  171. while !self.regs.crl.read().rtoff().bit() {}
  172. // Put the clock into config mode
  173. self.regs.crl.modify(|_, w| w.cnf().set_bit());
  174. // Perform the write operation
  175. func(self);
  176. // Take the device out of config mode
  177. self.regs.crl.modify(|_, w| w.cnf().clear_bit());
  178. // Wait for the write to be done
  179. while !self.regs.crl.read().rtoff().bit() {}
  180. }
  181. }