gd32e2-hal 0.14.0

HAL for the GD32E23x series (Cortex-M23), currently the GD32E230
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
//! Timers: the counter core shared by every TIMER peripheral.
//!
//! A timer counts `CK_TIMERx` ticks divided by `PSC + 1`, and restarts from zero
//! once the count reaches `CAR`. Everything else a timer can do — PWM, input
//! capture, triggering other peripherals — is built on top of that core.
//!
//! ```ignore
//! let timer = dp.timer5.constrain(&mut rcu, clocks);
//! let timer = timer.start_interval(500.millis());
//! timer.wait();
//! ```

use core::convert::Infallible;

use embedded_hal::delay::DelayNs;
use embedded_hal::pwm::{ErrorType, SetDutyCycle};

use crate::gpio::{Alternate, Pin};
use crate::pac;
use crate::rcu::{Clocks, Enable, Rcu, Reset};
use crate::time::{Duration, Hertz, NanosDuration};

/// Counts one prescaler or counter cycle can span, both fields being 16-bit.
const MAX_COUNT: u32 = 1 << 16;

/// Splits a tick count into the `PSC` and `CAR` values whose cycle spans it.
///
/// The prescaler is kept as small as the counter width allows, leaving the
/// counter as much of the interval as possible: its step is the resolution
/// everything built on the core inherits. The division truncates, so the
/// realised interval is at most one prescaler cycle short of the requested one.
///
/// A zero tick count is raised to one — the shortest interval the hardware can
/// express, since a counter cycle is at least one tick.
fn dividers(ticks: u32) -> (u16, u16) {
    let ticks = ticks.max(1);
    let psc = ticks.div_ceil(MAX_COUNT);
    let car = ticks / psc;
    ((psc - 1) as u16, (car - 1) as u16)
}

/// Converts an interval of any scale into ticks of `clock`.
///
/// A `Duration` is a plain count whose unit is `NOM / DENOM` seconds, so the
/// interval in seconds is `as_ticks() * NOM / DENOM` and the tick count follows
/// by multiplying with the frequency. The division comes last: taking `NOM /
/// DENOM` first would floor to zero on every scale finer than a second.
///
/// Saturates instead of wrapping, both in the product and on the way down to
/// `u32`. Anything past `u32::MAX` ticks is beyond what the dividers can span
/// anyway — under a minute at 72 MHz — so the result is the longest interval the
/// hardware can express.
fn interval_to_ticks<const NOM: u64, const DENOM: u64>(
    interval: Duration<u32, NOM, DENOM>,
    clock: Hertz,
) -> u32 {
    let raw_time = u64::from(interval.as_ticks());
    let raw_freq = u64::from(clock.to_Hz());
    (raw_time.saturating_mul(raw_freq).saturating_mul(NOM) / DENOM).min(u32::MAX.into()) as u32
}

/// Converts a tick count of `clock`, divided by `psc`, into a duration.
///
/// The inverse of [`interval_to_ticks`], and saturating for the same reasons:
/// one tick is `psc + 1` cycles of the clock, so the duration in seconds is
/// `ticks * (psc + 1) / clock`, and the scale turns that into `DENOM / NOM` of
/// its own units. The division comes last, in `u64`, or every scale finer than
/// a second would floor to zero.
fn ticks_to_interval<const NOM: u64, const DENOM: u64>(
    ticks: u16,
    psc: u16,
    clock: Hertz,
) -> Duration<u32, NOM, DENOM> {
    let ticks = u64::from(ticks);
    let psc = u64::from(psc);
    let clock = u64::from(clock.to_Hz());
    Duration::<u32, NOM, DENOM>::from_ticks(
        (ticks.saturating_mul(psc + 1).saturating_mul(DENOM) / clock.saturating_mul(NOM))
            .min(u32::MAX.into()) as u32,
    )
}

/// Loads the dividers and sets the counter running.
///
/// Both are written before the counter runs: `UPG` loads them out of their
/// shadow registers, and the update event it raises is consumed here so the
/// first wait afterwards sees a real rollover.
fn start_counter<TIMERX: Instance>(timer: &TIMERX, psc: u16, car: u16) {
    timer.set_psc(psc);
    timer.set_car(car);
    timer.gen_update();
    timer.clear_upif();
    timer.set_cen(true);
}

/// Blocks until the counter rolls over, then clears the flag it raised.
///
/// The counter is left as it was: hardware never clears `UPIF` itself, so the
/// clear here is what makes the next wait measure a fresh cycle.
fn wait_update<TIMERX: Instance>(timer: &TIMERX) {
    while !timer.read_upif() {}
    timer.clear_upif();
}

/// A timer peripheral, tying it to the bus that clocks it.
///
/// Which APB a timer sits on is fixed in silicon, so the frequency for the
/// period arithmetic comes from the type rather than from an argument.
pub trait Instance: Enable + Reset {
    /// The `CK_TIMERx` branch feeding this timer, taken from a frozen tree.
    fn clk(clocks: &Clocks) -> Hertz;
    /// Writes the prescaler, which reaches the counter on the next update event.
    fn set_psc(&self, psc: u16);
    /// Reads back the prescaler dividing the clock into counter ticks.
    fn read_psc(&self) -> u16;
    /// Writes the auto-reload value the counter rolls over at.
    fn set_car(&self, car: u16);
    /// Reads back the auto-reload value the counter rolls over at.
    fn read_car(&self) -> u16;
    /// Reads the counter, which advances on its own while the timer runs.
    fn read_cnt(&self) -> u16;
    /// Raises an update event in software, loading the shadowed dividers.
    fn gen_update(&self);
    /// Runs or halts the counter.
    fn set_cen(&self, on: bool);
    /// Update flag — set by hardware on every rollover, never cleared by it.
    fn read_upif(&self) -> bool;
    /// Clears the update flag.
    fn clear_upif(&self);
    /// Produces a second handle to the same peripheral.
    ///
    /// # Safety
    ///
    /// Ownership of a peripheral is what the whole HAL builds its typestate on:
    /// one handle means one configuration in flight. A second handle sidesteps
    /// that, and keeping the two from contradicting each other is on the caller
    /// — either by handing them disjoint registers, or by never reconfiguring
    /// the peripheral through both.
    unsafe fn steal(&self) -> Self;
}

