stm32f1-hal 0.12.3

HAL for the STM32F1 family
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! # Reset & Control Clock

mod enable;

#[cfg(any(feature = "f103", feature = "connectivity"))]
use crate::time::MHz;
use crate::{
    backup_domain::BackupDomain,
    common::holder::StaticHolder,
    flash::ACR,
    fugit::{HertzU32, RateExtU32},
    pac::{
        BKP, PWR, RCC,
        rcc::{self, RegisterBlock as RccRB},
    },
};
use core::ops::{Deref, DerefMut};

static CLOCKS: StaticHolder<Clocks> = StaticHolder::new(Clocks::new());

pub trait RccInit {
    fn init(self) -> Rcc;
}

impl RccInit for RCC {
    fn init(self) -> Rcc {
        CLOCKS.set(Clocks::default());
        Rcc { rb: self }
    }
}

/// Initialize RCC peripheral
///
/// Aquired by calling the [init](../trait.RccInit.html#init) method
/// on the Rcc struct from the `PAC`
///
/// ```rust
/// let dp = pac::Peripherals::take().unwrap();
/// let mut rcc = dp.RCC.init();
/// ```
pub struct Rcc {
    pub(crate) rb: RCC,
}

impl Rcc {
    /// Applies the clock configuration and returns a `Clocks` struct that signifies that the
    /// clocks are frozen, and contains the frequencies used. After this function is called,
    /// the clocks can not change
    ///
    /// Usage:
    ///
    /// ```rust
    /// let dp = pac::Peripherals::take().unwrap();
    /// let mut flash = dp.FLASH.init();
    /// let cfg = rcc::Config::hse(8.MHz()).sysclk(72.MHz());
    /// let mut rcc = dp.RCC.init().freeze(cfg, &mut flash.acr);
    /// ```
    #[allow(unused_variables)]
    #[inline(always)]
    pub fn freeze(self, cfg: impl Into<RawConfig>, acr: &mut ACR) -> Self {
        let cfg = cfg.into();
        let clocks = cfg.get_clocks();
        // adjust flash wait states
        #[cfg(any(feature = "f103", feature = "connectivity"))]
        unsafe {
            acr.acr().write(|w| {
                w.latency().bits(if clocks.sysclk <= MHz(24) {
                    0b000
                } else if clocks.sysclk <= MHz(48) {
                    0b001
                } else {
                    0b010
                })
            });
        }

        let rcc = unsafe { &*RCC::ptr() };

        if cfg.hse.is_some() {
            // enable HSE and wait for it to be ready

            rcc.cr().modify(|_, w| {
                if cfg.hse_bypass {
                    w.hsebyp().bypassed();
                }
                w.hseon().set_bit()
            });

            while rcc.cr().read().hserdy().bit_is_clear() {}
        }

        if let Some(pllmul_bits) = cfg.pllmul {
            // enable PLL and wait for it to be ready

            #[allow(unused_unsafe)]
            rcc.cfgr().modify(|_, w| unsafe {
                w.pllmul().bits(pllmul_bits).pllsrc().bit(cfg.hse.is_some())
            });

            rcc.cr().modify(|_, w| w.pllon().set_bit());

            while rcc.cr().read().pllrdy().bit_is_clear() {}
        }

        // set prescalers and clock source
        #[cfg(feature = "connectivity")]
        rcc.cfgr().modify(|_, w| unsafe {
            w.adcpre().variant(cfg.adcpre);
            w.ppre2().bits(cfg.ppre2 as u8);
            w.ppre1().bits(cfg.ppre1 as u8);
            w.hpre().bits(cfg.hpre as u8);
            w.otgfspre().variant(cfg.usbpre);
            w.sw().bits(if cfg.pllmul.is_some() {
                // PLL
                0b10
            } else if cfg.hse.is_some() {
                // HSE
                0b1
            } else {
                // HSI
                0b0
            })
        });

        #[cfg(feature = "f103")]
        rcc.cfgr().modify(|_, w| unsafe {
            w.adcpre().variant(cfg.adcpre);
            w.ppre2().bits(cfg.ppre2 as u8);
            w.ppre1().bits(cfg.ppre1 as u8);
            w.hpre().bits(cfg.hpre as u8);
            w.usbpre().variant(cfg.usbpre);
            w.sw().bits(if cfg.pllmul.is_some() {
                // PLL
                0b10
            } else {
                // HSE or HSI
                u8::from(cfg.hse.is_some())
            })
        });

        #[cfg(any(feature = "f100", feature = "f101"))]
        rcc.cfgr().modify(|_, w| unsafe {
            w.adcpre().variant(cfg.adcpre);
            w.ppre2().bits(cfg.ppre2 as u8);
            w.ppre1().bits(cfg.ppre1 as u8);
            w.hpre().bits(cfg.hpre as u8);
            w.sw().bits(if cfg.pllmul.is_some() {
                // PLL
                0b10
            } else if cfg.hse.is_some() {
                // HSE
                0b1
            } else {
                // HSI
                0b0
            })
        });

        CLOCKS.set(clocks);
        Self { rb: self.rb }
    }

