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
//! Timers

// TODO: on the h7x3 at least, only TIM2, TIM3, TIM4, TIM5 can support 32 bits.
// TIM1 is 16 bit.

use core::convert::TryFrom;
use core::marker::PhantomData;

use crate::hal::timer::{CountDown, Periodic};

use crate::stm32::{lptim1, lptim3};
use crate::stm32::{LPTIM1, LPTIM2, LPTIM3};
#[cfg(not(feature = "rm0455"))]
use crate::stm32::{LPTIM4, LPTIM5};

use crate::stm32::{
    TIM1, TIM12, TIM13, TIM14, TIM15, TIM16, TIM17, TIM2, TIM3, TIM4, TIM5,
    TIM6, TIM7, TIM8,
};

use cast::{u16, u32};
use nb;
use void::Void;

#[cfg(feature = "rm0455")]
use crate::stm32::rcc::{cdccip2r as ccip2r, srdccipr};
#[cfg(not(feature = "rm0455"))]
use crate::stm32::rcc::{d2ccip2r as ccip2r, d3ccipr as srdccipr};

use crate::rcc::{rec, CoreClocks, ResetEnable};
use crate::stm32;
use crate::time::Hertz;
use stm32h7::Variant::Val;

/// Associate clocks with timers
pub trait GetClk {
    fn get_clk(clocks: &CoreClocks) -> Option<Hertz>;
}

/// Timers with CK_INT derived from rcc_tim[xy]_ker_ck
macro_rules! impl_tim_ker_ck {
    ($($ckX:ident: $($TIMX:ident),+)+) => {
        $(
            $(
                impl GetClk for $TIMX {
                    fn get_clk(clocks: &CoreClocks) -> Option<Hertz> {
                        Some(clocks.$ckX())
                    }
                }
            )+
        )+
    }
}
impl_tim_ker_ck! {
    timx_ker_ck: TIM2, TIM3, TIM4, TIM5, TIM6, TIM7, TIM12, TIM13, TIM14
    timy_ker_ck: TIM1, TIM8, TIM15, TIM16, TIM17
}

/// LPTIM1 Kernel Clock
impl GetClk for LPTIM1 {
    /// Current kernel clock
    fn get_clk(clocks: &CoreClocks) -> Option<Hertz> {
        // unsafe: read only
        #[cfg(not(feature = "rm0455"))]
        let ccip2r = &unsafe { &*stm32::RCC::ptr() }.d2ccip2r;
        #[cfg(feature = "rm0455")]
        let ccip2r = &unsafe { &*stm32::RCC::ptr() }.cdccip2r;

        match ccip2r.read().lptim1sel().variant() {
            Val(ccip2r::LPTIM1SEL_A::RCC_PCLK1) => Some(clocks.pclk1()),
            Val(ccip2r::LPTIM1SEL_A::PLL2_P) => clocks.pll2_p_ck(),
            Val(ccip2r::LPTIM1SEL_A::PLL3_R) => clocks.pll3_r_ck(),
            Val(ccip2r::LPTIM1SEL_A::LSE) => unimplemented!(),
            Val(ccip2r::LPTIM1SEL_A::LSI) => unimplemented!(),
            Val(ccip2r::LPTIM1SEL_A::PER) => clocks.per_ck(),
            _ => unreachable!(),
        }
    }
}
/// LPTIM2 Kernel Clock
impl GetClk for LPTIM2 {
    /// Current kernel clock
    fn get_clk(clocks: &CoreClocks) -> Option<Hertz> {
        // unsafe: read only
        #[cfg(not(feature = "rm0455"))]
        let srdccipr = &unsafe { &*stm32::RCC::ptr() }.d3ccipr;
        #[cfg(feature = "rm0455")]
        let srdccipr = &unsafe { &*stm32::RCC::ptr() }.srdccipr;

        match srdccipr.read().lptim2sel().variant() {
            Val(srdccipr::LPTIM2SEL_A::RCC_PCLK4) => Some(clocks.pclk4()),
            Val(srdccipr::LPTIM2SEL_A::PLL2_P) => clocks.pll2_p_ck(),
            Val(srdccipr::LPTIM2SEL_A::PLL3_R) => clocks.pll3_r_ck(),
            Val(srdccipr::LPTIM2SEL_A::LSE) => unimplemented!(),
            Val(srdccipr::LPTIM2SEL_A::LSI) => unimplemented!(),
            Val(srdccipr::LPTIM2SEL_A::PER) => clocks.per_ck(),
            _ => unreachable!(),
        }
    }
}