macro_rules! timer_instance {
    ($($TIMERX:ty => $clk:ident,)+) => {
        $(
            impl Instance for $TIMERX {
                fn clk(clocks: &Clocks) -> Hertz {
                    clocks.$clk()
                }
                fn set_psc(&self, psc: u16) {
                    self.psc().write(|w| w.psc().bits(psc));
                }
                fn read_psc(&self) -> u16 {
                    self.psc().read().psc().bits()
                }
                // The `CAR` writer is unsafe on TIMER2 only, where the SVD leaves
                // the field unconstrained, and safe on the other six. One macro
                // body serves all of them, so the block is always written and the
                // lint is silenced for the six that do not need it. Nothing is
                // actually being asserted here: every `u16` is a legal reload
                // value in counting mode, zero included.
                #[allow(unused_unsafe)]
                fn set_car(&self, car: u16) {
                    self.car().write(|w| unsafe { w.car().bits(car) });
                }
                fn read_car(&self) -> u16 {
                    self.car().read().car().bits()
                }
                fn read_cnt(&self) -> u16 {
                    self.cnt().read().cnt().bits()
                }
                fn gen_update(&self) {
                    self.swevg().write(|w| w.upg().set_bit());
                }
                fn set_cen(&self, on: bool) {
                    self.ctl0().modify(|_, w| w.cen().bit(on));
                }
                fn read_upif(&self) -> bool {
                    self.intf().read().upif().bit_is_set()
                }
                // `INTF` is a flag register where zero clears and one leaves
                // alone, and its reset value is zero — so `write` would clear
                // every flag it does not name. `modify` writes the neighbours
                // back as the ones they were read as, leaving them untouched.
                fn clear_upif(&self) {
                    self.intf().modify(|_, w| w.upif().clear());
                }
                unsafe fn steal(&self) -> Self{
                    unsafe { Self::steal() }
                }
            }
        )+
    };
}

timer_instance! {
    pac::Timer2 => pclk1_tim,
    pac::Timer5 => pclk1_tim,
    pac::Timer13 => pclk1_tim,
    pac::Timer0 => pclk2_tim,
    pac::Timer14 => pclk2_tim,
    pac::Timer15 => pclk2_tim,
    pac::Timer16 => pclk2_tim,
}

/// A stopped timer, holding the peripheral and the frequency feeding it.
///
/// Clocked and reset on construction, but the counter is not running: the
/// methods that wait on the count live on the running type, so waiting on a
/// timer that was never started cannot be expressed.
pub struct Timer<TIMERX> {
    timer: TIMERX,
    clk: Hertz,
}

impl<TIMERX: Instance> Timer<TIMERX> {
    /// Clocks the peripheral, resets it, and records the clock feeding it.
    pub fn new(rcu: &mut Rcu, timer: TIMERX, clocks: Clocks) -> Timer<TIMERX> {
        TIMERX::enable(rcu);
        TIMERX::reset(rcu);
        Timer {
            timer,
            clk: TIMERX::clk(&clocks),
        }
    }
    /// Returns the peripheral.
    ///
    /// The clock is left enabled and no reset is performed — a later `new()`
    /// does both anyway.
    pub fn release(self) -> TIMERX {
        self.timer
    }

    /// Starts the counter, which then rolls over every `car + 1` ticks of
    /// `clk / (psc + 1)`.
    ///
    /// The dividers reach the counter before it runs, so the first
    /// [`wait`](CountDownTimer::wait) already measures the full interval.
    pub fn start(self, psc: u16, car: u16) -> CountDownTimer<TIMERX> {
        start_counter(&self.timer, psc, car);
        CountDownTimer {
            timer: self.timer,
            clk: self.clk,
        }
    }
    /// Starts the counter, which then rolls over once per `interval`.
    ///
    /// The interval is taken in whatever scale the caller wrote it in — `5.secs()`,
    /// `500.millis()`, `100.micros()` all work, with no conversion at the call
    /// site. The dividers are derived from it against this timer's own clock,
    /// truncating: the realised interval is at most one prescaler cycle short.
    ///
    /// Intervals past what the 16-bit dividers can span (just under a minute at
    /// 72 MHz) saturate to the longest the hardware can produce, and a zero
    /// interval becomes a single tick.
    pub fn start_interval<const NOM: u64, const DENOM: u64>(
        self,
        interval: Duration<u32, NOM, DENOM>,
    ) -> CountDownTimer<TIMERX> {
        let (psc, car) = dividers(interval_to_ticks(interval, self.clk));
        self.start(psc, car)
    }
    /// Hands the timer over to blocking delays.
    ///
    /// The counter carries no interval of its own afterwards: every
    /// [`delay`](Delay::delay) sets up its own and tears it down again.
    pub fn into_delay(self) -> Delay<TIMERX> {
        Delay {
            timer: self.timer,
            clk: self.clk,
        }
    }
    /// Hands the timer over to PWM and starts it on the given period.
    ///
    /// The period is the counter cycle every channel of this timer shares, and
    /// `car + 1` is also the duty resolution the channels get: a larger reload
    /// buys finer steps at a lower frequency.
    pub fn into_pwm(self, psc: u16, car: u16) -> Pwm<TIMERX> {
        start_counter(&self.timer, psc, car);
        Pwm {
            timer: self.timer,
            clk: self.clk,
        }
    }
    /// Hands the timer over to PWM, taking the period as a duration.
    ///
    /// Splits the period between the dividers the same way
    /// [`start_interval`](Self::start_interval) does, keeping the reload as
    /// large as it can — which here is what leaves the duty as many steps as
    /// possible.
    pub fn into_pwm_interval<const NOM: u64, const DENOM: u64>(
        self,
        interval: Duration<u32, NOM, DENOM>,
    ) -> Pwm<TIMERX> {
        let (psc, car) = dividers(interval_to_ticks(interval, self.clk));
        self.into_pwm(psc, car)
    }
    /// Sets the counter free running and hands out the input capture role.
    ///
    /// Only the prescaler is a choice here: it alone sets what one tick costs,
    /// trading resolution against the longest interval that still fits between
    /// two rollovers. The reload value is not a choice at all — capture reads
    /// the counter as a clock rather than a period, so it is pinned to the
    /// maximum and never reaches the caller.
    pub fn into_capture(self, psc: u16) -> Capture<TIMERX> {
        start_counter(&self.timer, psc, u16::MAX);
        Capture {
            timer: self.timer,
            clk: self.clk,
        }
    }
}