    pub fn enable<T: Enable>(&mut self, _periph: &T) {
        T::enable(self);
    }

    pub fn reset<T: Reset>(&mut self, _periph: &T) {
        T::reset(self);
    }

    #[inline(always)]
    pub fn clocks(&self) -> &Clocks {
        unsafe { CLOCKS.get() }
    }
}

impl Deref for Rcc {
    type Target = RCC;
    fn deref(&self) -> &Self::Target {
        &self.rb
    }
}

impl DerefMut for Rcc {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.rb
    }
}

pub fn get_clocks() -> &'static Clocks {
    unsafe { CLOCKS.get() }
}

macro_rules! bus_struct {
    ($($busX:ident => ($EN:ident, $en:ident, $($RST:ident, $rst:ident,)? $doc:literal),)+) => {
        $(
            #[doc = $doc]
            #[non_exhaustive]
            pub struct $busX;

            impl $busX {
                pub(crate) fn enr(rcc: &RccRB) -> &rcc::$EN {
                    rcc.$en()
                }
                $(
                    pub(crate) fn rstr(rcc: &RccRB) -> &rcc::$RST {
                        rcc.$rst()
                    }
                )?
            }
        )+
    };
}

bus_struct! {
    APB1 => (APB1ENR, apb1enr, APB1RSTR, apb1rstr, "Advanced Peripheral Bus 1 (APB1) registers"),
    APB2 => (APB2ENR, apb2enr, APB2RSTR, apb2rstr, "Advanced Peripheral Bus 2 (APB2) registers"),
    AHB => (AHBENR, ahbenr, "Advanced High-performance Bus (AHB) registers"),
}

const HSI: u32 = 8_000_000; // Hz

/// Clock configuration
///
/// Used to configure the frequencies of the clocks present in the processor.
///
/// After setting all frequencies, call the [freeze](#method.freeze) function to
/// apply the configuration.
///
/// **NOTE**: Currently, it is not guaranteed that the exact frequencies selected will be
/// used, only frequencies close to it.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Config {
    hse: Option<u32>,
    hse_bypass: bool,
    hclk: Option<u32>,
    pclk1: Option<u32>,
    pclk2: Option<u32>,
    sysclk: Option<u32>,
    adcclk: Option<u32>,
}

impl Config {
    pub const DEFAULT: Self = Self {
        hse: None,
        hse_bypass: false,
        hclk: None,
        pclk1: None,
        pclk2: None,
        sysclk: None,
        adcclk: None,
    };

    pub fn hsi() -> Self {
        Self::DEFAULT
    }

    pub fn hse(freq: HertzU32) -> Self {
        Self::DEFAULT.use_hse(freq)
    }

    /// Uses HSE (external oscillator) instead of HSI (internal RC oscillator) as the clock source.
    /// Will result in a hang if an external oscillator is not connected or it fails to start.
    /// The frequency specified must be the frequency of the external oscillator
    #[inline(always)]
    pub fn use_hse(mut self, freq: HertzU32) -> Self {
        self.hse = Some(freq.raw());
        self
    }

    /// Bypasses the high-speed external oscillator and uses an external clock input on the OSC_IN
    /// pin.
    ///
    /// For this configuration, the OSC_IN pin should be connected to a clock source with a
    /// frequency specified in the call to use_hse(), and the OSC_OUT pin should not be connected.
    ///
    /// This function has no effect unless use_hse() is also called.
    pub fn bypass_hse_oscillator(self) -> Self {
        Self {
            hse_bypass: true,
            ..self
        }
    }