#[cfg(feature = "rm0455")]
/// LPTIM3 Kernel Clock
impl GetClk for LPTIM3 {
    /// Current kernel clock
    fn get_clk(clocks: &CoreClocks) -> Option<Hertz> {
        // unsafe: read only
        let srdccipr = &unsafe { &*stm32::RCC::ptr() }.srdccipr;

        match srdccipr.read().lptim3sel().bits() {
            0 => Some(clocks.pclk4()),
            1 => clocks.pll2_p_ck(),
            2 => clocks.pll3_r_ck(),
            3 => unimplemented!(),
            4 => unimplemented!(),
            5 => clocks.per_ck(),
            _ => unreachable!(),
        }
    }
}

#[cfg(not(feature = "rm0455"))]
/// LPTIM345 Kernel Clock
macro_rules! impl_clk_lptim345 {
	($($TIMX:ident),+) => {
	    $(
            impl GetClk for $TIMX {
                /// Current kernel clock
                fn get_clk(clocks: &CoreClocks) -> Option<Hertz> {
                    // unsafe: read only
                    let d3ccipr = &unsafe { &*stm32::RCC::ptr() }.d3ccipr;

                    match d3ccipr.read().lptim345sel().variant() {
                        Val(srdccipr::LPTIM345SEL_A::RCC_PCLK4) => Some(clocks.pclk4()),
                        Val(srdccipr::LPTIM345SEL_A::PLL2_P) => clocks.pll2_p_ck(),
                        Val(srdccipr::LPTIM345SEL_A::PLL3_R) => clocks.pll3_r_ck(),
                        Val(srdccipr::LPTIM345SEL_A::LSE) => unimplemented!(),
                        Val(srdccipr::LPTIM345SEL_A::LSI) => unimplemented!(),
                        Val(srdccipr::LPTIM345SEL_A::PER) => clocks.per_ck(),
                        _ => unreachable!(),
                    }
                }
            }
        )+
    }
}
#[cfg(not(feature = "rm0455"))]
impl_clk_lptim345! { LPTIM3, LPTIM4, LPTIM5 }

/// Enabled LPTIM (type state)
pub struct Enabled;
/// Disabled LPTIM (type state)
pub struct Disabled;

/// External trait for hardware timers
pub trait TimerExt<TIM> {
    type Rec: ResetEnable;

    /// Configures a periodic timer
    ///
    /// Generates an overflow event at the `timeout` frequency.
    fn timer<T>(self, timeout: T, prec: Self::Rec, clocks: &CoreClocks) -> TIM
    where
        T: Into<Hertz>;

    /// Configures the timer to count up at the given frequency
    ///
    /// Counts from 0 to the counter's maximum value, then repeats.
    /// Because this only uses the timer prescaler, the frequency
    /// is rounded to a multiple of the timer's kernel clock.
    fn tick_timer<T>(
        self,
        frequency: T,
        prec: Self::Rec,
        clocks: &CoreClocks,
    ) -> TIM
    where
        T: Into<Hertz>;
}

/// Hardware timers
#[derive(Debug)]
pub struct Timer<TIM> {
    clk: u32,
    tim: TIM,
}

/// Low power hardware timers
#[derive(Debug)]
pub struct LpTimer<TIM, ED> {
    clk: u32,
    tim: TIM,
    timeout: Hertz,
    _enabled: PhantomData<ED>,
}

/// Timer Events
///
/// Each event is a possible interrupt source, if enabled
pub enum Event {
    /// Timer timed out / count down ended
    TimeOut,
}

