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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
//! Provides support for timers. Includes initialization, interrupts,
//! and PWM features.
//!
//! Low-power timers (LPTIM) are not yet supported.

// todo: WB and WL should support pwm features

use core::ops::Deref;

use num_traits::float::Float;

use cortex_m::interrupt::free;

#[cfg(feature = "embedded-hal")]
use embedded_hal::{
    blocking::delay::{DelayMs, DelayUs},
    timer::Periodic,
};

// todo: LPTIM (low-power timers) and HRTIM (high-resolution timers). And Advanced control functionality

use crate::{
    clocks::Clocks,
    pac::{self, RCC},
    rcc_en_reset,
    util::RccPeriph,
};

#[cfg(feature = "g0")]
use crate::pac::dma as dma_p;
#[cfg(any(
    feature = "f3",
    feature = "l4",
    feature = "g4",
    feature = "h7",
    feature = "wb",
    feature = "wl"
))]
use crate::pac::dma1 as dma_p;

#[cfg(not(any(feature = "f4", feature = "l5")))]
use crate::dma::{self, ChannelCfg, Dma, DmaChannel};

#[cfg(any(feature = "f3", feature = "l4"))]
use crate::dma::DmaInput;

use cfg_if::cfg_if;
use paste::paste;

// todo: Low power timer enabling etc. eg on L4, RCC_APB1ENR1.LPTIM1EN

#[derive(Clone, Copy, Debug)]
/// Used for when attempting to set a timer period that is out of range.
pub struct ValueError {}

#[derive(Clone, Copy)]
#[repr(u8)]
/// These bits allow selected information to be sent in master mode to slave timers for
/// synchronization (TRGO). Sets CR2 register, MMS field.
pub enum MasterModeSelection {
    /// Tthe UG bit from the TIMx_EGR register is used as trigger output (TRGO). If the
    /// reset is generated by the trigger input (slave mode controller configured in reset mode) then
    /// the signal on TRGO is delayed compared to the actual reset.
    Reset = 0b000,
    /// the Counter Enable signal CNT_EN is used as trigger output (TRGO). It is
    /// useful to start several timers at the same time or to control a window in which a slave timer is
    /// enable. The Counter Enable signal is generated by a logic AND between CEN control bit
    /// and the trigger input when configured in gated mode. When the Counter Enable signal is
    /// controlled by the trigger input, there is a delay on TRGO, except if the master/slave mode is
    /// selected (see the MSM bit description in TIMx_SMCR register).
    Enable = 0b001,
    /// The update event is selected as trigger output (TRGO). For instance a master
    /// timer can then be used as a prescaler for a slave timer.
    Update = 0b010,
    /// Compare Pulse - The trigger output send a positive pulse when the CC1IF flag is to be
    /// set (even if it was already high), as soon as a capture or a compare match occurred.
    /// (TRGO).
    ComparePulse = 0b011,
    /// OC1REF signal is used as trigger output (TRGO)
    Compare1 = 0b100,
    /// OC2REF signal is used as trigger output (TRGO)
    Compare2 = 0b101,
    /// OC3REF signal is used as trigger output (TRGO)
    Compare3 = 0b110,
    /// OC4REF signal is used as trigger output (TRGO)
    Compare4 = 0b111,
}

/// Timer interrupt
pub enum TimerInterrupt {
    /// Update interrupt can be used for a timeout. DIER UIE to set, ... to clear
    Update,
    /// Trigger. DIER TIE to set, ... to clear
    Trigger,
    /// Capture/Compare. CC1IE to set, ... to clear
    CaptureCompare1,
    /// Capture/Compare. CC2IE to set, ... to clear
    CaptureCompare2,
    /// Capture/Compare. CC3IE to set, ... to clear
    CaptureCompare3,
    /// Capture/Compare. CC4IE to set, ... to clear
    CaptureCompare4,
    /// Update DMA. DIER UDE to set, ... to clear
    UpdateDma,
    /// Drigger. TDE to set, ... to clear
    TriggerDma,
    /// Capture/Compare. CC1DE to set, ... to clear
    CaptureCompare1Dma,
    /// Capture/Compare. CC2DE to set, ... to clear
    CaptureCompare2Dma,
    /// Capture/Compare. CC3DE to set, ... to clear
    CaptureCompare3Dma,
    /// Capture/Compare. CC4DE to set, ... to clear
    CaptureCompare4Dma,
}

/// Output alignment. Sets `TIMx_CR1` register, `CMS` field.
#[derive(Clone, Copy)]
pub enum Alignment {
    /// Edge-aligned mode. The counter counts up or down depending on the direction bit
    /// (DIR).
    Edge = 0b00,
    /// Center-aligned mode 1. The counter counts up and down alternatively. Output compare
    /// interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set
    /// only when the counter is counting down.
    Center1 = 0b01,
    /// Center-aligned mode 2. The counter counts up and down alternatively. Output compare
    /// interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set
    /// only when the counter is counting up.
    Center2 = 0b10,
    /// Center-aligned mode 3. The counter counts up and down alternatively. Output compare
    /// interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set
    /// both when the counter is counting up or down.
    Center3 = 0b11,
}

/// Timer channel
#[derive(Clone, Copy)]
pub enum TimChannel {
    C1,
    C2,
    C3,
    #[cfg(not(feature = "wl"))]
    C4,
}

/// Timer count direction
#[repr(u8)]
#[derive(Clone, Copy)]
pub enum CountDir {
    Up = 0,
    Down = 1,
}

/// Capture/Compare selection.
/// This field defines the direction of the channel (input/output) as well as the used input.
/// It affects the TIMx_CCMR1 register, CCxS fields.
#[repr(u8)]
#[derive(Clone, Copy)]
pub enum CaptureCompare {
    Output = 0b00,
    InputTi1 = 0b01,
    InputTi2 = 0b10,
    InputTrc = 0b11,
}

/// Capture/Compare output polarity. Defaults to `ActiveHigh` in hardware. Sets TIMx_CCER register,
/// CCxP and CCXNP fields.
#[derive(Clone, Copy)]
pub enum Polarity {
    ActiveHigh,
    ActiveLow,
}

impl Polarity {
    /// For use with `set_bit()`.
    fn bit(&self) -> bool {
        match self {
            Self::ActiveHigh => false,
            Self::ActiveLow => true,
        }
    }
}

#[derive(Clone, Copy)]
#[repr(u8)]
/// See F303 ref man, section 21.4.7. H745 RM, section 41.4.8. Sets TIMx_CCMR1 register, OC1M field.
/// These bits define the behavior of the output reference signal OC1REF from which OC1 and
/// OC1N are derived. OC1REF is active high whereas OC1 and OC1N active level depends
/// on CC1P and CC1NP bits.
pub enum OutputCompare {
    /// Frozen - The comparison between the output compare register TIMx_CCR1 and the
    /// counter TIMx_CNT has no effect on the outputs.(this mode is used to generate a timing
    /// base).
    Frozen = 0b0000,
    /// Set channel 1 to active level on match. OC1REF signal is forced high when the
    /// counter TIMx_CNT matches the capture/compare register 1 (TIMx_CCR1).
    Active = 0b0001,
    /// Set channel 1 to inactive level on match. OC1REF signal is forced low when the
    /// counter TIMx_CNT matches the capture/compare register 1 (TIMx_CCR1).
    /// 0011: Toggle - OC1REF toggles when TIMx_CNT=TIMx_CCR1.
    Inactive = 0b0010,
    /// tim_oc1ref toggles when TIMx_CNT=TIMx_CCR1.
    Toggle = 0b0011,
    /// Force inactive level - OC1REF is forced low.
    ForceInactive = 0b0100,
    /// Force active level - OC1REF is forced high.
    ForceActive = 0b0101,
    /// PWM mode 1 - In upcounting, channel 1 is active as long as TIMx_CNT<TIMx_CCR1
    /// else inactive. In downcounting, channel 1 is inactive (OC1REF=‘0) as long as
    /// TIMx_CNT>TIMx_CCR1 else active (OC1REF=1).
    Pwm1 = 0b0110,
    /// PWM mode 2 - In upcounting, channel 1 is inactive as long as
    /// TIMx_CNT<TIMx_CCR1 else active. In downcounting, channel 1 is active as long as
    /// TIMx_CNT>TIMx_CCR1 else inactive.
    Pwm2 = 0b0111,
    /// Retriggerable OPM mode 1 - In up-counting mode, the channel is active until a trigger
    /// event is detected (on TRGI signal). Then, a comparison is performed as in PWM mode 1
    /// and the channels becomes inactive again at the next update. In down-counting mode, the
    /// channel is inactive until a trigger event is detected (on TRGI signal). Then, a comparison is
    /// performed as in PWM mode 1 and the channels becomes inactive again at the next update.
    RetriggerableOpmMode1 = 0b1000,
    /// Retriggerable OPM mode 2 - In up-counting mode, the channel is inactive until a
    /// trigger event is detected (on TRGI signal). Then, a comparison is performed as in PWM
    /// mode 2 and the channels becomes inactive again at the next update. In down-counting
    /// mode, the channel is active until a trigger event is detected (on TRGI signal). Then, a
    /// comparison is performed as in PWM mode 1 and the channels becomes active again at the
    /// next update.
    RetriggerableOpmMode2 = 0b1001,
    /// Combined PWM mode 1 - OC1REF has the same behavior as in PWM mode 1.
    /// OC1REFC is the logical OR between OC1REF and OC2REF.
    CombinedPwm1 = 0b1100,
    /// Combined PWM mode 2 - OC1REF has the same behavior as in PWM mode 2.
    /// OC1REFC is the logical AND between OC1REF and OC2REF.
    CombinedPwm2 = 0b1101,
    /// Asymmetric PWM mode 1 - OC1REF has the same behavior as in PWM mode 1.
    /// OC1REFC outputs OC1REF when the counter is counting up, OC2REF when it is counting
    /// down.
    AsymmetricPwm1 = 0b1110,
    /// Asymmetric PWM mode 2 - OC1REF has the same behavior as in PWM mode 2.
    /// /// OC1REFC outputs OC1REF when the counter is counting up, OC2REF when it is counting
    /// down
    AsymmetricPwm2 = 0b1111,
}