/// A running timer, counting down the interval [`Timer::start`] was given.
///
/// Free-running: the counter reloads and starts over on every rollover, so the
/// interval repeats until the timer is stopped.
pub struct CountDownTimer<TIMERX> {
    timer: TIMERX,
    clk: Hertz,
}

impl<TIMERX: Instance> CountDownTimer<TIMERX> {
    /// Returns the current counter value, in timer ticks.
    ///
    /// The counter runs from zero up to the reload value and starts over, so
    /// the reading only tells where inside the current interval the timer is,
    /// not how many intervals have passed. One tick lasts `(psc + 1)` cycles
    /// of the clock feeding the timer.
    pub fn cnt(&self) -> u16 {
        self.timer.read_cnt()
    }
    /// Returns the value the counter rolls over at, in timer ticks.
    ///
    /// Read back from the hardware rather than remembered, so it holds whether
    /// the interval came from [`start_interval`](Timer::start_interval) or from
    /// a raw [`start`](Timer::start). One full interval is `car() + 1` ticks,
    /// which is why `cnt()` reaching this value is the last tick before a
    /// rollover, not the rollover itself.
    pub fn car(&self) -> u16 {
        self.timer.read_car()
    }
    /// Returns the prescaler the counter is running on.
    ///
    /// One counter tick lasts `psc() + 1` cycles of the clock feeding the
    /// timer, which is what turns a [`cnt`](Self::cnt) reading into time.
    /// Read back from the hardware, so it holds for a raw
    /// [`start`](Timer::start) as well.
    pub fn psc(&self) -> u16 {
        self.timer.read_psc()
    }
    /// Returns how far into the current interval the counter is, as a duration.
    ///
    /// Reads [`cnt`](Self::cnt) and turns it into time, so the result restarts
    /// from zero at every rollover and never exceeds one interval. Intervals
    /// themselves are not counted: what has passed since the timer started is
    /// the caller's to track.
    ///
    /// The scale comes from the binding, the same way it is given to
    /// [`start_interval`](Timer::start_interval): `let t: MillisDuration =
    /// timer.elapsed();`. Pick it to match the interval — a scale coarser than
    /// one tick floors to zero, and a scale so fine that the full interval no
    /// longer fits `u32` saturates instead of wrapping.
    ///
    /// Resolution is one timer tick, `psc() + 1` cycles of the timer clock.
    pub fn elapsed<const NOM: u64, const DENOM: u64>(&self) -> Duration<u32, NOM, DENOM> {
        ticks_to_interval(self.cnt(), self.psc(), self.clk)
    }

    /// Blocks until the counter rolls over, then clears the update flag.
    ///
    /// Leaves the timer running, so calling this in a loop yields one full
    /// interval per call.
    pub fn wait(&self) {
        wait_update(&self.timer);
    }

    /// Halts the counter and hands the timer back in its stopped form.
    ///
    /// The counter keeps its current value; a later [`start`](Timer::start)
    /// reloads the dividers and restarts from zero.
    pub fn stop(self) -> Timer<TIMERX> {
        self.timer.set_cen(false);
        Timer {
            timer: self.timer,
            clk: self.clk,
        }
    }
    /// Halts the counter and returns the peripheral, skipping the stopped form.
    pub fn release(self) -> TIMERX {
        self.stop().timer
    }
}

/// A timer given over to blocking delays.
///
/// Unlike [`CountDownTimer`] this type promises no interval at all: the value
/// only says which timer the delays run on. Each call configures the dividers,
/// waits, and stops the counter again, so nothing survives between calls and a
/// delay can be asked for any length at any time.
pub struct Delay<TIMERX> {
    timer: TIMERX,
    clk: Hertz,
}

impl<TIMERX: Instance> Delay<TIMERX> {
    /// Blocks for `interval`, in whatever scale the caller wrote it in.
    ///
    /// Rounding and the saturation ceiling are the same as in
    /// [`Timer::start_interval`], the dividers being derived the same way.
    pub fn delay<const NOM: u64, const DENOM: u64>(&mut self, interval: Duration<u32, NOM, DENOM>) {
        let (psc, car) = dividers(interval_to_ticks(interval, self.clk));
        start_counter(&self.timer, psc, car);
        wait_update(&self.timer);
        self.timer.set_cen(false);
    }

    /// Takes the timer back out of delay duty, stopped and ready to be started.
    pub fn into_timer(self) -> Timer<TIMERX> {
        Timer {
            timer: self.timer,
            clk: self.clk,
        }
    }

    /// Returns the peripheral.
    ///
    /// The clock is left enabled and no reset is performed — a later `new()`
    /// does both anyway.
    pub fn release(self) -> TIMERX {
        self.timer
    }
}