macro_rules! hal {
    ($($TIMX:ident: ($timX:ident, $Rec:ident, $cntType:ty),)+) => {
        $(
            impl Periodic for Timer<$TIMX> {}

            impl CountDown for Timer<$TIMX> {
                type Time = Hertz;

                fn start<T>(&mut self, timeout: T)
                where
                    T: Into<Hertz>,
                {
                    // Pause
                    self.pause();

                    // Reset counter
                    self.tim.cnt.reset();

                    // UEV event occours on next overflow
                    self.tim.cr1.modify(|_, w| w.urs().counter_only());
                    self.clear_uif_bit();

                    // Set PSC and ARR
                    self.set_freq(timeout);

                    // Generate an update event to force an update of the ARR register. This ensures
                    // the first timer cycle is of the specified duration.
                    self.tim.egr.write(|w| w.ug().set_bit());

                    // Start counter
                    self.resume()
                }

                fn wait(&mut self) -> nb::Result<(), Void> {
                    if self.tim.sr.read().uif().bit_is_clear() {
                        Err(nb::Error::WouldBlock)
                    } else {
                        self.clear_uif_bit();
                        Ok(())
                    }
                }
            }

            impl TimerExt<Timer<$TIMX>> for $TIMX {
                type Rec = rec::$Rec;

                fn timer<T>(self, timeout: T,
                            prec: Self::Rec, clocks: &CoreClocks
                ) -> Timer<$TIMX>
                where
                    T: Into<Hertz>,
                {
                    let mut timer = Timer::$timX(self, prec, clocks);
                    timer.start(timeout);
                    timer
                }

                fn tick_timer<T>(self, frequency: T,
                                 prec: Self::Rec, clocks: &CoreClocks
                ) -> Timer<$TIMX>
                where
                    T: Into<Hertz>,
                {
                    let mut timer = Timer::$timX(self, prec, clocks);

                    timer.pause();

                    // UEV event occours on next overflow
                    timer.tim.cr1.modify(|_, w| w.urs().counter_only());
                    timer.clear_uif_bit();

                    // Set PSC and ARR
                    timer.set_tick_freq(frequency);

                    // Generate an update event to force an update of the ARR
                    // register. This ensures the first timer cycle is of the
                    // specified duration.
                    timer.tim.egr.write(|w| w.ug().set_bit());

                    // Start counter
                    timer.resume();

                    timer
                }
            }

            impl Timer<$TIMX> {
                /// Configures a TIM peripheral as a periodic count down timer,
                /// without starting it
                pub fn $timX(tim: $TIMX, prec: rec::$Rec, clocks: &CoreClocks) -> Self
                {
                    // enable and reset peripheral to a clean state
                    prec.enable().reset();

                    let clk = $TIMX::get_clk(clocks)
                        .expect("Timer input clock not running!").0;

                    Timer {
                        clk,
                        tim,
                    }
                }

                /// Configures the timer's frequency and counter reload value
                /// so that it underflows at the timeout's frequency
                pub fn set_freq<T>(&mut self, timeout: T)
                where
                    T: Into<Hertz>,
                {
                    let timeout = timeout.into();
                    let ticks = self.clk / timeout.0;

                    self.set_timeout_ticks(ticks);
                }

                /// Sets the timer period from a time duration
                ///
                /// ```
                /// // Set timeout to 100ms
                /// timer.set_timeout(100.ms());
                /// ```
                ///
                /// Alternatively, the duration can be set using the
                /// core::time::Duration type
                ///
                /// ```
                /// let duration = core::time::Duration::from_nanos(2_500);
                ///
                /// // Set timeout to 2.5µs
                /// timer.set_timeout(duration);
                /// ```
                pub fn set_timeout<T>(&mut self, timeout: T)
                where
                    T: Into<core::time::Duration>
                {
                    const NANOS_PER_SECOND: u64 = 1_000_000_000;
                    let timeout = timeout.into();

                    let clk = self.clk as u64;
                    let ticks = u32::try_from(
                        clk * timeout.as_secs() +
                        clk * u64::from(timeout.subsec_nanos()) / NANOS_PER_SECOND,
                    )
                    .unwrap_or(u32::max_value());

                    self.set_timeout_ticks(ticks.max(1));
                }

                fn set_timeout_ticks(&mut self, ticks: u32) {
                    let psc = u16((ticks - 1) / (1 << 16)).unwrap();
                    self.tim.psc.write(|w| w.psc().bits(psc));

                    let arr = u16(ticks / u32(psc + 1)).unwrap();
                    self.tim.arr.write(|w| unsafe { w.bits(u32(arr)) });
                }

                /// Configures the timer to count up at the given frequency
                ///
                /// Counts from 0 to the counter's maximum value, then repeats.
                /// Because this only uses the timer prescaler, the frequency
                /// is rounded to a multiple of the timer's kernel clock.
                pub fn set_tick_freq<T>(&mut self, frequency: T)
                where
                    T: Into<Hertz>,
                {
                    let frequency = frequency.into();
                    let div = self.clk / frequency.0;

                    let psc = u16(div - 1).unwrap();
                    self.tim.psc.write(|w| w.psc().bits(psc));

                    let counter_max = u32(<$cntType>::MAX);
                    self.tim.arr.write(|w| unsafe { w.bits(counter_max) });
                }

                /// Applies frequency/timeout changes immediately
                ///
                /// The timer will normally update its prescaler and auto-reload
                /// value when its counter overflows. This function causes
                /// those changes to happen immediately. Also clears the counter.
                pub fn apply_freq(&mut self) {
                    self.tim.egr.write(|w| w.ug().set_bit());
                }

                /// Clear uif bit
                pub fn clear_uif_bit(&mut self) {
                    self.tim.sr.modify(|_, w| w.uif().clear_bit());
                }

                /// Pauses the TIM peripheral
                pub fn pause(&mut self) {
                    self.tim.cr1.modify(|_, w| w.cen().clear_bit());
                }

                /// Resume (unpause) the TIM peripheral
                pub fn resume(&mut self) {
                    self.tim.cr1.modify(|_, w| w.cen().set_bit());
                }

                /// Reset the counter of the TIM peripheral
                pub fn reset_counter(&mut self) {
                    self.tim.cnt.reset();
                }

                /// Read the counter of the TIM peripheral
                pub fn counter(&self) -> u32 {
                    self.tim.cnt.read().bits()
                }

                /// Start listening for `event`
                pub fn listen(&mut self, event: Event) {
                    match event {
                        Event::TimeOut => {
                            // Enable update event interrupt
                            self.tim.dier.write(|w| w.uie().set_bit());
                        }
                    }
                }

                /// Stop listening for `event`
                pub fn unlisten(&mut self, event: Event) {
                    match event {
                        Event::TimeOut => {
                            // Enable update event interrupt
                            self.tim.dier.write(|w| w.uie().clear_bit());
                        }
                    }
                }

                /// Clears interrupt flag
                pub fn clear_irq(&mut self) {
                    self.tim.sr.modify(|_, w| {
                        // Clears timeout event
                        w.uif().clear_bit()
                    });
                }

                /// Releases the TIM peripheral
                pub fn free(mut self) -> ($TIMX, rec::$Rec) {
                    // pause counter
                    self.pause();

                    (self.tim, rec::$Rec { _marker: PhantomData })
                }
            }
        )+
    }
}