/// Update Request source. This bit is set and cleared by software to select the UEV event sources.
/// Sets `TIMx_CR1` register, `URS` field.
#[derive(Clone, Copy)]
#[repr(u8)]
pub enum UpdateReqSrc {
    /// Any of the following events generate an update interrupt or DMA request.
    /// These events can be:
    /// – Counter overflow/underflow
    /// – Setting the UG bit
    /// – Update generation through the slave mode controller
    Any = 0,
    /// Only counter overflow/underflow generates an update interrupt or DMA request.
    OverUnderFlow = 1,
}

/// Capture/Compaer DMA selection.
/// Sets `TIMx_CR2` register, `CCDS` field.
#[derive(Clone, Copy)]
#[repr(u8)]
pub enum CaptureCompareDma {
    /// CCx DMA request sent when CCx event occur
    Ccx = 0,
    /// CCx DMA request sent when update event occurs
    Update = 1,
}

/// Initial configuration data for Timer peripherals.
#[derive(Clone)]
pub struct TimerConfig {
    /// If `one_pulse_mode` is true, the counter stops counting at the next update event
    /// (clearing the bit CEN). If false, Counter is not stopped at update event. Defaults to false.
    /// Sets `TIMx_CR` register, `OPM` field.
    pub one_pulse_mode: bool,
    /// Update request source. Ie, counter overflow/underflow only, or any. defaults to any.
    pub update_request_source: UpdateReqSrc,
    /// Set `true` to buffer the preload. Useful when changing period and duty while the timer is running.
    /// Default to false.
    pub auto_reload_preload: bool,
    /// Select center or edge alignment. Defaults to edge.
    pub alignment: Alignment,
    /// Sets when CCx DMA requests occur. Defaults to on CCx event.
    pub capture_compare_dma: CaptureCompareDma,
    /// Timer counting direction. Defaults to up.
    pub direction: CountDir,
}

impl Default for TimerConfig {
    fn default() -> Self {
        Self {
            one_pulse_mode: false,
            update_request_source: UpdateReqSrc::Any,
            auto_reload_preload: false,
            alignment: Alignment::Edge,
            capture_compare_dma: CaptureCompareDma::Ccx,
            direction: CountDir::Up,
        }
    }
}

/// Represents a General Purpose or Advanced Control timer.
pub struct Timer<TIM> {
    pub regs: TIM, // Register block for the specific timer.
    pub cfg: TimerConfig,
    clock_speed: u32, // Associated timer clock speed in Hz.
}