    /// Sets the desired frequency for the HCLK clock
    #[inline(always)]
    pub fn hclk(mut self, freq: HertzU32) -> Self {
        self.hclk = Some(freq.raw());
        self
    }

    /// Sets the desired frequency for the PCKL1 clock
    #[inline(always)]
    pub fn pclk1(mut self, freq: HertzU32) -> Self {
        self.pclk1 = Some(freq.raw());
        self
    }

    /// Sets the desired frequency for the PCLK2 clock
    #[inline(always)]
    pub fn pclk2(mut self, freq: HertzU32) -> Self {
        self.pclk2 = Some(freq.raw());
        self
    }

    /// Sets the desired frequency for the SYSCLK clock
    #[inline(always)]
    pub fn sysclk(mut self, freq: HertzU32) -> Self {
        self.sysclk = Some(freq.raw());
        self
    }

    /// Sets the desired frequency for the ADCCLK clock
    #[inline(always)]
    pub fn adcclk(mut self, freq: HertzU32) -> Self {
        self.adcclk = Some(freq.raw());
        self
    }
}

pub trait BkpInit {
    /// Enables write access to the registers in the backup domain
    fn init(self, pwr: &mut PWR, rcc: &mut RCC) -> BackupDomain;
}

impl BkpInit for BKP {
    fn init(self, pwr: &mut PWR, rcc: &mut RCC) -> BackupDomain {
        // Enable the backup interface by setting PWREN and BKPEN
        BKP::enable(rcc);
        PWR::enable(rcc);

        // Enable access to the backup registers
        pwr.cr().modify(|_r, w| w.dbp().set_bit());

        BackupDomain { _regs: self }
    }
}

/// Frozen clock frequencies
///
/// The existence of this value indicates that the clock configuration can no longer be changed
///
/// To acquire it, use the freeze function on the `rcc.cfgr` register. If desired, you can adjust
/// the frequencies using the methods on [cfgr](struct.CFGR.html) before calling freeze.
///
/// ```rust
/// let dp = pac::Peripherals::take().unwrap();
/// let mut rcc = dp.RCC.init();
/// let mut flash = dp.FLASH.init();
///
/// let clocks = rcc.cfgr.freeze(&mut flash.acr);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Clocks {
    hclk: HertzU32,
    pclk1: HertzU32,
    pclk2: HertzU32,
    ppre1: u8,
    ppre2: u8,
    sysclk: HertzU32,
    adcclk: HertzU32,
    #[cfg(any(feature = "f103", feature = "connectivity"))]
    usbclk_valid: bool,
}

impl Clocks {
    const fn new() -> Self {
        let freq = HertzU32::from_raw(HSI);
        Self {
            hclk: freq,
            pclk1: freq,
            pclk2: freq,
            ppre1: 1,
            ppre2: 1,
            sysclk: freq,
            adcclk: HertzU32::from_raw(HSI / 2),
            #[cfg(any(feature = "f103", feature = "connectivity"))]
            usbclk_valid: false,
        }
    }
}

impl Default for Clocks {
    fn default() -> Clocks {
        Self::new()
    }
}

impl Clocks {
    /// Returns the frequency of the AHB
    pub const fn hclk(&self) -> HertzU32 {
        self.hclk
    }

    /// Returns the frequency of the APB1
    pub const fn pclk1(&self) -> HertzU32 {
        self.pclk1
    }

    /// Returns the frequency of the APB2
    pub const fn pclk2(&self) -> HertzU32 {
        self.pclk2
    }

    /// Returns the frequency of the APB1 Timers
    pub const fn pclk1_tim(&self) -> HertzU32 {
        HertzU32::from_raw(self.pclk1.raw() * if self.ppre1() == 1 { 1 } else { 2 })
    }

    /// Returns the frequency of the APB2 Timers
    pub const fn pclk2_tim(&self) -> HertzU32 {
        HertzU32::from_raw(self.pclk2.raw() * if self.ppre2() == 1 { 1 } else { 2 })
    }

    pub(crate) const fn ppre1(&self) -> u8 {
        self.ppre1
    }

    // TODO remove `allow`
    #[allow(dead_code)]
    pub(crate) const fn ppre2(&self) -> u8 {
        self.ppre2
    }

    /// Returns the system (core) frequency
    pub const fn sysclk(&self) -> HertzU32 {
        self.sysclk
    }