/// A timer running as the period behind one or more PWM channels.
///
/// Owns the counter the channels compare against, which is what keeps the
/// period in one place: channels carry their own duty, and the frequency they
/// all run at is set here, once, on the way in.
pub struct Pwm<TIMERX> {
    timer: TIMERX,
    clk: Hertz,
}

impl<TIMERX: Instance> Pwm<TIMERX> {
    /// Configures one channel of this timer and hands it out on the given pin.
    ///
    /// Which channel it is follows from the pin: the silicon routes each pin to
    /// exactly one channel of one timer, so a pin that reaches this timer at all
    /// leaves no choice to make. The channel comes out configured but not
    /// enabled, and with no duty set yet.
    ///
    /// The pin moves in and stays there for as long as the channel lives, which
    /// is what keeps it from being reconfigured out from under a running output.
    ///
    /// Several pins can reach the same channel — `TIMER2` channel 0 answers on
    /// both `PA6` and `PB4` — and handing over each of them yields two channels
    /// writing one compare register. Both pins then carry the same signal, which
    /// is occasionally the point; the duty of one, however, is the duty of the
    /// other, whichever wrote last.
    pub fn channel<PIN, const C: u8>(&self, pin: PIN) -> PwmChannel<TIMERX, PIN, C>
    where
        PIN: ChannelPin<TIMERX, C>,
        TIMERX: PwmOps<C>,
    {
        self.timer.apply_pwm_mode();
        PwmChannel {
            // Each channel reaches its own compare register and its own bits of
            // the shared ones, so the handles this hands out never configure the
            // same thing twice — the obligation `steal` places on the caller.
            timer: unsafe { self.timer.steal() },
            pin,
        }
    }

    /// Changes the period without disturbing the running counter.
    ///
    /// Channels already handed out keep the duty they were given **in ticks**,
    /// so a new reload silently moves what fraction of the period that is: half
    /// of a thousand ticks is all of five hundred. Set the duties again after
    /// changing the period, or read the new [`max_duty`](PwmChannel::max_duty)
    /// and scale them.
    ///
    /// The prescaler reaches the counter at the next update event, so the
    /// cycle in flight when this is called still runs on the old one.
    pub fn set_period(&self, psc: u16, car: u16) {
        self.timer.set_psc(psc);
        self.timer.set_car(car);
    }
    /// Changes the period, taking it as a duration.
    ///
    /// Splits it between the dividers exactly as
    /// [`into_pwm_interval`](Timer::into_pwm_interval) does, keeping the reload
    /// as large as it fits so the duty keeps as many steps as possible.
    pub fn set_period_interval<const NOM: u64, const DENOM: u64>(
        &self,
        interval: Duration<u32, NOM, DENOM>,
    ) {
        let (psc, car) = dividers(interval_to_ticks(interval, self.clk));
        self.set_period(psc, car);
    }

    /// Halts the counter and takes the timer back out of PWM duty.
    ///
    /// Channels already handed out keep their stolen handles and their pins, so
    /// they outlive this and go on reaching the registers. Their outputs hold
    /// whatever level they were at when the counter stopped, since the pins stay
    /// driven by the channels rather than reverting.
    pub fn into_timer(self) -> Timer<TIMERX> {
        self.timer.set_cen(false);
        Timer {
            timer: self.timer,
            clk: self.clk,
        }
    }
    /// Halts the counter and returns the peripheral, skipping the stopped form.
    pub fn release(self) -> TIMERX {
        self.into_timer().timer
    }
}

impl<TIMERX> Pwm<TIMERX>
where
    TIMERX: PrimaryOutput,
{
    /// Lets the channels reach their pins.
    ///
    /// Timers carrying a `CCHP` register keep their outputs behind this one
    /// switch, and it starts off: a channel of such a timer stays silent no
    /// matter how it is configured until this is called. The timers without the
    /// register have no such gate and need nothing.
    pub fn enable_output(&self) {
        self.timer.set_poen(true);
    }
    /// Cuts every channel off from its pin at once, keeping them configured.
    pub fn disable_output(&self) {
        self.timer.set_poen(false);
    }
}

/// A free running timer whose channels timestamp edges on their pins.
///
/// The counter is the time base and nothing else: it runs to `u16::MAX` and
/// wraps, while each channel latches the count at the moment its edge arrives.
/// Intervals come out as differences between those latched values, so the role
/// carries no period of its own — unlike [`CountDownTimer`], where the period
/// is the whole invariant.
pub struct Capture<TIMERX> {
    timer: TIMERX,
    clk: Hertz,
}

impl<TIMERX: Instance> Capture<TIMERX> {
    /// Points one channel of this timer at the given pin and hands it out.
    ///
    /// Which channel it is follows from the pin, exactly as it does for
    /// [`Pwm::channel`]: the silicon routes each pin to one channel of one
    /// timer, so nothing is left to choose. The channel comes out configured
    /// but not enabled, and latches nothing until it is.
    ///
    /// The edge is taken here rather than left for later so that a channel is
    /// never half configured; [`select_edge`](CaptureChannel::select_edge)
    /// changes it afterwards.
    ///
    /// The pin moves in and stays there for as long as the channel lives, which
    /// is what keeps it from being reconfigured out from under a live capture.
    pub fn channel<PIN, const C: u8>(&self, pin: PIN, edge: Edge) -> CaptureChannel<TIMERX, PIN, C>
    where
        PIN: ChannelPin<TIMERX, C>,
        TIMERX: CaptureOps<C>,
    {
        self.timer.apply_capture_mode();
        self.timer.select_edge(edge);
        CaptureChannel {
            // Each channel reaches its own capture register and its own bits of
            // the shared ones, so the handles this hands out never configure the
            // same thing twice — the obligation `steal` places on the caller.
            timer: unsafe { self.timer.steal() },
            pin,
            clk: self.clk,
        }
    }