macro_rules! make_timer {
    ($TIMX:ident, $tim:ident, $apb:expr, $res:ident) => {
        impl Timer<pac::$TIMX> {
            paste! {
                /// Initialize a DFSDM peripheral, including  enabling and resetting
                /// its RCC peripheral clock.
                pub fn [<new_ $tim>](regs: pac::$TIMX, freq: f32, cfg: TimerConfig, clocks: &Clocks) -> Self {
                    free(|_| {
                        let rcc = unsafe { &(*RCC::ptr()) };

                        // `freq` is in Hz.
                        rcc_en_reset!([<apb $apb>], $tim, rcc);
                    });

                    let clock_speed = match $apb {
                        1 => clocks.apb1_timer(),
                        _ => clocks.apb2_timer(),
                    };


                    regs.cr1.modify(|_, w| {
                        #[cfg(not(feature = "f373"))]
                        w.opm().bit(cfg.one_pulse_mode);
                        w.urs().bit(cfg.update_request_source as u8 != 0);
                        w.arpe().bit(cfg.auto_reload_preload)
                    });

                    #[cfg(not(feature = "f373"))]
                    regs.cr2.modify(|_, w| {
                        w.ccds().bit(cfg.capture_compare_dma as u8 != 0)
                    });

                    let mut result = Timer { clock_speed, cfg, regs };

                    result.set_freq(freq).ok();
                    result.set_dir();

                    // Trigger an update event to load the prescaler value to the clock
                    // NOTE(write): uses all bits in this register. This also clears the interrupt flag,
                    // which the EGER update will generate.
                    result.reinitialize();

                    result
                }
            }
            /// Enable a specific type of Timer interrupt.
            pub fn enable_interrupt(&mut self, interrupt: TimerInterrupt) {
                match interrupt {
                    TimerInterrupt::Update => self.regs.dier.modify(|_, w| w.uie().set_bit()),
                    // todo: Only DIER is in PAC, or some CCs. PAC BUG? Only avail on some timers/MCUs?
                    // TimerInterrupt::Trigger => self.regs.dier.modify(|_, w| w.tie().set_bit()),
                    // TimerInterrupt::CaptureCompare1 => self.regs.dier.modify(|_, w| w.cc1ie().set_bit()),
                    // TimerInterrupt::CaptureCompare2 => self.regs.dier.modify(|_, w| w.cc2ie().set_bit()),
                    // TimerInterrupt::CaptureCompare3 => self.regs.dier.modify(|_, w| w.cc3ie().set_bit()),
                    // TimerInterrupt::CaptureCompare4 => self.regs.dier.modify(|_, w| w.cc4ie().set_bit()),
                    #[cfg(not(feature = "f3"))] // todo: Not working on some variants
                    TimerInterrupt::UpdateDma => self.regs.dier.modify(|_, w| w.ude().set_bit()),
                    // TimerInterrupt::TriggerDma => self.regs.dier.modify(|_, w| w.tde().set_bit()),
                    // TimerInterrupt::CaptureCompare1Dma => self.regs.dier.modify(|_, w| w.cc1de().set_bit()),
                    // TimerInterrupt::CaptureCompare2Dma => self.regs.dier.modify(|_, w| w.ccd2de().set_bit()),
                    // TimerInterrupt::CaptureCompare3Dma => self.regs.dier.modify(|_, w| w.cc3de().set_bit()),
                    // TimerInterrupt::CaptureCompare4Dma => self.regs.dier.modify(|_, w| w.cc4de().set_bit()),
                    _ => unimplemented!("TODO TEMP PROBLEMS"),
                }
            }

            /// Disable a specific type of Timer interrupt.
            pub fn disable_interrupt(&mut self, interrupt: TimerInterrupt) {
                match interrupt {
                    TimerInterrupt::Update => self.regs.dier.modify(|_, w| w.uie().clear_bit()),
                    // todo: Only DIER is in PAC, or some CCs. PAC BUG? Only avail on some timers/MCUs?
                    // TimerInterrupt::Trigger => self.regs.dier.modify(|_, w| w.tie().clear_bit()),
                    // TimerInterrupt::CaptureCompare1 => self.regs.dier.modify(|_, w| w.cc1ie().clear_bit()),
                    // TimerInterrupt::CaptureCompare2 => self.regs.dier.modify(|_, w| w.cc2ie().clear_bit()),
                    // TimerInterrupt::CaptureCompare3 => self.regs.dier.modify(|_, w| w.cc3ie().clear_bit()),
                    // TimerInterrupt::CaptureCompare4 => self.regs.dier.modify(|_, w| w.cc4ie().clear_bit()),
                    #[cfg(not(feature = "f3"))] // todo: Not working on some variants
                    TimerInterrupt::UpdateDma => self.regs.dier.modify(|_, w| w.ude().clear_bit()),
                    // TimerInterrupt::TriggerDma => self.regs.dier.modify(|_, w| w.tde().clear_bit()),
                    // TimerInterrupt::CaptureCompare1Dma => self.regs.dier.modify(|_, w| w.cc1de().clear_bit()),
                    // TimerInterrupt::CaptureCompare2Dma => self.regs.dier.modify(|_, w| w.ccd2de().clear_bit()),
                    // TimerInterrupt::CaptureCompare3Dma => self.regs.dier.modify(|_, w| w.cc3de().clear_bit()),
                    // TimerInterrupt::CaptureCompare4Dma => self.regs.dier.modify(|_, w| w.cc4de().clear_bit()),
                    _ => unimplemented!("TODO TEMP PROBLEMS"),
                }
            }

            /// Clears interrupt associated with this timer.
            ///
            /// If the interrupt is not cleared, it will immediately retrigger after
            /// the ISR has finished. For examlpe, place this at the top of your timer's
            /// interrupt handler.
            pub fn clear_interrupt(&mut self, interrupt: TimerInterrupt) {
                // Note that unlike other clear interrupt functions, for this, we clear the bit instead
                // of setting it. Due to the way our SVDs are set up not working well with this atomic clear,
                // we need to make sure we write 1s to the rest of the bits.
                // todo: Overcapture flags for each CC? DMA interrupts?
                unsafe {
                    match interrupt {
                        TimerInterrupt::Update => self
                            .regs
                            .sr
                            .write(|w| w.bits(0xffff_ffff).uif().clear_bit()),
                        // todo: Only DIER is in PAC, or some CCs. PAC BUG? Only avail on some timers?
                        // TimerInterrupt::Trigger => self.regs.sr.write(|w| w.bits(0xffff_ffff).tif().clear_bit()),
                        // TimerInterrupt::CaptureCompare1 => self.regs.sr.write(|w| w.bits(0xffff_ffff).cc1if().clear_bit()),
                        // TimerInterrupt::CaptureCompare2 => self.regs.sr.write(|w| w.bits(0xffff_ffff).cc2if().clear_bit()),
                        // TimerInterrupt::CaptureCompare3 => self.regs.sr.write(|w| w.bits(0xffff_ffff).cc3if().clear_bit()),
                        // TimerInterrupt::CaptureCompare4 => self.regs.sr.write(|w| w.bits(0xffff_ffff).cc4if().clear_bit()),
                        _ => unimplemented!(
                            "Clearing DMA flags is unimplemented using this function."
                        ),
                    }
                }
            }

            /// Enable the timer.
            pub fn enable(&mut self) {
                self.regs.cr1.write(|w| w.cen().set_bit());
            }

            /// Disable the timer.
            pub fn disable(&mut self) {
                self.regs.cr1.modify(|_, w| w.cen().clear_bit());
            }

            /// Check if the timer is enabled.
            pub fn is_enabled(&self) -> bool {
                self.regs.cr1.read().cen().bit_is_set()
            }

            /// Set the timer frequency, in Hz. Overrides the period or frequency set
            /// in the constructor.
            pub fn set_freq(&mut self, mut freq: f32) -> Result<(), ValueError> {
                assert!(freq > 0.);
                // todo: Take into account the `timxsw` bit in RCC CFGR3, which may also
                // todo require an adjustment to freq.
                match self.cfg.alignment {
                    Alignment::Edge => (),
                    _ => freq *= 2.,
                }

                let (psc, arr) = calc_freq_vals(freq, self.clock_speed)?;

                self.regs.arr.write(|w| unsafe { w.bits(arr.into()) });
                self.regs.psc.write(|w| unsafe { w.bits(psc.into()) });

                Ok(())
            }

            /// Set the timer period, in seconds. Overrides the period or frequency set
            /// in the constructor.
            pub fn set_period(&mut self, period: f32) -> Result<(), ValueError> {
                assert!(period > 0.);
                self.set_freq(1. / period)
            }

            /// Set the auto-reload register value. Used for adjusting frequency.
            pub fn set_auto_reload(&mut self, arr: u32) {
                // todo: Could be u16 or u32 depending on timer resolution,
                // todo but this works for now.
                self.regs.arr.write(|w| unsafe { w.bits(arr.into()) });
            }

            /// Set the prescaler value. Used for adjusting frequency.
            pub fn set_prescaler(&mut self, psc: u16) {
                self.regs.psc.write(|w| unsafe { w.bits(psc.into()) });
            }

            /// Reset the countdown; set the counter to 0.
            pub fn reset_countdown(&mut self) {
                self.regs.cnt.write(|w| unsafe { w.bits(0) });
            }

            /// Re-initialize the counter and generates an update of the registers. Note that the prescaler
            /// counter is cleared too (anyway the prescaler ratio is not affected). The counter is cleared.
            /// When changing timer frequency (or period) via PSC, you may need to run this. Alternatively, change
            /// the freq in an update ISR.
            /// Note from RM, PSC reg: PSC contains the value to be loaded in the active prescaler
            /// register at each update event
            /// (including when the counter is cleared through UG bit of TIMx_EGR register or through
            /// trigger controller when configured in “reset mode”).'
            /// If you're doing something where the updates can wait a cycle, this isn't required. (eg PWM
            /// with changing duty period).
            pub fn reinitialize(&mut self) {
                self.regs.egr.write(|w| w.ug().set_bit());
                self.clear_interrupt(TimerInterrupt::Update);
            }

            /// Read the current counter value.
            pub fn read_count(&self) -> u32 {
                // todo: This depends on resolution. We read the whole
                // todo res and pass a u32 just in case.
                // self.regs.cnt.read().cnt().bits()
                self.regs.cnt.read().bits()
            }


            /// Enables PWM output for a given channel and output compare, with an initial duty cycle, in Hz.
            pub fn enable_pwm_output(
                &mut self,
                channel: TimChannel,
                compare: OutputCompare,
                duty: f32,
            ) {
                // todo: duty as an f32 is good from an API perspective, but forces the
                // todo use of software floats on non-FPU MCUs. How should we handle this?
                self.set_preload(channel, true);
                self.set_output_compare(channel, compare);
                self.set_duty(channel, (self.get_max_duty() as f32 * duty) as $res);
                self.enable_capture_compare(channel);
            }

            /// Return the integer associated with the maximum duty period.
            pub fn get_max_duty(&self) -> $res {
                #[cfg(feature = "g0")]
                return self.regs.arr.read().bits().try_into().unwrap();
                #[cfg(not(feature = "g0"))]
                self.regs.arr.read().arr().bits().try_into().unwrap()
            }

             /// See G4 RM, section 29.4.24: Dma burst mode. "The TIMx timers have the capability to
             /// generate multiple DMA requests upon a single event.
             /// The main purpose is to be able to re-program part of the timer multiple times without
             /// software overhead, but it can also be used to read several registers in a row, at regular
             /// intervals."
            #[cfg(not(any(feature = "g0", feature = "f4", feature = "l5", feature = "f3", feature = "l4")))]
            pub unsafe fn write_dma_burst<D>(
                &mut self,
                buf: &[u16],
                base_address: u8,
                burst_len: u8,
                dma_channel: DmaChannel,
                channel_cfg: ChannelCfg,
                dma: &mut Dma<D>,
                ds_32_bits: bool,
            ) where
                D: Deref<Target = dma_p::RegisterBlock>,
            {
                // Note: F3 and L4 are unsupported here, since I'm not sure how to select teh
                // correct Timer channel.

                // todo: Should we disable the timer here?

                let (ptr, len) = (buf.as_ptr(), buf.len());

                // todo: DMA2 support.

                // todo: For F3 and L4, manually set channel using PAC for now. Currently
                // todo we don't have a way here to pick the timer. Could do it with a new macro arg.

                // L44 RM, Table 41. "DMA1 requests for each channel"
                // #[cfg(any(feature = "f3", feature = "l4"))]
                // let dma_channel = match tim_channel {
                //     // SaiChannel::A => DmaInput::Sai1A.dma1_channel(),
                // };
                //
                // #[cfg(feature = "l4")]
                // match tim_channel {
                //     SaiChannel::B => dma.channel_select(DmaInput::Sai1B),
                // };

                // RM:
                // This example is for the case where every CCRx register has to be updated once. If every
                // CCRx register is to be updated twice for example, the number of data to transfer should be
                // 6. Let's take the example of a buffer in the RAM containing data1, data2, data3, data4, data5
                // and data6. The data is transferred to the CCRx registers as follows: on the first update DMA
                // request, data1 is transferred to CCR2, data2 is transferred to CCR3, data3 is transferred to
                // CCR4 and on the second update DMA request, data4 is transferred to CCR2, data5 is
                // transferred to CCR3 and data6 is transferred to CCR4.

                // 1. Configure the corresponding DMA channel as follows:
                // –DMA channel peripheral address is the DMAR register address
                let periph_addr = &self.regs.dmar as *const _ as u32;
                // –DMA channel memory address is the address of the buffer in the RAM containing
                // the data to be transferred by DMA into CCRx registers.

                // Number of data to transfer is our buffer len number of registers we're editing, x
                // number of half-words written to each reg.
                #[cfg(feature = "h7")]
                let num_data = len as u32;
                #[cfg(not(feature = "h7"))]
                let num_data = len as u16;

                // 2.
                // Configure the DCR register by configuring the DBA and DBL bit fields as follows:
                // DBL = 3 transfers, DBA = 0xE.

                // The DBL[4:0] bits in the TIMx_DCR register set the DMA burst length. The timer recognizes
                // a burst transfer when a read or a write access is done to the TIMx_DMAR address), i.e. the
                // number of transfers (either in half-words or in bytes).
                // The DBA[4:0] bits in the TIMx_DCR registers define the DMA base address for DMA
                // transfers (when read/write access are done through the TIMx_DMAR address). DBA is
                // defined as an offset starting from the address of the TIMx_CR1 register:
                // Example:
                // 00000: TIMx_CR1
                // 00001: TIMx_CR2
                // 00010: TIMx_SMCR
                self.regs.dcr.modify(|_, w| {
                    w.dba().bits(base_address);
                    w.dbl().bits(burst_len as u8 - 1)
                });

                // 3. Enable the TIMx update DMA request (set the UDE bit in the DIER register).
                // note: Leaving this to application code for now.
                // self.enable_interrupt(TimerInterrupt::UpdateDma);

                // 4. Enable TIMx
                self.enable();

                // 5. Enable the DMA channel
                dma.cfg_channel(
                    dma_channel,
                    periph_addr,
                    ptr as u32,
                    num_data,
                    dma::Direction::ReadFromMem,
                    // Note: This may only be relevant if modifying a reg that changes for 32-bit
                    // timers, like AAR and CCRx
                    if ds_32_bits { dma::DataSize::S32} else { dma::DataSize::S16 },
                    dma::DataSize::S16,
                    channel_cfg,
                );
            }
        }

        #[cfg(feature = "embedded-hal")]
        // #[cfg_attr(docsrs, doc(cfg(feature = "embedded-hal")))]
        impl DelayMs<u32> for Timer<pac::$TIMX> {
            fn delay_ms(&mut self, ms: u32) {
                self.delay_us(ms as u32 * 1_000);
            }
        }

        #[cfg(feature = "embedded-hal")]
        // #[cfg_attr(docsrs, doc(cfg(feature = "embedded-hal")))]
        impl DelayMs<u16> for Timer<pac::$TIMX> {
            fn delay_ms(&mut self, ms: u16) {
                self.delay_us(ms as u32 * 1_000);
            }
        }

        #[cfg(feature = "embedded-hal")]
        // #[cfg_attr(docsrs, doc(cfg(feature = "embedded-hal")))]
        impl DelayMs<u8> for Timer<pac::$TIMX> {
            fn delay_ms(&mut self, ms: u8) {
                self.delay_us(ms as u32 * 1_000);
            }
        }

        #[cfg(feature = "embedded-hal")]
        // #[cfg_attr(docsrs, doc(cfg(feature = "embedded-hal")))]
        impl DelayUs<u32> for Timer<pac::$TIMX> {
            fn delay_us(&mut self, us: u32) {
                self.set_freq(1. / (us as f32 * 1_000.)).ok();
                self.reset_countdown();
                self.enable();
                while self.read_count() != 0 {}
                self.disable();
            }
        }

        #[cfg(feature = "embedded-hal")]
        // #[cfg_attr(docsrs, doc(cfg(feature = "embedded-hal")))]
        impl DelayUs<u16> for Timer<pac::$TIMX> {
            fn delay_us(&mut self, us: u16) {
                self.delay_us(us as u32);
            }
        }

        #[cfg(feature = "embedded-hal")]
        // #[cfg_attr(docsrs, doc(cfg(feature = "embedded-hal")))]
        impl DelayUs<u8> for Timer<pac::$TIMX> {
            fn delay_us(&mut self, us: u8) {
                self.delay_us(us as u32);
            }
        }

        #[cfg(feature = "embedded-hal")]
        // #[cfg_attr(docsrs, doc(cfg(feature = "embedded-hal")))]
        impl Periodic for Timer<pac::$TIMX> {}
    }
}