    /// Returns the adc clock frequency
    pub const fn adcclk(&self) -> HertzU32 {
        self.adcclk
    }

    /// Returns whether the USBCLK clock frequency is valid for the USB peripheral
    #[cfg(any(feature = "f103", feature = "connectivity"))]
    pub const fn usbclk_valid(&self) -> bool {
        self.usbclk_valid
    }
}

/// Frequency on bus that peripheral is connected in
pub trait BusClock {
    /// Calculates frequency depending on `Clock` state
    fn clock(clocks: &Clocks) -> HertzU32;
}

impl BusClock for AHB {
    #[inline(always)]
    fn clock(clocks: &Clocks) -> HertzU32 {
        clocks.hclk
    }
}

impl BusClock for APB1 {
    #[inline(always)]
    fn clock(clocks: &Clocks) -> HertzU32 {
        clocks.pclk1
    }
}

impl BusClock for APB2 {
    #[inline(always)]
    fn clock(clocks: &Clocks) -> HertzU32 {
        clocks.pclk2
    }
}

pub trait GetClock: RccBus {
    fn get_clock(&self) -> HertzU32;
}

impl<T> GetClock for T
where
    T: RccBus,
    T::Bus: BusClock,
{
    #[inline(always)]
    fn get_clock(&self) -> HertzU32 {
        T::Bus::clock(unsafe { CLOCKS.get() })
    }
}

/// Frequency on bus that timer is connected in
pub trait BusTimerClock {
    /// Calculates base frequency of timer depending on `Clock` state
    fn timer_clock(clocks: &Clocks) -> HertzU32;
}

impl BusTimerClock for APB1 {
    #[inline(always)]
    fn timer_clock(clocks: &Clocks) -> HertzU32 {
        clocks.pclk1_tim()
    }
}

impl BusTimerClock for APB2 {
    #[inline(always)]
    fn timer_clock(clocks: &Clocks) -> HertzU32 {
        clocks.pclk2_tim()
    }
}

pub trait GetTimerClock: RccBus {
    fn get_timer_clock(&self) -> HertzU32;
}

impl<T> GetTimerClock for T
where
    T: RccBus,
    T::Bus: BusTimerClock,
{
    #[inline(always)]
    fn get_timer_clock(&self) -> HertzU32 {
        T::Bus::timer_clock(unsafe { CLOCKS.get() })
    }
}

/// Bus associated to peripheral
pub trait RccBus {
    /// Bus type;
    type Bus;
}

/// Enable/disable peripheral
pub trait Enable: RccBus {
    /// Enables peripheral
    fn enable(rcc: &mut RCC);

    /// Disables peripheral
    fn disable(rcc: &mut RCC);

    /// Check if peripheral enabled
    fn is_enabled() -> bool;

    /// Check if peripheral disabled
    #[inline]
    fn is_disabled() -> bool {
        !Self::is_enabled()
    }

    /// # Safety
    ///
    /// Enables peripheral. Takes access to RCC internally
    unsafe fn enable_unchecked() {
        let mut rcc = unsafe { RCC::steal() };
        Self::enable(&mut rcc);
    }

    /// # Safety
    ///
    /// Disables peripheral. Takes access to RCC internally
    unsafe fn disable_unchecked() {
        let mut rcc = unsafe { RCC::steal() };
        Self::disable(&mut rcc);
    }
}

/// Reset peripheral
pub trait Reset: RccBus {
    /// Resets peripheral
    fn reset(rcc: &mut RCC);