    /// Halts the counter and takes the timer back out of capture duty.
    ///
    /// Channels already handed out keep their stolen handles and their pins, so
    /// they outlive this and go on reaching the registers — they simply stop
    /// latching anything once the counter is halted.
    pub fn into_timer(self) -> Timer<TIMERX> {
        self.timer.set_cen(false);
        Timer {
            timer: self.timer,
            clk: self.clk,
        }
    }
    /// Halts the counter and returns the peripheral, skipping the stopped form.
    pub fn release(self) -> TIMERX {
        self.into_timer().timer
    }
}

/// Blocking delays for portable drivers, delegating to [`Delay::delay`].
///
/// The resolution is one timer tick — around 20 ns at 48 MHz — so a request
/// finer than that is served as a single tick rather than not at all. The
/// trait's `delay_us` and `delay_ms` are its own defaults, which split long
/// waits into chunks of at most `u32::MAX` nanoseconds; a chunk that size is
/// well inside what the dividers can span, so the saturation ceiling of
/// [`Timer::start_interval`] is never reached through this trait.
impl<TIMERX: Instance> DelayNs for Delay<TIMERX> {
    fn delay_ns(&mut self, ns: u32) {
        self.delay(NanosDuration::from_nanos(ns));
    }
}

/// Entry point on the raw peripheral, mirroring `GpioExt` and `DmaExt`.
pub trait TimerExt: Sized {
    /// Consumes the peripheral and returns it clocked, reset and stopped.
    ///
    /// Same thing [`Timer::new`] does, reached from the peripheral instead.
    fn constrain(self, rcu: &mut Rcu, clocks: Clocks) -> Timer<Self>;
}

impl<TIMERX: Instance> TimerExt for TIMERX {
    fn constrain(self, rcu: &mut Rcu, clocks: Clocks) -> Timer<Self> {
        Timer::new(rcu, self, clocks)
    }
}

/// The switch turning channel `C` on, whichever direction it points.
///
/// `CHxEN` is one field serving both roles — it releases the output on a
/// compare channel and arms the latch on a capture one — so it sits above them
/// rather than being spelled twice. Implemented once per timer and channel that
/// exist together, which is what makes a channel the hardware does not have
/// impossible to name: `TIMER13` carries channel 0 alone, `TIMER5` has no
/// channels at all.
pub trait ChannelEnable<const C: u8>: Instance {
    /// Enables or disables the channel, leaving its setup in place.
    fn set_chxen(&self, on: bool);
}

macro_rules! channel_enable {
    {$($Timer:ty => [$(($Ch:expr, $chen:ident)$(,)?)+]$(,)?)+} => {
        $($(impl ChannelEnable<$Ch> for $Timer {
            fn set_chxen(&self, on: bool) {
                self.chctl2().modify(|_, w| match on {
                    true => w.$chen().enabled(),
                    false => w.$chen().disabled(),
                })
            }
        })+)+
    };
}

channel_enable! {
    pac::Timer0 => [(0, ch0en), (1, ch1en), (2, ch2en), (3, ch3en)],
    pac::Timer2 => [(0, ch0en), (1, ch1en), (2, ch2en), (3, ch3en)],
    pac::Timer13 => [(0, ch0en)],
    pac::Timer14 => [(0, ch0en), (1, ch1en)],
    pac::Timer15 => [(0, ch0en)],
    pac::Timer16 => [(0, ch0en)]
}

/// Register operations on compare channel `C` of a timer.
///
/// Channel registers differ from one channel to the next, which is why the
/// number lives in the type rather than in an argument.
pub trait PwmOps<const C: u8>: ChannelEnable<C> {
    /// Configures the channel as a PWM output and readies it for a duty value.
    ///
    /// Covers the whole group of one-time fields at once — direction, compare
    /// mode and polarity — since a channel set to PWM mode while still pointed
    /// at its input drives nothing, and the two are only correct together.
    fn apply_pwm_mode(&self);
    /// Writes the compare value the channel switches its output at.
    ///
    /// The output stays active while the counter is below this value, so one
    /// full period is `car() + 1` and duty is the ratio between the two.
    fn set_chxcv(&self, cv: u16);
}

macro_rules! pwm {
    {$($Timer:ty => [
        $(
            ($Ch:expr, ($chctl_reg:ident, $chms:ident, $chcomctl:ident, $chcomsen:ident), ($chcv:ident, $chval:ident), $chp:ident)$(,)?
        )+]$(,)?)+
    } => {
        $($(impl PwmOps<$Ch> for $Timer {
            fn apply_pwm_mode(&self) {
                self.chctl2().modify(|_, w| w.$chp().not_inverted());
                self.$chctl_reg().modify(|_, w| {
                    w.$chms()
                        .output()
                        .$chcomctl()
                        .pwm_mode0()
                        .$chcomsen()
                        .enabled()
                });
            }
            #[allow(unused_unsafe)]
            fn set_chxcv(&self, cv: u16) {
                self.$chcv().write(|w| unsafe { w.$chval().bits(cv) });
            }
        })+)+
    };
}