// We use macros to support the varying number of capture compare channels available on
// different timers.
// Note that there's lots of DRY between these implementations.
macro_rules! cc_4_channels {
    ($TIMX:ident, $res:ident) => {
        impl Timer<pac::$TIMX> {
            /// Function that allows us to set direction only on timers that have this option.
            pub fn set_dir(&mut self) {
                self.regs.cr1.modify(|_, w| w.dir().bit(self.cfg.direction as u8 != 0));
                self.regs.cr1.modify(|_, w| unsafe { w.cms().bits(self.cfg.alignment as u8) });
            }

            /// Enables basic PWM input. TODO: Doesn't work yet.
            /// L4 RM, section 26.3.8
            pub fn _enable_pwm_input(
                &mut self,
                _channel: TimChannel,
                _compare: OutputCompare,
                _dir: CountDir,
                _duty: f32,
            ) {
                // todo: These instruction sare specifically for TI1
                // 1. Select the active input for TIMx_CCR1: write the CC1S bits to 01 in the TIMx_CCMR1
                // register (TI1 selected).
                // self.regs.ccmr1.modify(|_, w| w.cc1s().bit(0b01));

                // 2. Select the active polarity for TI1FP1 (used both for capture in TIMx_CCR1 and counter
                // clear): write the CC1P and CC1NP bits to ‘0’ (active on rising edge).
                // self.regs.ccmr1.modify(|_, w| {
                //     w.cc1p().bits(0b00);
                //     w.cc1np().bits(0b00)
                // });
                // 3. Select the active input for TIMx_CCR2: write the CC2S bits to 10 in the TIMx_CCMR1
                // register (TI1 selected).
                // self.regs.ccmr2.modify(|_, w| w.cc2s().bit(0b10));

                // 4. Select the active polarity for TI1FP2 (used for capture in TIMx_CCR2): write the CC2P
                // and CC2NP bits to CC2P/CC2NP=’10’ (active on falling edge).
                // self.regs.ccr2.modify(|_, w| {
                //     w.cc2p().bits(0b10);
                //     w.cc2np().bits(0b10)
                // });

                // 5. Select the valid trigger input: write the TS bits to 101 in the TIMx_SMCR register
                // (TI1FP1 selected).
                // self.regs.smcr.modify(|_, w| w.ts().bits(0b101));

                // 6. Configure the slave mode controller in reset mode: write the SMS bits to 0100 in the
                // TIMx_SMCR register.
                // self.regs.smcr.modify(|_, w| w.sms().bits(0b0100));

                // 7. Enable the captures: write the CC1E and CC2E bits to ‘1’ in the TIMx_CCER register.
                // self.regs.ccer.modify(|_, w| {
                //     w.cc1e().set_bit();
                //     w.cc2e().set_bit()
                // });
            }

            // todo: more advanced PWM modes. Asymmetric, combined, center-aligned etc.

            /// Set Output Compare Mode. See docs on the `OutputCompare` enum.
            pub fn set_output_compare(&mut self, channel: TimChannel, mode: OutputCompare) {
                match channel {
                    TimChannel::C1 => {
                        self.regs.ccmr1_output().modify(|_, w| unsafe {
                            #[cfg(not(any(feature = "f3", feature = "f4", feature = "l5", feature = "wb")))]
                            w.oc1m_3().bit((mode as u8) >> 3 != 0);
                            w.oc1m().bits((mode as u8) & 0b111)
                        });
                    }
                    TimChannel::C2 => {
                        self.regs.ccmr1_output().modify(|_, w| unsafe {
                            #[cfg(not(any(feature = "f3", feature = "f4", feature = "l5", feature = "wb")))]
                            w.oc2m_3().bit((mode as u8) >> 3 != 0);
                            w.oc2m().bits((mode as u8) & 0b111)

                        });
                    }
                    TimChannel::C3 => {
                        self.regs.ccmr2_output().modify(|_, w| unsafe {
                            #[cfg(not(any(feature = "f3", feature = "f4", feature = "l5", feature = "wb")))]
                            w.oc3m_3().bit((mode as u8) >> 3 != 0);
                            w.oc3m().bits((mode as u8) & 0b111)

                        });
                    }
                    #[cfg(not(feature = "wl"))]
                    TimChannel::C4 => {
                        self.regs.ccmr2_output().modify(|_, w| unsafe {
                            #[cfg(not(any(feature = "f3", feature = "f4", feature = "l5", feature = "wb")))]
                            w.oc4m_3().bit((mode as u8) >> 3 != 0);
                            w.oc4m().bits((mode as u8) & 0b111)

                        });
                    }
                }
            }

            /// Return the set duty period for a given channel. Divide by `get_max_duty()`
            /// to find the portion of the duty cycle used.
            pub fn get_duty(&self, channel: TimChannel) -> $res {
                cfg_if! {
                    if #[cfg(feature = "g0")] {
                        match channel {
                            // todo: This isn't right!!
                            TimChannel::C1 => self.regs.ccr1.read().bits(),
                            TimChannel::C2 => self.regs.ccr2.read().bits(),
                            TimChannel::C3 => self.regs.ccr3.read().bits(),
                            #[cfg(not(feature = "wl"))]
                            TimChannel::C4 => self.regs.ccr4.read().bits(),
                        }
                    } else if #[cfg(any(feature = "wb", feature = "wl", feature = "l5"))] {
                        match channel {
                            TimChannel::C1 => self.regs.ccr1.read().ccr1().bits(),
                            TimChannel::C2 => self.regs.ccr2.read().ccr2().bits(),
                            TimChannel::C3 => self.regs.ccr3.read().ccr3().bits(),
                            #[cfg(not(feature = "wl"))]
                            TimChannel::C4 => self.regs.ccr4.read().ccr4().bits(),
                        }
                    } else {
                        match channel {
                            TimChannel::C1 => self.regs.ccr1.read().ccr().bits().into(),
                            TimChannel::C2 => self.regs.ccr2.read().ccr().bits().into(),
                            TimChannel::C3 => self.regs.ccr3.read().ccr().bits().into(),
                            #[cfg(not(feature = "wl"))]
                            TimChannel::C4 => self.regs.ccr4.read().ccr().bits().into(),
                        }
                    }
                }
            }

            /// Set the duty cycle, as a portion of ARR (`get_max_duty()`). Note that this
            /// needs to be re-run if you change ARR at any point.
            pub fn set_duty(&mut self, channel: TimChannel, duty: $res) {
                cfg_if! {
                    if #[cfg(feature = "g0")] {
                        match channel {
                            // todo: This isn't right!!
                            TimChannel::C1 => self.regs.ccr1.read().bits(),
                            TimChannel::C2 => self.regs.ccr2.read().bits(),
                            TimChannel::C3 => self.regs.ccr3.read().bits(),
                            #[cfg(not(feature = "wl"))]
                            TimChannel::C4 => self.regs.ccr4.read().bits(),
                        };
                    } else if #[cfg(any(feature = "wb", feature = "wl"))] {
                        unsafe {
                            match channel {
                                TimChannel::C1 => self.regs.ccr1.write(|w| w.ccr1().bits(duty.try_into().unwrap())),
                                TimChannel::C2 => self.regs.ccr2.write(|w| w.ccr2().bits(duty.try_into().unwrap())),
                                TimChannel::C3 => self.regs.ccr3.write(|w| w.ccr3().bits(duty.try_into().unwrap())),
                                #[cfg(not(feature = "wl"))]
                                TimChannel::C4 => self.regs.ccr4.write(|w| w.ccr4().bits(duty.try_into().unwrap())),
                            }
                        }
                    } else {
                        unsafe {
                            match channel {
                                TimChannel::C1 => self.regs.ccr1.write(|w| w.ccr().bits(duty.try_into().unwrap())),
                                TimChannel::C2 => self.regs.ccr2.write(|w| w.ccr().bits(duty.try_into().unwrap())),
                                TimChannel::C3 => self.regs.ccr3.write(|w| w.ccr().bits(duty.try_into().unwrap())),
                                #[cfg(not(feature = "wl"))]
                                TimChannel::C4 => self.regs.ccr4.write(|w| w.ccr().bits(duty.try_into().unwrap())),
                            }
                        }
                    }
                }
            }

            /// Set timer alignment to Edge, or one of 3 center modes.
            /// STM32F303 ref man, section 21.4.1:
            /// Bits 6:5 CMS: Center-aligned mode selection
            /// 00: Edge-aligned mode. The counter counts up or down depending on the direction bit
            /// (DIR).
            /// 01: Center-aligned mode 1. The counter counts up and down alternatively. Output compare
            /// interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set
            /// only when the counter is counting down.
            /// 10: Center-aligned mode 2. The counter counts up and down alternatively. Output compare
            /// interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set
            /// only when the counter is counting up.
            /// 11: Center-aligned mode 3. The counter counts up and down alternatively. Output compare
            /// interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set
            /// both when the counter is counting up or down.
            pub fn set_alignment(&mut self, alignment: Alignment) {
                self.regs.cr1.modify(|_, w| unsafe { w.cms().bits(alignment as u8) });
                self.cfg.alignment = alignment;
            }

            /// Set output polarity. See docs on the `Polarity` enum.
            pub fn set_polarity(&mut self, channel: TimChannel, polarity: Polarity) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1p().bit(polarity.bit())),
                    TimChannel::C2 => self.regs.ccer.modify(|_, w| w.cc2p().bit(polarity.bit())),
                    TimChannel::C3 => self.regs.ccer.modify(|_, w| w.cc3p().bit(polarity.bit())),
                    #[cfg(not(feature = "wl"))]
                    TimChannel::C4 => self.regs.ccer.modify(|_, w| w.cc4p().bit(polarity.bit())),
                }
            }

            /// Set complementary output polarity. See docs on the `Polarity` enum.
            pub fn set_complementary_polarity(&mut self, channel: TimChannel, polarity: Polarity) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1np().bit(polarity.bit())),
                    TimChannel::C2 => self.regs.ccer.modify(|_, w| w.cc2np().bit(polarity.bit())),
                    TimChannel::C3 => self.regs.ccer.modify(|_, w| w.cc3np().bit(polarity.bit())),
                    // #[cfg(not(feature = "wl"))]
                    #[cfg(not(any(feature = "wl", feature = "l4")))] // PAC ommission
                    TimChannel::C4 => self.regs.ccer.modify(|_, w| w.cc4np().bit(polarity.bit())),
                    _ => panic!(),
                }
            }
            /// Disables capture compare on a specific channel.
            pub fn disable_capture_compare(&mut self, channel: TimChannel) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1e().clear_bit()),
                    TimChannel::C2 => self.regs.ccer.modify(|_, w| w.cc2e().clear_bit()),
                    TimChannel::C3 => self.regs.ccer.modify(|_, w| w.cc3e().clear_bit()),
                    #[cfg(not(feature = "wl"))]
                    TimChannel::C4 => self.regs.ccer.modify(|_, w| w.cc4e().clear_bit()),
                }
            }

            /// Enables capture compare on a specific channel.
            pub fn enable_capture_compare(&mut self, channel: TimChannel) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1e().set_bit()),
                    TimChannel::C2 => self.regs.ccer.modify(|_, w| w.cc2e().set_bit()),
                    TimChannel::C3 => self.regs.ccer.modify(|_, w| w.cc3e().set_bit()),
                    #[cfg(not(feature = "wl"))]
                    TimChannel::C4 => self.regs.ccer.modify(|_, w| w.cc4e().set_bit()),
                }
            }

            /// Set Capture Compare Mode. See docs on the `CaptureCompare` enum.
            pub fn set_capture_compare(&mut self, channel: TimChannel, mode: CaptureCompare) {
                match channel {
                    // Note: CC1S bits are writable only when the channel is OFF (CC1E = 0 in TIMx_CCER)
                    TimChannel::C1 => self
                        .regs
                        .ccmr1_output()
                        .modify(unsafe { |_, w| w.cc1s().bits(mode as u8) }),
                    TimChannel::C2 => self
                        .regs
                        .ccmr1_output()
                        .modify(unsafe { |_, w| w.cc2s().bits(mode as u8) }),
                    TimChannel::C3 => self
                        .regs
                        .ccmr2_output()
                        .modify(unsafe { |_, w| w.cc3s().bits(mode as u8) }),
                    #[cfg(not(feature = "wl"))]
                    TimChannel::C4 => self
                        .regs
                        .ccmr2_output()
                        .modify(unsafe { |_, w| w.cc4s().bits(mode as u8) }),
                }
            }

            /// Set preload mode.
            /// OC1PE: Output Compare 1 preload enable
            /// 0: Preload register on TIMx_CCR1 disabled. TIMx_CCR1 can be written at anytime, the
            /// new value is taken in account immediately.
            /// 1: Preload register on TIMx_CCR1 enabled. Read/Write operations access the preload
            /// register. TIMx_CCR1 preload value is loaded in the active register at each update event.
            /// Note: 1: These bits can not be modified as long as LOCK level 3 has been programmed
            /// (LOCK bits in TIMx_BDTR register) and CC1S=’00’ (the channel is configured in
            /// output).
            /// 2: The PWM mode can be used without validating the preload register only in one
            /// pulse mode (OPM bit set in TIMx_CR1 register). Else the behavior is not guaranteed.
            ///
            /// Setting preload is required to enable PWM.
            pub fn set_preload(&mut self, channel: TimChannel, value: bool) {
                match channel {
                    TimChannel::C1 => self.regs.ccmr1_output().modify(|_, w| w.oc1pe().bit(value)),
                    TimChannel::C2 => self.regs.ccmr1_output().modify(|_, w| w.oc2pe().bit(value)),
                    TimChannel::C3 => self.regs.ccmr2_output().modify(|_, w| w.oc3pe().bit(value)),
                    #[cfg(not(feature = "wl"))]
                    TimChannel::C4 => self.regs.ccmr2_output().modify(|_, w| w.oc4pe().bit(value)),
                }

                // "As the preload registers are transferred to the shadow registers only when an update event
                // occurs, before starting the counter, you have to initialize all the registers by setting the UG
                // bit in the TIMx_EGR register."
                self.reinitialize();
            }

        }
    }
}