    /// # Safety
    ///
    /// Resets peripheral. Takes access to RCC internally
    unsafe fn reset_unchecked() {
        let mut rcc = unsafe { RCC::steal() };
        Self::reset(&mut rcc);
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RawConfig {
    pub hse: Option<u32>,
    pub hse_bypass: bool,
    pub pllmul: Option<u8>,
    pub hpre: HPre,
    pub ppre1: PPre,
    pub ppre2: PPre,
    #[cfg(any(feature = "f103", feature = "connectivity"))]
    pub usbpre: UsbPre,
    pub adcpre: AdcPre,
    pub allow_overclock: bool,
}

impl Default for RawConfig {
    fn default() -> Self {
        Self {
            hse: None,
            hse_bypass: false,
            pllmul: None,
            hpre: HPre::Div1,
            ppre1: PPre::Div1,
            ppre2: PPre::Div1,
            #[cfg(any(feature = "f103", feature = "connectivity"))]
            usbpre: UsbPre::Div1_5,
            adcpre: AdcPre::Div2,
            allow_overclock: false,
        }
    }
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HPre {
    /// SYSCLK not divided
    Div1 = 7,
    /// SYSCLK divided by 2
    Div2 = 8,
    /// SYSCLK divided by 4
    Div4 = 9,
    /// SYSCLK divided by 8
    Div8 = 10,
    /// SYSCLK divided by 16
    Div16 = 11,
    /// SYSCLK divided by 64
    Div64 = 12,
    /// SYSCLK divided by 128
    Div128 = 13,
    /// SYSCLK divided by 256
    Div256 = 14,
    /// SYSCLK divided by 512
    Div512 = 15,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PPre {
    /// HCLK not divided
    Div1 = 3,
    /// HCLK divided by 2
    Div2 = 4,
    /// HCLK divided by 4
    Div4 = 5,
    /// HCLK divided by 8
    Div8 = 6,
    /// HCLK divided by 16
    Div16 = 7,
}

#[cfg(feature = "f103")]
pub type UsbPre = rcc::cfgr::USBPRE;
#[cfg(feature = "connectivity")]
pub type UsbPre = rcc::cfgr::OTGFSPRE;
pub type AdcPre = rcc::cfgr::ADCPRE;

impl From<Config> for RawConfig {
    #[inline(always)]
    fn from(cfgr: Config) -> Self {
        Self::from_cfgr(cfgr)
    }
}

impl RawConfig {
    pub const fn from_cfgr(cfgr: Config) -> Self {
        let hse = cfgr.hse;
        let hse_bypass = cfgr.hse_bypass;
        let pllsrcclk = if let Some(hse) = hse { hse } else { HSI / 2 };

        let pllmul = if let Some(sysclk) = cfgr.sysclk {
            sysclk / pllsrcclk
        } else {
            1
        };

        let (pllmul_bits, sysclk) = if pllmul == 1 {
            (None, if let Some(hse) = hse { hse } else { HSI })
        } else {
            #[cfg(not(feature = "connectivity"))]
            let pllmul = match pllmul {
                1..=16 => pllmul,
                0 => 1,
                _ => 16,
            };

            #[cfg(feature = "connectivity")]
            let pllmul = match pllmul {
                4..=9 => pllmul,
                0..=3 => 4,
                _ => 9,
            };

            (Some(pllmul as u8 - 2), pllsrcclk * pllmul)
        };

        let hpre_bits = if let Some(hclk) = cfgr.hclk {
            match sysclk / hclk {
                0..=1 => HPre::Div1,
                2 => HPre::Div2,
                3..=5 => HPre::Div4,
                6..=11 => HPre::Div8,
                12..=39 => HPre::Div16,
                40..=95 => HPre::Div64,
                96..=191 => HPre::Div128,
                192..=383 => HPre::Div256,
                _ => HPre::Div512,
            }
        } else {
            HPre::Div1
        };

        let hclk = if hpre_bits as u8 >= 0b1100 {
            sysclk / (1 << (hpre_bits as u8 - 0b0110))
        } else {
            sysclk / (1 << (hpre_bits as u8 - 0b0111))
        };

        let pclk1 = if let Some(pclk1) = cfgr.pclk1 {
            pclk1
        } else if hclk < 36_000_000 {
            hclk
        } else {
            36_000_000
        };
        let ppre1_bits = match hclk.div_ceil(pclk1) {
            0 | 1 => PPre::Div1,
            2 => PPre::Div2,
            3..=5 => PPre::Div4,
            6..=11 => PPre::Div8,
            _ => PPre::Div16,
        };

        let ppre2_bits = if let Some(pclk2) = cfgr.pclk2 {
            match hclk / pclk2 {
                0..=1 => PPre::Div1,
                2 => PPre::Div2,
                3..=5 => PPre::Div4,
                6..=11 => PPre::Div8,
                _ => PPre::Div16,
            }
        } else {
            PPre::Div1
        };

        let ppre2 = 1 << (ppre2_bits as u8 - 0b011);
        let pclk2 = hclk / (ppre2 as u32);

        // usbpre == false: divide clock by 1.5, otherwise no division
        #[cfg(any(feature = "f103", feature = "connectivity"))]
        let usbpre = match (hse, pllmul_bits, sysclk) {
            (Some(_), Some(_), 72_000_000) => UsbPre::Div1_5,
            _ => UsbPre::Div1,
        };

        let apre_bits = if let Some(adcclk) = cfgr.adcclk {
            match pclk2 / adcclk {
                0..=2 => AdcPre::Div2,
                3..=4 => AdcPre::Div4,
                5..=7 => AdcPre::Div6,
                _ => AdcPre::Div8,
            }
        } else {
            AdcPre::Div8
        };

        Self {
            hse,
            hse_bypass,
            pllmul: pllmul_bits,
            hpre: hpre_bits,
            ppre1: ppre1_bits,
            ppre2: ppre2_bits,
            #[cfg(any(feature = "f103", feature = "connectivity"))]
            usbpre,
            adcpre: apre_bits,
            allow_overclock: false,
        }
    }

    // NOTE: to maintain the invariant that the existence of a Clocks
    // value implies frozen clocks, this function must not be pub.
    fn get_clocks(&self) -> Clocks {
        let sysclk = if let Some(pllmul_bits) = self.pllmul {
            let pllsrcclk = if let Some(hse) = self.hse {
                hse
            } else {
                HSI / 2
            };
            pllsrcclk * (pllmul_bits as u32 + 2)
        } else if let Some(hse) = self.hse {
            hse
        } else {
            HSI
        };

        let hclk = if self.hpre as u8 >= 0b1100 {
            sysclk / (1 << (self.hpre as u8 - 0b0110))
        } else {
            sysclk / (1 << (self.hpre as u8 - 0b0111))
        };

        let ppre1 = 1 << (self.ppre1 as u8 - 0b011);
        let pclk1 = hclk / (ppre1 as u32);

        let ppre2 = 1 << (self.ppre2 as u8 - 0b011);
        let pclk2 = hclk / (ppre2 as u32);

        let apre = (self.adcpre as u8 + 1) << 1;
        let adcclk = pclk2 / (apre as u32);

        // the USB clock is only valid if an external crystal is used, the PLL is enabled, and the
        // PLL output frequency is a supported one.
        #[cfg(any(feature = "f103", feature = "connectivity"))]
        let usbclk_valid = matches!(
            (self.hse, self.pllmul, sysclk),
            (Some(_), Some(_), 72_000_000) | (Some(_), Some(_), 48_000_000)
        );

        assert!(
            self.allow_overclock
                || (sysclk <= 72_000_000
                    && hclk <= 72_000_000
                    && pclk1 <= 36_000_000
                    && pclk2 <= 72_000_000
                    && adcclk <= 14_000_000)
        );

        Clocks {
            hclk: hclk.Hz(),
            pclk1: pclk1.Hz(),
            pclk2: pclk2.Hz(),
            ppre1,
            ppre2,
            sysclk: sysclk.Hz(),
            adcclk: adcclk.Hz(),
            #[cfg(any(feature = "f103", feature = "connectivity"))]
            usbclk_valid,
        }
    }
}

#[test]
fn rcc_config_usb() {
    let cfgr = Config::default()
        .use_hse(8.MHz())
        .sysclk(48.MHz())
        .pclk1(24.MHz());

    let config = RawConfig::from_cfgr(cfgr);
    let config_expected = RawConfig {
        hse: Some(8_000_000),
        hse_bypass: false,
        pllmul: Some(4),
        hpre: HPre::Div1,
        ppre1: PPre::Div2,
        ppre2: PPre::Div1,
        #[cfg(any(feature = "f103", feature = "connectivity"))]
        usbpre: UsbPre::Div1,
        adcpre: AdcPre::Div8,
        allow_overclock: false,
    };
    assert_eq!(config, config_expected);

    let clocks = config.get_clocks();
    let clocks_expected = Clocks {
        hclk: 48.MHz(),
        pclk1: 24.MHz(),
        pclk2: 48.MHz(),
        ppre1: 2,
        ppre2: 1,
        sysclk: 48.MHz(),
        adcclk: 6.MHz(),
        #[cfg(any(feature = "f103", feature = "connectivity"))]
        usbclk_valid: true,
    };
    assert_eq!(clocks, clocks_expected);
}