pwm! {
    pac::Timer0 => [(0, (chctl0_output, ch0ms, ch0comctl, ch0comsen), (ch0cv, ch0val), ch0p),
        (1, (chctl0_output, ch1ms, ch1comctl, ch1comsen), (ch1cv, ch1val), ch1p),
        (2, (chctl1_output, ch2ms, ch2comctl, ch2comsen), (ch2cv, ch2val), ch2p),
        (3, (chctl1_output, ch3ms, ch3comctl, ch3comsen), (ch3cv, ch3val), ch3p)],
    pac::Timer2 => [(0, (chctl0_output, ch0ms, ch0comctl, ch0comsen), (ch0cv, ch0val), ch0p),
        (1, (chctl0_output, ch1ms, ch1comctl, ch1comsen), (ch1cv, ch1val), ch1p),
        (2, (chctl1_output, ch2ms, ch2comctl, ch2comsen), (ch2cv, ch2val), ch2p),
        (3, (chctl1_output, ch3ms, ch3comctl, ch3comsen), (ch3cv, ch3val), ch3p)],
    pac::Timer13 => [(0, (chctl0_output, ch0ms, ch0comctl, ch0comsen), (ch0cv, ch0val), ch0p)],
    pac::Timer14 => [(0, (chctl0_output, ch0ms, ch0comctl, ch0comsen), (ch0cv, ch0val), ch0p),
        (1, (chctl0_output, ch1ms, ch1comctl, ch1comsen), (ch1cv, ch1val), ch1p)],
    pac::Timer15 => [(0, (chctl0_output, ch0ms, ch0comctl, ch0comsen), (ch0cv, ch0val), ch0p)],
    pac::Timer16 => [(0, (chctl0_output, ch0ms, ch0comctl, ch0comsen), (ch0cv, ch0val), ch0p)]
}

/// The output switch shared by every channel of a timer that has one.
///
/// Only the timers carrying a `CCHP` register implement this: `TIMER0`,
/// `TIMER14`, `TIMER15` and `TIMER16`. It sits above the per-channel enables —
/// with it off, the channels stay configured and the counter keeps running
/// while the pins show nothing.
pub trait PrimaryOutput: Instance {
    /// Enables or disables the outputs of all channels at once.
    fn set_poen(&self, on: bool);
}

macro_rules! poen {
    ($($Timer:ty$(,)?)+) => {
        $(impl PrimaryOutput for $Timer {
            fn set_poen(&self, on: bool) {
                self.cchp().modify(|_, w| match on {
                    true => w.poen().enabled(),
                    false => w.poen().disabled(),
                });
            }
        })+
    };
}

poen!(pac::Timer0, pac::Timer14, pac::Timer15, pac::Timer16);

/// Marks a pin the silicon routes to channel `C` of `TIMERX`, in the right
/// alternate function.
pub trait ChannelPin<TIMERX, const C: u8> {}

macro_rules! channel_pins {
    ( $( $TIMERX:ty: $( $C:literal: [ $($p:literal $n:literal : $af:literal),* $(,)? ] )* ),* $(,)? ) => {
        $($($( impl ChannelPin<$TIMERX, $C> for Pin<$p, $n, Alternate<$af>> {} )*)*)*
    };
}

// Complementary outputs (`CHx_ON`), break inputs and `ETI` share these same
// pins at other alternate functions; only the plain compare outputs are listed.
channel_pins! {
    pac::Timer0:
        0: [ 'A' 8:2 ]
        1: [ 'A' 9:2 ]
        2: [ 'A' 10:2 ]
        3: [ 'A' 11:2 ],
    pac::Timer2:
        0: [ 'A' 6:1, 'B' 4:1 ]
        1: [ 'A' 7:1, 'B' 5:1 ]
        2: [ 'B' 0:1 ]
        3: [ 'B' 1:1 ],
    pac::Timer13:
        0: [ 'A' 4:4, 'A' 7:4, 'B' 1:2 ],
    pac::Timer15:
        0: [ 'A' 6:5, 'B' 8:2 ],
    pac::Timer16:
        0: [ 'A' 7:5, 'B' 9:2 ],
}

#[cfg(feature = "gd32e230x8")]
channel_pins! {
    pac::Timer14:
        0: [ 'A' 2:0, 'B' 14:1 ]
        1: [ 'A' 3:0, 'B' 15:1 ],
}

/// One PWM output of a timer, configured and ready to take a duty value.
///
/// Channels of the same timer are independent in everything but the period:
/// `PSC` and `CAR` belong to the counter they share, so changing the frequency
/// changes it for all of them at once. Duty is the channel's own.
///
/// Each channel carries its own handle to the peripheral, which is what lets
/// four of them exist while the timer is a single value. Writing a duty touches
/// only that channel's compare register, but the enables of all channels live in
/// one register: enabling a channel while another is being enabled elsewhere —
/// from an interrupt, say — can lose one of the two writes.
pub struct PwmChannel<TIMERX, PIN, const C: u8> {
    timer: TIMERX,
    pin: PIN,
}

impl<TIMERX: PwmOps<C>, PIN: ChannelPin<TIMERX, C>, const C: u8> PwmChannel<TIMERX, PIN, C> {
    /// Drives the pin from the comparison, keeping the duty already set.
    pub fn enable(&self) {
        self.timer.set_chxen(true);
    }
    /// Stops driving the pin, leaving the channel configured.
    pub fn disable(&self) {
        self.timer.set_chxen(false);
    }

    /// Sets the duty, in timer ticks of the period.
    ///
    /// The output is active for `cv` ticks out of [`max_duty`](Self::max_duty),
    /// so zero is a permanently inactive pin and anything from `max_duty` up is
    /// a permanently active one. The new value reaches the output at the next
    /// rollover, not mid-period.
    pub fn set_duty(&self, cv: u16) {
        self.timer.set_chxcv(cv);
    }
    /// Returns the duty that corresponds to a fully active output.
    ///
    /// This is the period the counter is running on, `car() + 1` ticks, and it
    /// is also the resolution: a period of 100 ticks leaves 100 distinct duties.
    /// A period spanning the whole counter reports one tick short, being the
    /// only value that does not fit `u16`.
    pub fn max_duty(&self) -> u16 {
        self.timer.read_car().saturating_add(1)
    }