macro_rules! cc_2_channels {
    ($TIMX:ident, $res:ident) => {
        impl Timer<pac::$TIMX> {
            /// Function that allows us to set direction only on timers that have this option.
            fn set_dir(&mut self) {
                // self.regs.cr1.modify(|_, w| w.dir().bit(self.cfg.direction as u8 != 0));
            }

            /// Enables basic PWM input. TODO: Doesn't work yet.
            /// L4 RM, section 26.3.8
            pub fn _enable_pwm_input(
                &mut self,
                _channel: TimChannel,
                _compare: OutputCompare,
                _dir: CountDir,
                _duty: f32,
            ) {
                // todo: These instruction sare specifically for TI1
                // 1. Select the active input for TIMx_CCR1: write the CC1S bits to 01 in the TIMx_CCMR1
                // register (TI1 selected).
                // self.regs.ccmr1.modify(|_, w| w.cc1s().bit(0b01));

                // 2. Select the active polarity for TI1FP1 (used both for capture in TIMx_CCR1 and counter
                // clear): write the CC1P and CC1NP bits to ‘0’ (active on rising edge).
                // self.regs.ccmr1.modify(|_, w| {
                //     w.cc1p().bits(0b00);
                //     w.cc1np().bits(0b00)
                // });
                // 3. Select the active input for TIMx_CCR2: write the CC2S bits to 10 in the TIMx_CCMR1
                // register (TI1 selected).
                // self.regs.ccmr2.modify(|_, w| w.cc2s().bit(0b10));

                // 4. Select the active polarity for TI1FP2 (used for capture in TIMx_CCR2): write the CC2P
                // and CC2NP bits to CC2P/CC2NP=’10’ (active on falling edge).
                // self.regs.ccr2.modify(|_, w| {
                //     w.cc2p().bits(0b10);
                //     w.cc2np().bits(0b10)
                // });

                // 5. Select the valid trigger input: write the TS bits to 101 in the TIMx_SMCR register
                // (TI1FP1 selected).
                // self.regs.smcr.modify(|_, w| w.ts().bits(0b101));

                // 6. Configure the slave mode controller in reset mode: write the SMS bits to 0100 in the
                // TIMx_SMCR register.
                // self.regs.smcr.modify(|_, w| w.sms().bits(0b0100));

                // 7. Enable the captures: write the CC1E and CC2E bits to ‘1’ in the TIMx_CCER register.
                // self.regs.ccer.modify(|_, w| {
                //     w.cc1e().set_bit();
                //     w.cc2e().set_bit()
                // });
            }

            // todo: more advanced PWM modes. Asymmetric, combined, center-aligned etc.

            /// Set Output Compare Mode. See docs on the `OutputCompare` enum.
            pub fn set_output_compare(&mut self, channel: TimChannel, mode: OutputCompare) {
                match channel {
                    TimChannel::C1 => {
                       self.regs.ccmr1_output().modify(|_, w| unsafe {
                        #[cfg(not(any(feature = "f4", feature = "l5", feature = "wb")))]
                           w.oc1m_3().bit((mode as u8) >> 3 != 0);
                           w.oc1m().bits((mode as u8) & 0b111)

                        });
                    }
                    TimChannel::C2 => {
                      self.regs.ccmr1_output().modify(|_, w| unsafe {
                        #[cfg(not(any(feature = "f4", feature = "l5", feature = "wb")))]
                          w.oc2m_3().bit((mode as u8) >> 3 != 0);
                          w.oc2m().bits((mode as u8) & 0b111)

                        });
                    }
                    _ => panic!()
                }
            }

            /// Return the set duty period for a given channel. Divide by `get_max_duty()`
            /// to find the portion of the duty cycle used.
            pub fn get_duty(&self, channel: TimChannel) -> $res {
                cfg_if! {
                    if #[cfg(feature = "g0")] {
                        match channel {
                            // todo: This isn't right!!
                            TimChannel::C1 => self.regs.ccr1.read().bits().try_into().unwrap(),
                            TimChannel::C2 => self.regs.ccr2.read().bits().try_into().unwrap(),
                            _ => panic!()
                        }
                    } else if #[cfg(any(feature = "wb", feature = "wl", feature = "l5"))] {
                        match channel {
                            TimChannel::C1 => self.regs.ccr1.read().ccr1().bits(),
                            TimChannel::C2 => self.regs.ccr2.read().ccr2().bits(),
                            _ => panic!()
                        }
                    } else {
                        match channel {
                            TimChannel::C1 => self.regs.ccr1.read().ccr().bits().try_into().unwrap(),
                            TimChannel::C2 => self.regs.ccr2.read().ccr().bits().try_into().unwrap(),
                            _ => panic!()
                        }
                    }
                }
            }

            /// Set the duty cycle, as a portion of ARR (`get_max_duty()`). Note that this
            /// needs to be re-run if you change ARR at any point.
            pub fn set_duty(&mut self, channel: TimChannel, duty: $res) {
                cfg_if! {
                    if #[cfg(feature = "g0")] {
                        match channel {
                            // todo: This isn't right!!
                            TimChannel::C1 => self.regs.ccr1.read().bits(),
                            TimChannel::C2 => self.regs.ccr2.read().bits(),
                            _ => panic!()
                        };
                    } else if #[cfg(any(feature = "wb", feature = "wl", feature = "l5"))] {
                        unsafe {
                            match channel {
                                TimChannel::C1 => self.regs.ccr1.write(|w| w.ccr1().bits(duty.try_into().unwrap())),
                                TimChannel::C2 => self.regs.ccr2.write(|w| w.ccr2().bits(duty.try_into().unwrap())),
                                _ => panic!()
                            }
                        }
                    } else {
                        unsafe {
                            match channel {
                                TimChannel::C1 => self.regs.ccr1.write(|w| w.ccr().bits(duty.try_into().unwrap())),
                                TimChannel::C2 => self.regs.ccr2.write(|w| w.ccr().bits(duty.try_into().unwrap())),
                                _ => panic!()
                            }
                        }
                    }
                }
            }

            /// Set output polarity. See docs on the `Polarity` enum.
            pub fn set_polarity(&mut self, channel: TimChannel, polarity: Polarity) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1p().bit(polarity.bit())),
                    TimChannel::C2 => self.regs.ccer.modify(|_, w| w.cc2p().bit(polarity.bit())),
                    _ => panic!()
                }
            }

            /// Set complementary output polarity. See docs on the `Polarity` enum.
            pub fn set_complementary_polarity(&mut self, channel: TimChannel, polarity: Polarity) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1np().bit(polarity.bit())),
                    TimChannel::C2 => self.regs.ccer.modify(|_, w| w.cc2np().bit(polarity.bit())),
                    _ => panic!()
                }
            }
            /// Disables capture compare on a specific channel.
            pub fn disable_capture_compare(&mut self, channel: TimChannel) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1e().clear_bit()),
                    TimChannel::C2 => self.regs.ccer.modify(|_, w| w.cc2e().clear_bit()),
                    _ => panic!()
                }
            }

            /// Enables capture compare on a specific channel.
            pub fn enable_capture_compare(&mut self, channel: TimChannel) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1e().set_bit()),
                    TimChannel::C2 => self.regs.ccer.modify(|_, w| w.cc2e().set_bit()),
                    _ => panic!()
                }
            }

            /// Set Capture Compare Mode. See docs on the `CaptureCompare` enum.
            pub fn set_capture_compare(&mut self, channel: TimChannel, mode: CaptureCompare) {
                match channel {
                    // Note: CC1S bits are writable only when the channel is OFF (CC1E = 0 in TIMx_CCER)
                    TimChannel::C1 => self
                        .regs
                        .ccmr1_output()
                        .modify(unsafe { |_, w| w.cc1s().bits(mode as u8) }),
                    TimChannel::C2 => self
                        .regs
                        .ccmr1_output()
                        .modify(unsafe { |_, w| w.cc2s().bits(mode as u8) }),
                    _ => panic!()
                }
            }

            /// Set preload mode.
            /// OC1PE: Output Compare 1 preload enable
            /// 0: Preload register on TIMx_CCR1 disabled. TIMx_CCR1 can be written at anytime, the
            /// new value is taken in account immediately.
            /// 1: Preload register on TIMx_CCR1 enabled. Read/Write operations access the preload
            /// register. TIMx_CCR1 preload value is loaded in the active register at each update event.
            /// Note: 1: These bits can not be modified as long as LOCK level 3 has been programmed
            /// (LOCK bits in TIMx_BDTR register) and CC1S=’00’ (the channel is configured in
            /// output).
            /// 2: The PWM mode can be used without validating the preload register only in one
            /// pulse mode (OPM bit set in TIMx_CR1 register). Else the behavior is not guaranteed.
            ///
            /// Setting preload is required to enable PWM.
            pub fn set_preload(&mut self, channel: TimChannel, value: bool) {
                match channel {
                    TimChannel::C1 => self.regs.ccmr1_output().modify(|_, w| w.oc1pe().bit(value)),
                    TimChannel::C2 => self.regs.ccmr1_output().modify(|_, w| w.oc2pe().bit(value)),
                    _ => panic!()
                }

                // "As the preload registers are transferred to the shadow registers only when an update event
                // occurs, before starting the counter, you have to initialize all the registers by setting the UG
                // bit in the TIMx_EGR register."
                self.reinitialize();
            }

        }
    }
}

