rcc.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. //! # Reset & Control Clock
  2. use core::cmp;
  3. use crate::pac::{rcc, PWR, RCC};
  4. use cast::u32;
  5. use crate::flash::ACR;
  6. use crate::time::Hertz;
  7. use crate::backup_domain::BackupDomain;
  8. /// Extension trait that constrains the `RCC` peripheral
  9. pub trait RccExt {
  10. /// Constrains the `RCC` peripheral so it plays nicely with the other abstractions
  11. fn constrain(self) -> Rcc;
  12. }
  13. impl RccExt for RCC {
  14. fn constrain(self) -> Rcc {
  15. Rcc {
  16. ahb: AHB { _0: () },
  17. apb1: APB1 { _0: () },
  18. apb2: APB2 { _0: () },
  19. cfgr: CFGR {
  20. hse: None,
  21. hclk: None,
  22. pclk1: None,
  23. pclk2: None,
  24. sysclk: None,
  25. adcclk: None,
  26. },
  27. bkp: BKP { _0: () },
  28. }
  29. }
  30. }
  31. /// Constrained RCC peripheral
  32. pub struct Rcc {
  33. /// AMBA High-performance Bus (AHB) registers
  34. pub ahb: AHB,
  35. /// Advanced Peripheral Bus 1 (APB1) registers
  36. pub apb1: APB1,
  37. /// Advanced Peripheral Bus 2 (APB2) registers
  38. pub apb2: APB2,
  39. pub cfgr: CFGR,
  40. pub bkp: BKP,
  41. }
  42. /// AMBA High-performance Bus (AHB) registers
  43. pub struct AHB {
  44. _0: (),
  45. }
  46. impl AHB {
  47. // TODO remove `allow`
  48. #[allow(dead_code)]
  49. pub(crate) fn enr(&mut self) -> &rcc::AHBENR {
  50. // NOTE(unsafe) this proxy grants exclusive access to this register
  51. unsafe { &(*RCC::ptr()).ahbenr }
  52. }
  53. }
  54. /// Advanced Peripheral Bus 1 (APB1) registers
  55. pub struct APB1 {
  56. _0: (),
  57. }
  58. impl APB1 {
  59. pub(crate) fn enr(&mut self) -> &rcc::APB1ENR {
  60. // NOTE(unsafe) this proxy grants exclusive access to this register
  61. unsafe { &(*RCC::ptr()).apb1enr }
  62. }
  63. pub(crate) fn rstr(&mut self) -> &rcc::APB1RSTR {
  64. // NOTE(unsafe) this proxy grants exclusive access to this register
  65. unsafe { &(*RCC::ptr()).apb1rstr }
  66. }
  67. }
  68. impl APB1 {
  69. /// Set power interface clock (PWREN) bit in RCC_APB1ENR
  70. pub fn set_pwren(&mut self) {
  71. self.enr().modify(|_r, w| w.pwren().set_bit())
  72. }
  73. }
  74. /// Advanced Peripheral Bus 2 (APB2) registers
  75. pub struct APB2 {
  76. _0: (),
  77. }
  78. impl APB2 {
  79. pub(crate) fn enr(&mut self) -> &rcc::APB2ENR {
  80. // NOTE(unsafe) this proxy grants exclusive access to this register
  81. unsafe { &(*RCC::ptr()).apb2enr }
  82. }
  83. pub(crate) fn rstr(&mut self) -> &rcc::APB2RSTR {
  84. // NOTE(unsafe) this proxy grants exclusive access to this register
  85. unsafe { &(*RCC::ptr()).apb2rstr }
  86. }
  87. }
  88. const HSI: u32 = 8_000_000; // Hz
  89. pub struct CFGR {
  90. hse: Option<u32>,
  91. hclk: Option<u32>,
  92. pclk1: Option<u32>,
  93. pclk2: Option<u32>,
  94. sysclk: Option<u32>,
  95. adcclk: Option<u32>,
  96. }
  97. impl CFGR {
  98. /// Uses HSE (external oscillator) instead of HSI (internal RC oscillator) as the clock source.
  99. /// Will result in a hang if an external oscillator is not connected or it fails to start.
  100. pub fn use_hse<F>(mut self, freq: F) -> Self
  101. where
  102. F: Into<Hertz>,
  103. {
  104. self.hse = Some(freq.into().0);
  105. self
  106. }
  107. /// Sets the desired frequency for the HCLK clock
  108. pub fn hclk<F>(mut self, freq: F) -> Self
  109. where
  110. F: Into<Hertz>,
  111. {
  112. self.hclk = Some(freq.into().0);
  113. self
  114. }
  115. /// Sets the desired frequency for the PCKL1 clock
  116. pub fn pclk1<F>(mut self, freq: F) -> Self
  117. where
  118. F: Into<Hertz>,
  119. {
  120. self.pclk1 = Some(freq.into().0);
  121. self
  122. }
  123. /// Sets the desired frequency for the PCLK2 clock
  124. pub fn pclk2<F>(mut self, freq: F) -> Self
  125. where
  126. F: Into<Hertz>,
  127. {
  128. self.pclk2 = Some(freq.into().0);
  129. self
  130. }
  131. /// Sets the desired frequency for the SYSCLK clock
  132. pub fn sysclk<F>(mut self, freq: F) -> Self
  133. where
  134. F: Into<Hertz>,
  135. {
  136. self.sysclk = Some(freq.into().0);
  137. self
  138. }
  139. /// Sets the desired frequency for the ADCCLK clock
  140. pub fn adcclk<F>(mut self, freq: F) -> Self
  141. where
  142. F: Into<Hertz>,
  143. {
  144. self.adcclk = Some(freq.into().0);
  145. self
  146. }
  147. pub fn freeze(self, acr: &mut ACR) -> Clocks {
  148. let pllsrcclk = self.hse.unwrap_or(HSI / 2);
  149. let pllmul = self.sysclk.unwrap_or(pllsrcclk) / pllsrcclk;
  150. let (pllmul_bits, sysclk) = if pllmul == 1 {
  151. (None, self.hse.unwrap_or(HSI))
  152. } else {
  153. #[cfg(not(feature = "connectivity"))]
  154. let pllmul = cmp::min(cmp::max(pllmul, 1), 16);
  155. #[cfg(feature = "connectivity")]
  156. let pllmul = cmp::min(cmp::max(pllmul, 4), 9);
  157. (Some(pllmul as u8 - 2), pllsrcclk * pllmul)
  158. };
  159. assert!(sysclk <= 72_000_000);
  160. let hpre_bits = self
  161. .hclk
  162. .map(|hclk| match sysclk / hclk {
  163. 0 => unreachable!(),
  164. 1 => 0b0111,
  165. 2 => 0b1000,
  166. 3..=5 => 0b1001,
  167. 6..=11 => 0b1010,
  168. 12..=39 => 0b1011,
  169. 40..=95 => 0b1100,
  170. 96..=191 => 0b1101,
  171. 192..=383 => 0b1110,
  172. _ => 0b1111,
  173. })
  174. .unwrap_or(0b0111);
  175. let hclk = if hpre_bits >= 0b1100 {
  176. sysclk / (1 << (hpre_bits - 0b0110))
  177. } else {
  178. sysclk / (1 << (hpre_bits - 0b0111))
  179. };
  180. assert!(hclk <= 72_000_000);
  181. let ppre1_bits = self
  182. .pclk1
  183. .map(|pclk1| match hclk / pclk1 {
  184. 0 => unreachable!(),
  185. 1 => 0b011,
  186. 2 => 0b100,
  187. 3..=5 => 0b101,
  188. 6..=11 => 0b110,
  189. _ => 0b111,
  190. })
  191. .unwrap_or(0b011);
  192. let ppre1 = 1 << (ppre1_bits - 0b011);
  193. let pclk1 = hclk / u32(ppre1);
  194. assert!(pclk1 <= 36_000_000);
  195. let ppre2_bits = self
  196. .pclk2
  197. .map(|pclk2| match hclk / pclk2 {
  198. 0 => unreachable!(),
  199. 1 => 0b011,
  200. 2 => 0b100,
  201. 3..=5 => 0b101,
  202. 6..=11 => 0b110,
  203. _ => 0b111,
  204. })
  205. .unwrap_or(0b011);
  206. let ppre2 = 1 << (ppre2_bits - 0b011);
  207. let pclk2 = hclk / u32(ppre2);
  208. assert!(pclk2 <= 72_000_000);
  209. // adjust flash wait states
  210. #[cfg(any(feature = "stm32f103", feature = "connectivity"))]
  211. unsafe {
  212. acr.acr().write(|w| {
  213. w.latency().bits(if sysclk <= 24_000_000 {
  214. 0b000
  215. } else if sysclk <= 48_000_000 {
  216. 0b001
  217. } else {
  218. 0b010
  219. })
  220. })
  221. }
  222. // the USB clock is only valid if an external crystal is used, the PLL is enabled, and the
  223. // PLL output frequency is a supported one.
  224. // usbpre == false: divide clock by 1.5, otherwise no division
  225. let (usbpre, usbclk_valid) = match (self.hse, pllmul_bits, sysclk) {
  226. (Some(_), Some(_), 72_000_000) => (false, true),
  227. (Some(_), Some(_), 48_000_000) => (true, true),
  228. _ => (true, false),
  229. };
  230. let apre_bits: u8 = self
  231. .adcclk
  232. .map(|adcclk| match pclk2 / adcclk {
  233. 0..=2 => 0b00,
  234. 3..=4 => 0b01,
  235. 5..=7 => 0b10,
  236. _ => 0b11,
  237. })
  238. .unwrap_or(0b11);
  239. let apre = (apre_bits + 1) << 1;
  240. let adcclk = pclk2 / u32(apre);
  241. assert!(adcclk <= 14_000_000);
  242. let rcc = unsafe { &*RCC::ptr() };
  243. if self.hse.is_some() {
  244. // enable HSE and wait for it to be ready
  245. rcc.cr.modify(|_, w| w.hseon().set_bit());
  246. while rcc.cr.read().hserdy().bit_is_clear() {}
  247. }
  248. if let Some(pllmul_bits) = pllmul_bits {
  249. // enable PLL and wait for it to be ready
  250. #[allow(unused_unsafe)]
  251. rcc.cfgr.modify(|_, w| unsafe {
  252. w.pllmul()
  253. .bits(pllmul_bits)
  254. .pllsrc()
  255. .bit(self.hse.is_some())
  256. });
  257. rcc.cr.modify(|_, w| w.pllon().set_bit());
  258. while rcc.cr.read().pllrdy().bit_is_clear() {}
  259. }
  260. // set prescalers and clock source
  261. #[cfg(feature = "connectivity")]
  262. rcc.cfgr.modify(|_, w| unsafe {
  263. w.adcpre().bits(apre_bits);
  264. w.ppre2()
  265. .bits(ppre2_bits)
  266. .ppre1()
  267. .bits(ppre1_bits)
  268. .hpre()
  269. .bits(hpre_bits)
  270. .otgfspre()
  271. .bit(usbpre)
  272. .sw()
  273. .bits(if pllmul_bits.is_some() {
  274. // PLL
  275. 0b10
  276. } else if self.hse.is_some() {
  277. // HSE
  278. 0b1
  279. } else {
  280. // HSI
  281. 0b0
  282. })
  283. });
  284. #[cfg(feature = "stm32f103")]
  285. rcc.cfgr.modify(|_, w| unsafe {
  286. w.adcpre().bits(apre_bits);
  287. w.ppre2()
  288. .bits(ppre2_bits)
  289. .ppre1()
  290. .bits(ppre1_bits)
  291. .hpre()
  292. .bits(hpre_bits)
  293. .usbpre()
  294. .bit(usbpre)
  295. .sw()
  296. .bits(if pllmul_bits.is_some() {
  297. // PLL
  298. 0b10
  299. } else if self.hse.is_some() {
  300. // HSE
  301. 0b1
  302. } else {
  303. // HSI
  304. 0b0
  305. })
  306. });
  307. #[cfg(any(feature = "stm32f100", feature = "stm32f101"))]
  308. rcc.cfgr.modify(|_, w| unsafe {
  309. w.adcpre().bits(apre_bits);
  310. w.ppre2()
  311. .bits(ppre2_bits)
  312. .ppre1()
  313. .bits(ppre1_bits)
  314. .hpre()
  315. .bits(hpre_bits)
  316. .sw()
  317. .bits(if pllmul_bits.is_some() {
  318. // PLL
  319. 0b10
  320. } else if self.hse.is_some() {
  321. // HSE
  322. 0b1
  323. } else {
  324. // HSI
  325. 0b0
  326. })
  327. });
  328. Clocks {
  329. hclk: Hertz(hclk),
  330. pclk1: Hertz(pclk1),
  331. pclk2: Hertz(pclk2),
  332. ppre1,
  333. ppre2,
  334. sysclk: Hertz(sysclk),
  335. adcclk: Hertz(adcclk),
  336. usbclk_valid,
  337. }
  338. }
  339. }
  340. pub struct BKP {
  341. _0: (),
  342. }
  343. impl BKP {
  344. /// Enables write access to the registers in the backup domain
  345. pub fn constrain(self, bkp: crate::pac::BKP, apb1: &mut APB1, pwr: &mut PWR) -> BackupDomain {
  346. // Enable the backup interface by setting PWREN and BKPEN
  347. apb1.enr()
  348. .modify(|_r, w| w.bkpen().set_bit().pwren().set_bit());
  349. // Enable access to the backup registers
  350. pwr.cr.modify(|_r, w| w.dbp().set_bit());
  351. BackupDomain { _regs: bkp }
  352. }
  353. }
  354. /// Frozen clock frequencies
  355. ///
  356. /// The existence of this value indicates that the clock configuration can no longer be changed
  357. #[derive(Clone, Copy)]
  358. pub struct Clocks {
  359. hclk: Hertz,
  360. pclk1: Hertz,
  361. pclk2: Hertz,
  362. ppre1: u8,
  363. ppre2: u8,
  364. sysclk: Hertz,
  365. adcclk: Hertz,
  366. usbclk_valid: bool,
  367. }
  368. impl Clocks {
  369. /// Returns the frequency of the AHB
  370. pub fn hclk(&self) -> Hertz {
  371. self.hclk
  372. }
  373. /// Returns the frequency of the APB1
  374. pub fn pclk1(&self) -> Hertz {
  375. self.pclk1
  376. }
  377. /// Returns the frequency of the APB2
  378. pub fn pclk2(&self) -> Hertz {
  379. self.pclk2
  380. }
  381. /// Returns the frequency of the APB1 Timers
  382. pub fn pclk1_tim(&self) -> Hertz {
  383. Hertz(self.pclk1.0 * if self.ppre1() == 1 { 1 } else { 2 })
  384. }
  385. /// Returns the frequency of the APB2 Timers
  386. pub fn pclk2_tim(&self) -> Hertz {
  387. Hertz(self.pclk2.0 * if self.ppre2() == 1 { 1 } else { 2 })
  388. }
  389. pub(crate) fn ppre1(&self) -> u8 {
  390. self.ppre1
  391. }
  392. // TODO remove `allow`
  393. #[allow(dead_code)]
  394. pub(crate) fn ppre2(&self) -> u8 {
  395. self.ppre2
  396. }
  397. /// Returns the system (core) frequency
  398. pub fn sysclk(&self) -> Hertz {
  399. self.sysclk
  400. }
  401. /// Returns the adc clock frequency
  402. pub fn adcclk(&self) -> Hertz {
  403. self.adcclk
  404. }
  405. /// Returns whether the USBCLK clock frequency is valid for the USB peripheral
  406. pub fn usbclk_valid(&self) -> bool {
  407. self.usbclk_valid
  408. }
  409. }
  410. pub trait GetBusFreq {
  411. fn get_frequency(clocks: &Clocks) -> Hertz;
  412. fn get_timer_frequency(clocks: &Clocks) -> Hertz {
  413. Self::get_frequency(clocks)
  414. }
  415. }
  416. impl GetBusFreq for AHB {
  417. fn get_frequency(clocks: &Clocks) -> Hertz {
  418. clocks.hclk
  419. }
  420. }
  421. impl GetBusFreq for APB1 {
  422. fn get_frequency(clocks: &Clocks) -> Hertz {
  423. clocks.pclk1
  424. }
  425. fn get_timer_frequency(clocks: &Clocks) -> Hertz {
  426. clocks.pclk1_tim()
  427. }
  428. }
  429. impl GetBusFreq for APB2 {
  430. fn get_frequency(clocks: &Clocks) -> Hertz {
  431. clocks.pclk2
  432. }
  433. fn get_timer_frequency(clocks: &Clocks) -> Hertz {
  434. clocks.pclk2_tim()
  435. }
  436. }
  437. pub(crate) mod sealed {
  438. /// Bus associated to peripheral
  439. pub trait RccBus {
  440. /// Bus type;
  441. type Bus;
  442. }
  443. }
  444. use sealed::RccBus;
  445. /// Enable/disable peripheral
  446. pub trait Enable: RccBus {
  447. fn enable(apb: &mut Self::Bus);
  448. fn disable(apb: &mut Self::Bus);
  449. }
  450. /// Reset peripheral
  451. pub trait Reset: RccBus {
  452. fn reset(apb: &mut Self::Bus);
  453. }
  454. macro_rules! bus {
  455. ($($PER:ident => ($apbX:ty, $peren:ident, $perrst:ident),)+) => {
  456. $(
  457. impl RccBus for crate::pac::$PER {
  458. type Bus = $apbX;
  459. }
  460. impl Enable for crate::pac::$PER {
  461. #[inline(always)]
  462. fn enable(apb: &mut Self::Bus) {
  463. apb.enr().modify(|_, w| w.$peren().set_bit());
  464. }
  465. #[inline(always)]
  466. fn disable(apb: &mut Self::Bus) {
  467. apb.enr().modify(|_, w| w.$peren().clear_bit());
  468. }
  469. }
  470. impl Reset for crate::pac::$PER {
  471. #[inline(always)]
  472. fn reset(apb: &mut Self::Bus) {
  473. apb.rstr().modify(|_, w| w.$perrst().set_bit());
  474. apb.rstr().modify(|_, w| w.$perrst().clear_bit());
  475. }
  476. }
  477. )+
  478. }
  479. }
  480. macro_rules! ahb_bus {
  481. ($($PER:ident => ($peren:ident),)+) => {
  482. $(
  483. impl RccBus for crate::pac::$PER {
  484. type Bus = AHB;
  485. }
  486. impl Enable for crate::pac::$PER {
  487. #[inline(always)]
  488. fn enable(apb: &mut Self::Bus) {
  489. apb.enr().modify(|_, w| w.$peren().set_bit());
  490. }
  491. #[inline(always)]
  492. fn disable(apb: &mut Self::Bus) {
  493. apb.enr().modify(|_, w| w.$peren().clear_bit());
  494. }
  495. }
  496. )+
  497. }
  498. }
  499. #[cfg(feature = "stm32f103")]
  500. bus! {
  501. ADC2 => (APB2, adc2en, adc2rst),
  502. CAN1 => (APB1, canen, canrst),
  503. }
  504. #[cfg(all(feature = "stm32f103", feature = "high",))]
  505. bus! {
  506. ADC3 => (APB2, adc3en, adc3rst),
  507. }
  508. bus! {
  509. ADC1 => (APB2, adc1en, adc1rst),
  510. AFIO => (APB2, afioen, afiorst),
  511. GPIOA => (APB2, iopaen, ioparst),
  512. GPIOB => (APB2, iopben, iopbrst),
  513. GPIOC => (APB2, iopcen, iopcrst),
  514. GPIOD => (APB2, iopden, iopdrst),
  515. GPIOE => (APB2, iopeen, ioperst),
  516. I2C1 => (APB1, i2c1en, i2c1rst),
  517. I2C2 => (APB1, i2c2en, i2c2rst),
  518. SPI1 => (APB2, spi1en, spi1rst),
  519. SPI2 => (APB1, spi2en, spi2rst),
  520. USART1 => (APB2, usart1en, usart1rst),
  521. USART2 => (APB1, usart2en, usart2rst),
  522. USART3 => (APB1, usart3en, usart3rst),
  523. WWDG => (APB1, wwdgen, wwdgrst),
  524. }
  525. #[cfg(any(feature = "high", feature = "connectivity"))]
  526. bus! {
  527. SPI3 => (APB1, spi3en, spi3rst),
  528. }
  529. ahb_bus! {
  530. CRC => (crcen),
  531. DMA1 => (dma1en),
  532. DMA2 => (dma2en),
  533. }
  534. #[cfg(feature = "high")]
  535. ahb_bus! {
  536. FSMC => (fsmcen),
  537. }
  538. bus! {
  539. TIM2 => (APB1, tim2en, tim2rst),
  540. TIM3 => (APB1, tim3en, tim3rst),
  541. }
  542. #[cfg(any(feature = "stm32f100", feature = "stm32f103", feature = "connectivity"))]
  543. bus! {
  544. TIM1 => (APB2, tim1en, tim1rst),
  545. }
  546. #[cfg(any(feature = "stm32f100", feature = "high", feature = "connectivity"))]
  547. bus! {
  548. TIM6 => (APB1, tim6en, tim6rst),
  549. }
  550. #[cfg(any(
  551. all(feature = "high", any(feature = "stm32f101", feature = "stm32f103")),
  552. any(feature = "stm32f100", feature = "connectivity")
  553. ))]
  554. bus! {
  555. TIM7 => (APB1, tim7en, tim7rst),
  556. }
  557. #[cfg(feature = "stm32f100")]
  558. bus! {
  559. TIM15 => (APB2, tim15en, tim15rst),
  560. TIM16 => (APB2, tim16en, tim16rst),
  561. TIM17 => (APB2, tim17en, tim17rst),
  562. }
  563. #[cfg(feature = "medium")]
  564. bus! {
  565. TIM4 => (APB1, tim4en, tim4rst),
  566. }
  567. #[cfg(any(feature = "high", feature = "connectivity"))]
  568. bus! {
  569. TIM5 => (APB1, tim5en, tim5rst),
  570. }
  571. #[cfg(any(feature = "xl", all(feature = "stm32f100", feature = "high",)))]
  572. bus! {
  573. TIM12 => (APB1, tim12en, tim12rst),
  574. TIM13 => (APB1, tim13en, tim13rst),
  575. TIM14 => (APB1, tim14en, tim14rst),
  576. }
  577. #[cfg(all(feature = "stm32f103", feature = "high",))]
  578. bus! {
  579. TIM8 => (APB2, tim8en, tim8rst),
  580. }
  581. #[cfg(feature = "xl")]
  582. bus! {
  583. TIM9 => (APB2, tim9en, tim9rst),
  584. TIM10 => (APB2, tim10en, tim10rst),
  585. TIM11 => (APB2, tim11en, tim11rst),
  586. }
  587. #[cfg(any(feature = "stm32f102", feature = "stm32f103"))]
  588. bus! {
  589. USB => (APB1, usben, usbrst),
  590. }