hal! {
    // Advanced-control
    TIM1: (tim1, Tim1, u16),
    TIM8: (tim8, Tim8, u16),

    // General-purpose
    TIM2: (tim2, Tim2, u32),
    TIM3: (tim3, Tim3, u16),
    TIM4: (tim4, Tim4, u16),
    TIM5: (tim5, Tim5, u32),

    // Basic
    TIM6: (tim6, Tim6, u16),
    TIM7: (tim7, Tim7, u16),

    // General-purpose
    TIM12: (tim12, Tim12, u16),
    TIM13: (tim13, Tim13, u16),
    TIM14: (tim14, Tim14, u16),

    // General-purpose
    TIM15: (tim15, Tim15, u16),
    TIM16: (tim16, Tim16, u16),
    TIM17: (tim17, Tim17, u16),
}

macro_rules! lptim_hal {
    ($($TIMX:ident: ($timx:ident, $Rec:ident, $timXpac:ident),)+) => {
        $(
            impl Periodic for LpTimer<$TIMX, Enabled> {}

            impl CountDown for LpTimer<$TIMX, Enabled> {
                type Time = Hertz;

                fn start<T>(&mut self, timeout: T)
                where
                    T: Into<Hertz>,
                {
                    // Reset: counter must be running
                    self.reset_counter();

                    // Disable counter
                    self.tim.cr.write(|w| w.enable().disabled());

                    // Set prescale and ARR
                    self.priv_set_freq(timeout); // side effect: enables counter

                    // Clear IRQ
                    self.clear_irq();

                    // Start counter
                    self.tim.cr.write(|w| w.cntstrt().set_bit().enable().enabled());
                }

                fn wait(&mut self) -> nb::Result<(), Void> {
                    if self.tim.isr.read().arrm().bit_is_clear() {
                        Err(nb::Error::WouldBlock)
                    } else {
                        self.clear_irq();
                        Ok(())
                    }
                }
            }

            impl TimerExt<LpTimer<$TIMX, Enabled>> for $TIMX {
                type Rec = rec::$Rec;

                fn timer<T>(self, timeout: T,
                            prec: Self::Rec, clocks: &CoreClocks
                ) -> LpTimer<$TIMX, Enabled>
                    where
                        T: Into<Hertz>,
                {
                    LpTimer::$timx(self, timeout, prec, clocks)
                }

                fn tick_timer<T>(self, _frequency: T,
                                 _prec: Self::Rec, _clocks: &CoreClocks
                ) -> LpTimer<$TIMX, Enabled>
                where
                    T: Into<Hertz>,
                {
                    unimplemented!()
                }
            }

            impl LpTimer<$TIMX, Enabled> {
                /// Configures a LPTIM peripheral as a periodic count down timer
                pub fn $timx<T>(tim: $TIMX, timeout: T,
                                prec: rec::$Rec, clocks: &CoreClocks
                ) -> Self
                where
                    T: Into<Hertz>,
                {
                    // enable and reset peripheral to a clean state
                    prec.enable().reset();

                    let clk = $TIMX::get_clk(clocks)
                        .expect("Timer input clock not running!").0;

                    let mut timer = LpTimer {
                        clk,
                        tim,
                        timeout: Hertz(0),
                        _enabled: PhantomData,
                    };
                    timer.start(timeout);

                    timer
                }

                /// Perform a synchronous reset of the LPTIM counter. The timer
                /// must be running.
                pub fn reset_counter(&mut self) {
                    // Counter Reset
                    self.tim.cr.write(|w| w.countrst().set_bit().enable().enabled());

                    while self.tim.cr.read().countrst().bit_is_set() {}
                }

                /// Disables the LPTIM peripheral
                pub fn pause(self) -> LpTimer<$TIMX, Disabled> {
                    // Disable the entire timer
                    self.tim.cr.write(|w| w.enable().disabled());

                    LpTimer {
                        clk: self.clk,
                        tim: self.tim,
                        timeout: self.timeout,
                        _enabled: PhantomData,
                    }
                }
            }

            impl LpTimer<$TIMX, Disabled> {
                /// Sets the frequency of the LPTIM counter.
                ///
                /// The counter must be disabled.
                pub fn set_freq<T>(&mut self, timeout: T)
                where
                    T: Into<Hertz>,
                {
                    self.priv_set_freq(timeout); // side effect: enables counter

                    // Disable timer
                    self.tim.cr.write(|w| w.enable().disabled());
                }

                /// Start listening for `event`
                ///
                /// The timer must be disabled, see RM0433 Rev 7. 43.4.13
                pub fn listen(&mut self, event: Event) {
                    match event {
                        Event::TimeOut => {
                            // Enable autoreload match interrupt
                            self.tim.ier.modify(|_, w| w.arrmie().set_bit());
                        }
                    }
                }

                /// Stop listening for `event`
                ///
                /// The timer must be disabled, see RM0433 Rev 7. 43.4.13
                pub fn unlisten(&mut self, event: Event) {
                    match event {
                        Event::TimeOut => {
                            // Disable autoreload match interrupt
                            self.tim.ier.modify(|_, w| w.arrmie().clear_bit());
                        }
                    }
                }

                /// Enables the LPTIM, and starts counting
                pub fn resume(self) -> LpTimer<$TIMX, Enabled> {
                    // Enable and start counting
                    self.tim.cr.write(|w| w.enable().enabled());
                    self.tim.cr.write(|w| w.cntstrt().set_bit().enable().enabled());

                    LpTimer {
                        clk: self.clk,
                        tim: self.tim,
                        timeout: self.timeout,
                        _enabled: PhantomData,
                    }
                }
            }

            impl<ED> LpTimer<$TIMX, ED> {
                /// Private method to set the frequency of the LPTIM
                /// counter. The counter must be disabled, but it will be
                /// enabled at the end of this method.
                fn priv_set_freq<T>(&mut self, timeout: T)
                where
                    T: Into<Hertz>,
                {
                    self.timeout = timeout.into();

                    let clk = self.clk;
                    let frequency = self.timeout.0;
                    let ticks = clk / frequency;
                    assert!(ticks < 128 * (1 << 16));

                    // Calculate prescaler
                    let (prescale, prescale_div) = match ticks / (1 << 16) {
                        0 => ($timXpac::cfgr::PRESC_A::DIV1, 1),
                        1 => ($timXpac::cfgr::PRESC_A::DIV2, 2),
                        2..=3 => ($timXpac::cfgr::PRESC_A::DIV4, 4),
                        4..=7 => ($timXpac::cfgr::PRESC_A::DIV8, 8),
                        8..=15 => ($timXpac::cfgr::PRESC_A::DIV16, 16),
                        16..=31 => ($timXpac::cfgr::PRESC_A::DIV32, 32),
                        32..=63 => ($timXpac::cfgr::PRESC_A::DIV64, 64),
                        _ => ($timXpac::cfgr::PRESC_A::DIV128, 128),
                    };

                    // Calcuate reload
                    let arr = ticks / prescale_div;
                    assert!(arr <= 0xFFFF);
                    assert!(arr > 0);

                    // Write CFGR: LPTIM must be disabled
                    self.tim.cfgr.modify(|_, w| w.presc().variant(prescale));

                    // Enable
                    self.tim.cr.write(|w| w.enable().enabled());

                    // Write ARR: LPTIM must be enabled
                    self.tim.arr.write(|w| w.arr().bits(arr as u16));
                    while self.tim.isr.read().arrok().bit_is_clear() {}
                    self.tim.icr.write(|w| w.arrokcf().clear());
                }

                /// Read the counter of the LPTIM peripheral
                pub fn counter(&self) -> u32 {
                    loop {
                        // Read once
                        let count1 = self.tim.cnt.read().bits();

                        // Read twice - see RM0433 Rev 7. 43.4.14
                        let count2 = self.tim.cnt.read().bits();

                        if count1 == count2 { return count2; }
                    }
                }

                /// Clears interrupt flag
                pub fn clear_irq(&mut self) {
                    // Clear autoreload match event
                    self.tim.icr.write(|w| w.arrmcf().set_bit());
                }

                /// Releases the LPTIM peripheral
                pub fn free(self) -> ($TIMX, rec::$Rec) {
                    // Disable timer
                    self.tim.cr.write(|w| w.enable().disabled());

                    (self.tim, rec::$Rec { _marker: PhantomData })
                }
            }
        )+
    }
}

lptim_hal! {
    LPTIM1: (lptim1, Lptim1, lptim1),
    LPTIM2: (lptim2, Lptim2, lptim1),
    LPTIM3: (lptim3, Lptim3, lptim3),
}
#[cfg(not(feature = "rm0455"))]
lptim_hal! {
    LPTIM4: (lptim4, Lptim4, lptim3),
    LPTIM5: (lptim5, Lptim5, lptim3),
}