macro_rules! cc_1_channel {
    ($TIMX:ident, $res:ident) => {
        impl Timer<pac::$TIMX> {
            /// Function that allows us to set direction only on timers that have this option.
            fn set_dir(&mut self) {}

            /// Enables basic PWM input. TODO: Doesn't work yet.
            /// L4 RM, section 26.3.8
            pub fn _enable_pwm_input(
                &mut self,
                _channel: TimChannel,
                _compare: OutputCompare,
                _dir: CountDir,
                _duty: f32,
            ) {
                // todo: These instruction sare specifically for TI1
                // 1. Select the active input for TIMx_CCR1: write the CC1S bits to 01 in the TIMx_CCMR1
                // register (TI1 selected).
                // self.regs.ccmr1.modify(|_, w| w.cc1s().bit(0b01));

                // 2. Select the active polarity for TI1FP1 (used both for capture in TIMx_CCR1 and counter
                // clear): write the CC1P and CC1NP bits to ‘0’ (active on rising edge).
                // self.regs.ccmr1.modify(|_, w| {
                //     w.cc1p().bits(0b00);
                //     w.cc1np().bits(0b00)
                // });
                // 3. Select the active input for TIMx_CCR2: write the CC2S bits to 10 in the TIMx_CCMR1
                // register (TI1 selected).
                // self.regs.ccmr2.modify(|_, w| w.cc2s().bit(0b10));

                // 4. Select the active polarity for TI1FP2 (used for capture in TIMx_CCR2): write the CC2P
                // and CC2NP bits to CC2P/CC2NP=’10’ (active on falling edge).
                // self.regs.ccr2.modify(|_, w| {
                //     w.cc2p().bits(0b10);
                //     w.cc2np().bits(0b10)
                // });

                // 5. Select the valid trigger input: write the TS bits to 101 in the TIMx_SMCR register
                // (TI1FP1 selected).
                // self.regs.smcr.modify(|_, w| w.ts().bits(0b101));

                // 6. Configure the slave mode controller in reset mode: write the SMS bits to 0100 in the
                // TIMx_SMCR register.
                // self.regs.smcr.modify(|_, w| w.sms().bits(0b0100));

                // 7. Enable the captures: write the CC1E and CC2E bits to ‘1’ in the TIMx_CCER register.
                // self.regs.ccer.modify(|_, w| {
                //     w.cc1e().set_bit();
                //     w.cc2e().set_bit()
                // });
            }

            // todo: more advanced PWM modes. Asymmetric, combined, center-aligned etc.

            /// Set Output Compare Mode. See docs on the `OutputCompare` enum.
            pub fn set_output_compare(&mut self, channel: TimChannel, mode: OutputCompare) {
                match channel {
                    TimChannel::C1 => {
                        #[cfg(not(feature = "g070"))] // todo: PAC bug?
                        self.regs.ccmr1_output().modify(|_, w| unsafe {
                            // todo: L5/WB is probably due to a PAC error. Has oc1m_2.
                            #[cfg(not(any(feature = "f3", feature = "f4", feature = "l4",
                                feature = "l5", feature = "wb", feature = "g0")))]
                            w.oc1m_3().bit((mode as u8) >> 3 != 0);
                            w.oc1m().bits((mode as u8) & 0b111)
                        });
                    }
                    _ => panic!()
                }
            }

            /// Return the set duty period for a given channel. Divide by `get_max_duty()`
            /// to find the portion of the duty cycle used.
            pub fn get_duty(&self, channel: TimChannel) -> $res {
                cfg_if! {
                    if #[cfg(feature = "g0")] {
                        match channel {
                            // todo: This isn't right!!
                            // todo: PAC is showing G0 having Tim15 as 32 bits. Is this right?
                            TimChannel::C1 => self.regs.ccr1.read().bits().try_into().unwrap(),
                            _ => panic!()
                        }
                    } else if #[cfg(any(feature = "wb", feature = "wl", feature = "l5"))] {
                        match channel {
                            TimChannel::C1 => self.regs.ccr1.read().ccr1().bits(),
                            _ => panic!()
                        }
                    } else {
                        match channel {
                            TimChannel::C1 => self.regs.ccr1.read().ccr().bits().try_into().unwrap(),
                            _ => panic!()
                        }
                    }
                }
            }

            /// Set the duty cycle, as a portion of ARR (`get_max_duty()`). Note that this
            /// needs to be re-run if you change ARR at any point.
            pub fn set_duty(&mut self, channel: TimChannel, duty: $res) {
                cfg_if! {
                    if #[cfg(feature = "g0")] {
                        match channel {
                            // todo: This isn't right!!
                            TimChannel::C1 => self.regs.ccr1.read().bits(),
                            _ => panic!()
                        };
                    } else if #[cfg(any(feature = "wb", feature = "wl", feature = "l5"))] {
                        unsafe {
                            match channel {
                                TimChannel::C1 => self.regs.ccr1.write(|w| w.ccr1().bits(duty.try_into().unwrap())),
                                _ => panic!()
                            }
                        }
                    } else {
                        unsafe {
                            match channel {
                                TimChannel::C1 => self.regs.ccr1.write(|w| w.ccr().bits(duty.try_into().unwrap())),
                                _ => panic!()
                            }
                        }
                    }
                }
            }

            /// Set output polarity. See docs on the `Polarity` enum.
            pub fn set_polarity(&mut self, channel: TimChannel, polarity: Polarity) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1p().bit(polarity.bit())),
                    _ => panic!()
                }
            }

            /// Set complementary output polarity. See docs on the `Polarity` enum.
            pub fn set_complementary_polarity(&mut self, channel: TimChannel, polarity: Polarity) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1np().bit(polarity.bit())),
                    _ => panic!()
                }
            }
            /// Disables capture compare on a specific channel.
            pub fn disable_capture_compare(&mut self, channel: TimChannel) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1e().clear_bit()),
                    _ => panic!()
                }
            }

            /// Enables capture compare on a specific channel.
            pub fn enable_capture_compare(&mut self, channel: TimChannel) {
                match channel {
                    TimChannel::C1 => self.regs.ccer.modify(|_, w| w.cc1e().set_bit()),
                    _ => panic!()
                }
            }

            /// Set Capture Compare Mode. See docs on the `CaptureCompare` enum.
            pub fn set_capture_compare(&mut self, channel: TimChannel, mode: CaptureCompare) {
                match channel {
                    // Note: CC1S bits are writable only when the channel is OFF (CC1E = 0 in TIMx_CCER)
                    TimChannel::C1 => self
                        .regs
                        .ccmr1_output()
                        .modify(unsafe { |_, w| w.cc1s().bits(mode as u8) }),
                    _ => panic!()
                }
            }

            /// Set preload mode.
            /// OC1PE: Output Compare 1 preload enable
            /// 0: Preload register on TIMx_CCR1 disabled. TIMx_CCR1 can be written at anytime, the
            /// new value is taken in account immediately.
            /// 1: Preload register on TIMx_CCR1 enabled. Read/Write operations access the preload
            /// register. TIMx_CCR1 preload value is loaded in the active register at each update event.
            /// Note: 1: These bits can not be modified as long as LOCK level 3 has been programmed
            /// (LOCK bits in TIMx_BDTR register) and CC1S=’00’ (the channel is configured in
            /// output).
            /// 2: The PWM mode can be used without validating the preload register only in one
            /// pulse mode (OPM bit set in TIMx_CR1 register). Else the behavior is not guaranteed.
            ///
            /// Setting preload is required to enable PWM.
            pub fn set_preload(&mut self, channel: TimChannel, value: bool) {
                match channel {
                    TimChannel::C1 => self.regs.ccmr1_output().modify(|_, w| w.oc1pe().bit(value)),
                    _ => panic!()
                }

                // "As the preload registers are transferred to the shadow registers only when an update event
                // occurs, before starting the counter, you have to initialize all the registers by setting the UG
                // bit in the TIMx_EGR register."
                self.reinitialize();
            }

        }
    }
}