    /// Gives the pin back, dropping the channel.
    ///
    /// The output is left exactly as it was — still enabled, still driving its
    /// duty. Call [`disable`](Self::disable) first if the pin is wanted quiet.
    pub fn release(self) -> PIN {
        self.pin
    }
}

/// What can go wrong while reading a capture.
///
/// Its own type rather than a bare `Option`: a missing capture and a lost one
/// are different answers, and only the second means the value in hand is not
/// the one that was asked for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Error {
    /// An edge landed on a value that had not been read yet (`CHxOF`).
    ///
    /// The capture register holds the newer timestamp and the older one is gone,
    /// so an interval measured across this is wrong rather than merely late.
    Overcapture,
}

/// One capture input of a timer, configured and ready to be armed.
///
/// Channels of the same timer are independent in everything but the time base:
/// `PSC` belongs to the counter they share, so what one tick is worth is the
/// same for all of them. The edge and the latched value are the channel's own.
///
/// Each channel carries its own handle to the peripheral, which is what lets
/// four of them exist while the timer is a single value. Latching touches only
/// that channel's capture register, but the enables of all channels live in one
/// register: enabling a channel while another is being enabled elsewhere — from
/// an interrupt, say — can lose one of the two writes.
pub struct CaptureChannel<TIMERX, PIN, const C: u8> {
    timer: TIMERX,
    pin: PIN,
    clk: Hertz,
}

impl<TIMERX: CaptureOps<C>, PIN: ChannelPin<TIMERX, C>, const C: u8>
    CaptureChannel<TIMERX, PIN, C>
{
    /// Arms the channel, from here on latching the counter on every edge.
    pub fn enable(&self) {
        self.timer.set_chxen(true);
    }
    /// Stops latching, leaving the channel configured and its last value intact.
    pub fn disable(&self) {
        self.timer.set_chxen(false);
    }

    /// Changes which edge the channel latches on.
    ///
    /// Takes effect on the pin as it is called, so an edge arriving during the
    /// switch belongs to whichever setting won the race. Measurements spanning
    /// the change should be discarded rather than reasoned about.
    pub fn select_edge(&self, edge: Edge) {
        self.timer.select_edge(edge);
    }

    /// Takes the timestamp of the last edge, if one has arrived.
    ///
    /// Returns [`WouldBlock`](nb::Error::WouldBlock) while no edge has been
    /// latched since the previous read, so this can be polled and, wrapped in
    /// [`nb::block!`], waited on. Both flags are cleared on the way out, which
    /// is what makes the next call speak about the next edge.
    ///
    /// The value is the counter at the moment of the edge, not an interval —
    /// intervals come from feeding two of these to
    /// [`interval`](Self::interval).
    ///
    /// # Errors
    ///
    /// [`Error::Overcapture`] when a further edge arrived before this read: the
    /// timestamp handed back belongs to the later edge and the earlier one is
    /// lost. The channel keeps running, so the following read is sound again.
    pub fn read(&self) -> nb::Result<u16, Error> {
        if !self.timer.read_chxif() {
            return Err(nb::Error::WouldBlock);
        }
        let cv = self.timer.read_chxcv();
        let lost = self.timer.read_chxof();
        // Hardware only ever raises these flags, so both have to be taken down
        // here — left standing, `CHxIF` would report the same edge for ever.
        self.timer.clear_chxif();
        match lost {
            true => {
                self.timer.clear_chxof();
                Err(nb::Error::Other(Error::Overcapture))
            }
            false => Ok(cv),
        }
    }

    /// Converts the span between two timestamps into a duration.
    ///
    /// Takes them in the order they were captured and counts forward from the
    /// first, so a counter rollover in between costs nothing — the subtraction
    /// wraps exactly as the counter does, the reload being the full width of the
    /// register. Spans longer than one full counter cycle are indistinguishable
    /// from short ones and come back wrong; keep the prescaler large enough that
    /// the signal fits.
    ///
    /// The scale comes from the binding, as in
    /// [`elapsed`](CountDownTimer::elapsed): `let t: MicrosDuration =
    /// channel.interval(first, second);`.
    pub fn interval<const NOM: u64, const DENOM: u64>(
        &self,
        from: u16,
        to: u16,
    ) -> Duration<u32, NOM, DENOM> {
        ticks_to_interval(to.wrapping_sub(from), self.timer.read_psc(), self.clk)
    }

    /// Gives the pin back, dropping the channel.
    ///
    /// The channel is left exactly as it was — still armed if it was armed.
    /// Call [`disable`](Self::disable) first if it should stop latching.
    pub fn release(self) -> PIN {
        self.pin
    }
}

/// Writing a duty cannot fail: the value goes straight into a compare register
/// the hardware always accepts.
impl<TIMERX: PwmOps<C>, PIN: ChannelPin<TIMERX, C>, const C: u8> ErrorType
    for PwmChannel<TIMERX, PIN, C>
{
    type Error = Infallible;
}

/// Duty control for portable drivers, delegating to [`PwmChannel::set_duty`].
///
/// The trait's `set_duty_cycle_percent`, `_fraction`, `_fully_on` and
/// `_fully_off` are its own defaults built on these two, and scale against the
/// period the timer currently runs on.
impl<TIMERX: PwmOps<C>, PIN: ChannelPin<TIMERX, C>, const C: u8> SetDutyCycle
    for PwmChannel<TIMERX, PIN, C>
{
    fn max_duty_cycle(&self) -> u16 {
        self.max_duty()
    }
    fn set_duty_cycle(&mut self, duty: u16) -> Result<(), Self::Error> {
        self.set_duty(duty);
        Ok(())
    }
}

/// Which edge on the pin makes a channel take its snapshot.
///
/// A runtime value rather than a typestate: the edge changes what the hardware
/// reacts to on the wire, but no method signature depends on it.
///
/// Discriminants are the `CHxP` register encoding. Capturing on both edges is
/// not offered because the hardware has no such setting — the encoding that
/// would express it is reserved on every timer of this part.
#[derive(Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[allow(missing_docs)]
pub enum Edge {
    Rising,
    Falling,
}