/// Calculate values required to set the timer frequency: `PSC` and `ARR`. This can be
/// used for initial timer setup, or changing the value later.
fn calc_freq_vals(freq: f32, clock_speed: u32) -> Result<(u16, u16), ValueError> {
    // `period` and `clock_speed` are both in Hz.

    // PSC and ARR range: 0 to 65535
    // (PSC+1)*(ARR+1) = TIMclk/Updatefrequency = TIMclk * period
    // APB1 (pclk1) is used by Tim2, 3, 4, 6, 7.
    // APB2 (pclk2) is used by Tim8, 15-20 etc.

    // We need to factor the right-hand-side of the above equation (`rhs` variable)
    // into integers. There are likely clever algorithms available to do this.
    // Some examples: https://cp-algorithms.com/algebra/factorization.html
    // We've chosen something quick to write, and with sloppy precision;
    // should be good enough for most cases.

    // - If you work with pure floats, there are an infinite number of solutions: Ie for any value of PSC, you can find an ARR to solve the equation.
    // - The actual values are integers that must be between 0 and 65_536
    // - Different combinations will result in different amounts of rounding errors. Ideally, we pick the one with the lowest rounding error.
    // - The aboveapproach sets PSC and ARR always equal to each other.
    // This results in concise code, is computationally easy, and doesn't limit
    // the maximum period. There will usually be solutions that have a smaller rounding error.

    let max_val = 65_535;
    let rhs = clock_speed as f32 / freq;

    let arr = rhs.sqrt().round() as u16 - 1;
    let psc = arr;

    if arr > max_val || psc > max_val {
        return Err(ValueError {});
    }

    Ok((psc, arr))
}

// todo: Concepts for non-macro approach
// todo: Basic timers are easier to handle, since they generally deref to tim6.

cfg_if! {
    if #[cfg(not(any(
        feature = "f401",
        feature = "f410",
        feature = "f411",
        feature = "f413",
        feature = "g031",
        feature = "g041",
        feature = "g070",
        feature = "g030",
        feature = "wb",
        feature = "wl"
    )))]  {
        /// Represents a Basic timer, used primarily to trigger the onboard DAC. Eg Tim6 or Tim7.
        pub struct BasicTimer<R> {
            pub regs: R,
            clock_speed: u32,
        }

        impl<R> BasicTimer<R>
            where
                R: Deref<Target = pac::tim6::RegisterBlock> + RccPeriph,
        {
            /// Initialize a Basic timer, including  enabling and resetting
            /// its RCC peripheral clock.
            pub fn new(
                regs: R,
                freq: f32,
                clock_cfg: &Clocks,
            ) -> Self {
                free(|_| {
                    let rcc = unsafe { &(*RCC::ptr()) };
                    R::en_reset(rcc)
                });

                // Self { regs, config, clock_speed: clocks.apb1_timer()  }
                let mut result = Self { regs, clock_speed: clock_cfg.apb1_timer()  };

                result.set_freq(freq).ok();
                result
            }

            // todo: These fns are DRY from GP timer code!

            /// Enable the timer.
            pub fn enable(&mut self) {
                self.regs.cr1.modify(|_, w| w.cen().set_bit());
            }

            /// Disable the timer.
            pub fn disable(&mut self) {
                self.regs.cr1.modify(|_, w| w.cen().clear_bit());
            }

            /// Check if the timer is enabled.
            pub fn is_enabled(&self) -> bool {
                self.regs.cr1.read().cen().bit_is_set()
            }

            /// Set the timer period, in seconds. Overrides the period or frequency set
            /// in the constructor.
            pub fn set_period(&mut self, time: f32) -> Result<(), ValueError> {
                assert!(time > 0.);
                self.set_freq(1. / time)
            }

            /// Set the timer frequency, in Hz. Overrides the period or frequency set
            /// in the constructor.
            pub fn set_freq(&mut self, freq: f32) -> Result<(), ValueError> {
                assert!(freq > 0.);

                let (psc, arr) = calc_freq_vals(freq, self.clock_speed)?;

                self.regs.arr.write(|w| unsafe { w.bits(arr.into()) });
                self.regs.psc.write(|w| unsafe { w.bits(psc.into()) });

                Ok(())
            }

            /// Return the integer associated with the maximum duty period.
            pub fn get_max_duty(&self) -> u16 {
                #[cfg(feature = "l5")]
                return self.regs.arr.read().bits() as u16;
                #[cfg(not(feature = "l5"))]
                self.regs.arr.read().arr().bits()
            }

            /// Set the auto-reload register value. Used for adjusting frequency.
            pub fn set_auto_reload(&mut self, arr: u16) {
                self.regs.arr.write(|w| unsafe { w.bits(arr.into()) });
            }

            /// Set the prescaler value. Used for adjusting frequency.
            pub fn set_prescaler(&mut self, psc: u16) {
                self.regs.psc.write(|w| unsafe { w.bits(psc.into()) });
            }

            /// Reset the countdown; set the counter to 0.
            pub fn reset_countdown(&mut self) {
                self.regs.cnt.write(|w| unsafe { w.bits(0) });
            }

            /// Read the current counter value.
            pub fn read_count(&self) -> u16 {
                #[cfg(feature = "l5")]
                return self.regs.cnt.read().bits() as u16;
                #[cfg(not(feature = "l5"))]
                self.regs.cnt.read().cnt().bits()
            }

            /// Allow selected information to be sent in master mode to slave timers for
            /// synchronization (TRGO).
            pub fn set_mastermode(&self, mode: MasterModeSelection) {
                self.regs.cr2.modify(|_, w| unsafe { w.mms().bits(mode as u8) });
            }
        }
    }
}

// #[cfg(feature = "embedded-hal")]
// struct WaitError {}

// todo: Non-macro refactor base timer reg blocks:

// GP 32-bit: Tim2
// 2, 3, 4, 5

// GP 16-bit:
// 15, 16, 17 // (9-14 on F4) 14 on G0

// Basic:
// 6, 7

// Advanced: 1/8/20

#[cfg(not(any(feature = "f373")))]
make_timer!(TIM1, tim1, 2, u16);
// PAC error, I think.
#[cfg(not(any(
    feature = "f373",
    feature = "f4",
    feature = "l5",
    feature = "g0",
    feature = "g4",
    feature = "h7"
)))]
cc_4_channels!(TIM1, u16);
#[cfg(any(
    feature = "f4",
    feature = "l5",
    feature = "g0",
    feature = "g4",
    feature = "h7"
))] // PAC bug.
cc_2_channels!(TIM1, u16);

cfg_if! {
    if #[cfg(not(any(
        feature = "f410",
        feature = "g070",
        feature = "l5", // todo PAC bug?
        feature = "wb55", // todo PAC bug?
    )))] {
        make_timer!(TIM2, tim2, 1, u32);
        cc_4_channels!(TIM2, u32);
    }
}

// todo: Note. G4, for example, has TIM2 and 5 as 32-bit, and TIM3 and 4 as 16-bit per RM,
// todo: But PAC shows different.
cfg_if! {
    if #[cfg(not(any(
        feature = "f301",
        feature = "l4x1",
        // feature = "l412",
        feature = "l5", // todo PAC bug?
        feature = "l4x3",
        feature = "f410",
        feature = "wb",
        feature = "wl"
    )))] {
        make_timer!(TIM3, tim3, 1, u32);
        cc_4_channels!(TIM3, u32);
    }
}

cfg_if! {
    if #[cfg(not(any(
        feature = "f301",
        feature = "f3x4",
        feature = "f410",
        feature = "l4x1",
        feature = "l4x2",
        feature = "l412",
        feature = "l4x3",
        feature = "l5", // todo PAC bug?
        feature = "g0",
        feature = "wb",
        feature = "wl"
    )))] {
        make_timer!(TIM4, tim4, 1, u32);
        cc_4_channels!(TIM4, u32);
    }
}

cfg_if! {
    if #[cfg(any(
       feature = "f373",
       feature = "l4x5",
       feature = "l4x6",
       // feature = "l562", // todo: PAC bug?
       feature = "h7",
       all(feature = "f4", not(feature = "f410")),
   ))] {
        make_timer!(TIM5, tim5, 1, u32);
        cc_4_channels!(TIM5, u32);
   }
}

cfg_if! {
    if #[cfg(any(
        feature = "f303",
        feature = "l4x5",
        feature = "l4x6",
        feature = "l562",
    ))] {
        make_timer!(TIM8, tim8, 2, u16);
        // todo: Some issues with field names or something on l562 here.
        #[cfg(not(feature = "l5"))] // PAC bug.
        cc_4_channels!(TIM8, u16);
        #[cfg(feature = "l5")] // PAC bug.
        cc_1_channel!(TIM8, u16);
    }
}

// Todo: the L5 PAC has an address error on TIM15 - remove it until solved.
cfg_if! {
    if #[cfg(not(any(
        feature = "l5",
        feature = "f4",
        feature = "g031",
        feature = "g031",
        feature = "g041",
        feature = "g030",
        feature = "wb",
        feature = "wl"
    )))] {
        make_timer!(TIM15, tim15, 2, u16);
        // todo: TIM15 on some variant has 2 channels (Eg H7). On others, like L4x3, it appears to be 1.
        cc_1_channel!(TIM15, u16);
    }
}

#[cfg(not(feature = "f4"))]
make_timer!(TIM16, tim16, 2, u16);
#[cfg(not(feature = "f4"))]
cc_1_channel!(TIM16, u16);

cfg_if! {
    if #[cfg(not(any(
        feature = "l4x1",
        feature = "l4x2",
        feature = "l412",
        feature = "l4x3",
        feature = "f4",
    )))] {
        make_timer!(TIM17, tim17, 2, u16);
        cc_1_channel!(TIM17, u16);
    }
}

// { todo: tim18
//     TIM18: (tim18, apb2, enr, rstr),
// },

cfg_if! {
    if #[cfg(any(feature = "f373"))] {
        make_timer!(TIM12, tim12, 1, u16);
        make_timer!(TIM13, tim13, 1, u16);
        make_timer!(TIM14, tim14, 1, u16);
        make_timer!(TIM19, tim19, 2, u16);

        cc_1_channel!(TIM12, u16);
        cc_1_channel!(TIM13, u16);
        cc_1_channel!(TIM14, u16);
        cc_1_channel!(TIM19, u16);
    }
}

#[cfg(any(feature = "f303"))]
make_timer!(TIM20, tim20, 2, u16);
#[cfg(any(feature = "f303"))]
cc_4_channels!(TIM20, u16);

// todo: Remove the final "true/false" for adv ctrl. You need a sep macro like you do for ccx_channel!.