/// The input capture half of one channel, numbered by `C` like [`PwmOps`].
///
/// Mirrors the output side: the channel points its pin at the counter instead
/// of the other way round, and every register difference between timers and
/// between channels stays inside the implementations.
pub trait CaptureOps<const C: u8>: ChannelEnable<C> {
    /// Points the channel at its pin and readies it to latch the counter.
    ///
    /// Covers the one-time fields as a group — direction plus the input filter
    /// and the capture prescaler — for the same reason the output side does: a
    /// channel left pointing at its comparator captures nothing, and the fields
    /// are only correct together.
    fn apply_capture_mode(&self);
    /// Chooses the edge the channel takes its snapshot on.
    fn select_edge(&self, edge: Edge);
    /// Reads the counter value the last edge latched.
    ///
    /// Says nothing about whether an edge ever arrived: the register holds
    /// whatever it held before, so the value only means something once
    /// [`read_chxif`](CaptureOps::read_chxif) has confirmed a capture.
    fn read_chxcv(&self) -> u16;
    /// Capture flag — set by hardware on every capture, never cleared by it.
    fn read_chxif(&self) -> bool;
    /// Clears the capture flag.
    fn clear_chxif(&self);
    /// Overcapture flag — set when an edge lands on a value not yet read.
    fn read_chxof(&self) -> bool;
    /// Clears the overcapture flag.
    fn clear_chxof(&self);
}

macro_rules! capture {
    {$($Timer:ty => [
        $(
            ($Ch:expr, ($chctl_reg:ident, $chms:ident, $ci:ident, $capflt:ident, $cappsc:ident), ($chcv:ident, $chval:ident), ($chp:ident $(, $chnp:ident)?), $chif:ident, $chof:ident$(,)?)$(,)?
        )+]$(,)?)+
    } => {
        $($(impl CaptureOps<$Ch> for $Timer {
            fn apply_capture_mode(&self) {
                // `CHxNP` is only present on the channels that have a
                // complementary output — channel 3 has neither, and there the
                // bit the table pairs with `CHxP` is simply hardwired to zero.
                $(self.chctl2().modify(|_, w| w.$chnp().not_inverted());)?
                self.$chctl_reg().modify(|_, w| {
                    w.$chms()
                        .$ci()
                        .$capflt()
                        .no_filter()
                        .$cappsc()
                        .div1()
                })
            }
            fn select_edge(&self, edge: Edge) {
                self.chctl2().modify(|_, w| match edge {
                    Edge::Rising => w.$chp().not_inverted(),
                    Edge::Falling => w.$chp().inverted()
                })
            }
            fn read_chxcv(&self) -> u16 {
                self.$chcv().read().$chval().bits()
            }
            fn read_chxif(&self) -> bool {
                self.intf().read().$chif().bit_is_set()
            }
            fn clear_chxif(&self) {
                self.intf().modify(|_, w| w.$chif().clear())
            }
            fn read_chxof(&self) -> bool {
                self.intf().read().$chof().bit_is_set()
            }
            fn clear_chxof(&self) {
                self.intf().modify(|_, w| w.$chof().clear())
            }
        })+)+
    };
}

capture! {
    pac::Timer0 => [(0, (chctl0_input, ch0ms, ci0, ch0capflt, ch0cappsc), (ch0cv, ch0val), (ch0p, ch0np), ch0if, ch0of),
        (1, (chctl0_input, ch1ms, ci0, ch1capflt, ch1cappsc), (ch1cv, ch1val), (ch1p, ch1np), ch1if, ch1of),
        (2, (chctl1_input, ch2ms, ci0, ch2capflt, ch2cappsc), (ch2cv, ch2val), (ch2p, ch2np), ch2if, ch2of),
        (3, (chctl1_input, ch3ms, ci0, ch3capflt, ch3cappsc), (ch3cv, ch3val), (ch3p), ch3if, ch3of)],
    pac::Timer2 => [(0, (chctl0_input, ch0ms, ci0, ch0capflt, ch0cappsc), (ch0cv, ch0val), (ch0p, ch0np), ch0if, ch0of),
        (1, (chctl0_input, ch1ms, ci0, ch1capflt, ch1cappsc), (ch1cv, ch1val), (ch1p, ch1np), ch1if, ch1of),
        (2, (chctl1_input, ch2ms, ci0, ch2capflt, ch2cappsc), (ch2cv, ch2val), (ch2p, ch2np), ch2if, ch2of),
        (3, (chctl1_input, ch3ms, ci0, ch3capflt, ch3cappsc), (ch3cv, ch3val), (ch3p), ch3if, ch3of)],
    pac::Timer13 => [(0, (chctl0_input, ch0ms, ci0, ch0capflt, ch0cappsc), (ch0cv, ch0val), (ch0p, ch0np), ch0if, ch0of)],
    pac::Timer14 => [(0, (chctl0_input, ch0ms, ci0, ch0capflt, ch0cappsc), (ch0cv, ch0val), (ch0p, ch0np), ch0if, ch0of),
        (1, (chctl0_input, ch1ms, ci0, ch1capflt, ch1cappsc), (ch1cv, ch1val), (ch1p, ch1np), ch1if, ch1of)],
    pac::Timer15 => [(0, (chctl0_input, ch0ms, ci0, ch0capflt, ch0cappsc), (ch0cv, ch0val), (ch0p, ch0np), ch0if, ch0of)],
    pac::Timer16 => [(0, (chctl0_input, ch0ms, ci0, ch0capflt, ch0cappsc), (ch0cv, ch0val), (ch0p, ch0np), ch0if, ch0of)]
}