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
//! General Purpose Input / Output

// TODO the pins here currently correspond to the LQFP-100 package. There
// should be Cargo features that let you select different microcontroller
// packages

use crate::rcc::AHB;
use bobbin_bits::*;
use core::intrinsics::transmute;
use core::marker::PhantomData;
#[allow(deprecated)]
use hal::digital::{v2, InputPin, OutputPin, StatefulOutputPin};

/// Marker trait for any pin
pub trait GPIOPin {
    /// Returns GPIO group
    fn group(&self) -> Group;
    /// Returns pin index within group
    fn index(&self) -> u8;
}

/// Trait for pin mode
pub trait PinMode {
    /// Convert type state into actual bits
    fn pin_mode() -> U2;
}

/// Input
pub struct Input;
impl PinMode for Input {
    /// bits
    fn pin_mode() -> U2 {
        U2::B00
    }
}

/// Output
pub struct Output<OT: OutputType, OS: OutputSpeed> {
    _output_mode: PhantomData<OT>,
    _output_speed: PhantomData<OS>,
}
impl<OT: OutputType, OS: OutputSpeed> PinMode for Output<OT, OS> {
    fn pin_mode() -> U2 {
        U2::B01
    }
}

/// Alternating function
pub struct AltFn<AN: AltFnNum, OT: OutputType, OS: OutputSpeed> {
    _afnum: PhantomData<AN>,
    _output_mode: PhantomData<OT>,
    _output_speed: PhantomData<OS>,
}
impl<AN: AltFnNum, OT: OutputType, OS: OutputSpeed> PinMode
    for AltFn<AN, OT, OS>
{
    fn pin_mode() -> U2 {
        U2::B10
    }
}

/// Analog
pub struct Analog;
impl PinMode for Analog {
    fn pin_mode() -> U2 {
        U2::B11
    }
}

/// Pull (pin resistor state)
pub trait PullType {
    /// pull
    fn pull_type(&self) -> U2;
}

/// No pull; floating
pub struct PullNone;
impl PullType for PullNone {
    fn pull_type(&self) -> U2 {
        U2::B00
    }
}

/// Pull up
pub struct PullUp;
impl PullType for PullUp {
    fn pull_type(&self) -> U2 {
        U2::B01
    }
}

/// Pull down
pub struct PullDown;
impl PullType for PullDown {
    fn pull_type(&self) -> U2 {
        U2::B10
    }
}

/// Reserved
pub struct PullReserved;
impl PullType for PullReserved {
    fn pull_type(&self) -> U2 {
        U2::B11
    }
}

/// Configures output speed
pub trait OutputSpeed {
    /// Converts type state to actual bits
    fn output_speed(&self) -> U2;
}

/// Low speed
pub struct LowSpeed;
impl OutputSpeed for LowSpeed {
    fn output_speed(&self) -> U2 {
        U2::B00
    }
}

/// Medium  speed
pub struct MediumSpeed;
impl OutputSpeed for MediumSpeed {
    fn output_speed(&self) -> U2 {
        U2::B01
    }
}

/// Fast speed
pub struct FastSpeed;
impl OutputSpeed for FastSpeed {
    fn output_speed(&self) -> U2 {
        U2::B10
    }
}

/// High speed
pub struct HighSpeed;
impl OutputSpeed for HighSpeed {
    fn output_speed(&self) -> U2 {
        U2::B11
    }
}

/// Output type
pub trait OutputType {
    /// converts type state to actual type
    fn output_type(&self) -> U1;
}

/// Push pull
pub struct PushPull;
impl OutputType for PushPull {
    fn output_type(&self) -> U1 {
        U1::B0
    }
}

/// Open drain
pub struct OpenDrain;
impl OutputType for OpenDrain {
    fn output_type(&self) -> U1 {
        U1::B1
    }
}

/// AltFn number
pub trait AltFnNum {
    /// converts type state
    fn alt_fn_num(&self) -> U4;
}

macro_rules! gen_af {
    ([$(($af:ident, $bit:ident)) , +]) => {
        $(
            /// $af
            pub struct $af;
            impl AltFnNum for $af {
                fn alt_fn_num(&self) -> U4 {
                    U4::$bit
                }
            }
        )+
    }
}

gen_af!([(AF0, B0000),
         (AF1, B0001),
         (AF2, B0010),
         (AF3, B0011),
         (AF4, B0100),
         (AF5, B0101),
         (AF6, B0110),
         (AF7, B0111),
         (AF8, B1000),
         (AF9, B1001),
         (AF10, B1010),
         (AF11, B1011),
         (AF12, B1100),
         (AF13, B1101),
         (AF14, B1110),
         (AF15, B1111)]);

/// Extension trait to split a GPIO peripheral in independent pins and registers
pub trait GpioExt {
    /// The to split the GPIO into
    type Ports;

    /// Splits the GPIO block into independent pins and registers
    fn split(self, ahb: &mut AHB) -> Self::Ports;
}

macro_rules! gpio {
    ($GPIOX:ident, $Gpiox:ident, $gpiox:ident, $iopxenr:ident, $iopxrst:ident, $group: ident, $PXx:ident, [
        $($PXi:ident: ($pxi:ident, $i:expr, $AFR:ident),)+
    ]) => {
        use crate::pac::$GPIOX;
        /// GPIO ports
        pub struct $Gpiox {
            $(
                /// Pin $PXi
                pub $pxi: $PXi<PullNone, Input>,
            )+
        }

        impl GpioExt for $GPIOX {
            type Ports = $Gpiox;

            fn split(self, ahb: &mut AHB) -> Self::Ports {
                ahb.enr().modify(|_, w| w.$iopxenr().enabled());
                ahb.rstr().modify(|_, w| w.$iopxrst().set_bit());
                ahb.rstr().modify(|_, w| w.$iopxrst().clear_bit());

                $Gpiox {
                    $(
                        $pxi: $PXi {
                            _pullup_state: PhantomData,
                            _pin_mode: PhantomData
                        },
                    )+
                }
            }
        }

        impl $Gpiox {
            // helper functions

            fn set_pin_mode<PM: PinMode>(index: u32) {
                let offset = 2 * index;
                let mode_bits:u32 = PM::pin_mode().into();
                let moder = unsafe { &(*$GPIOX::ptr()).moder };
                // set io mode
                moder.modify(|r, w| unsafe {
                    w.bits((r.bits()
                            & !(0b11 << offset))
                           | (mode_bits << offset))
                });
            }

            fn set_output_speed<OS: OutputSpeed>(index: u32, os: OS) {
                let offset = 2 * index;
                let ospeedr = unsafe { &(*$GPIOX::ptr()).ospeedr };
                let speed_bits:u32 = os.output_speed().into();
                ospeedr.modify(|r, w| unsafe {
                    w.bits((r.bits()
                            & !(0b11 << offset))
                           | (speed_bits << offset))
                });
            }

            fn set_output_type<OT: OutputType>(index: u32, ot: OT) {
                let otyper = unsafe { &(*$GPIOX::ptr()).otyper };
                let type_bits:u32 = ot.output_type().into();
                otyper.modify(|r, w| unsafe {
                    w.bits(r.bits() | (type_bits << index))
                });
            }

        }


        /// Partially erased pin
        pub struct $PXx<PT: PullType, PM: PinMode> {
            i: u8,
            _pullup_state: PhantomData<PT>,
            _pin_mode: PhantomData<PM>
        }

        #[allow(deprecated)]
        impl<PT: PullType, OT: OutputType, OS: OutputSpeed>
            OutputPin for $PXx<PT, Output<OT, OS>> {
                fn set_high(&mut self) {
                    // NOTE(unsafe) atomic write to a stateless register
                    unsafe { (*$GPIOX::ptr()).bsrr.write(|w| w.bits(1 << self.i)) }
                }

                fn set_low(&mut self) {
                    // NOTE(unsafe) atomic write to a stateless register
                    unsafe { (*$GPIOX::ptr()).bsrr.write(|w| w.bits(1 << (16 + self.i))) }
                }
            }

        #[allow(deprecated)]
        impl<PT: PullType,
        AN: AltFnNum,
        OT: OutputType,
        OS: OutputSpeed> OutputPin for $PXx<PT, AltFn<AN, OT, OS>> {
            fn set_high(&mut self) {
                // NOTE(unsafe) atomic write to a stateless register
                unsafe { (*$GPIOX::ptr()).bsrr.write(|w| w.bits(1 << self.i)) }
            }

            fn set_low(&mut self) {
                // NOTE(unsafe) atomic write to a stateless register
                unsafe { (*$GPIOX::ptr()).bsrr.write(|w| w.bits(1 << (16 + self.i))) }
            }
        }

        #[allow(deprecated)]
        impl<PT: PullType> InputPin for $PXx<PT, Input> {
            fn is_high(&self) -> bool {
                !self.is_low()
            }

            fn is_low(&self) -> bool {
                // NOTE(unsafe) atomic read with no side effects
                unsafe { (*$GPIOX::ptr()).idr.read().bits() & (1 << self.i) == 0 }
            }
        }

        $(
            /// Pin
            pub struct $PXi<PT: PullType, PM: PinMode> {
                _pullup_state: PhantomData<PT>,
                _pin_mode: PhantomData<PM>
            }

            impl <PT: PullType, PM: PinMode> GPIOPin for $PXi<PT, PM> {
                fn group(&self) -> Group {
                    Group::$group
                }

                fn index(&self) -> u8 {
                    $i
                }
            }

            impl<PT: PullType, PM: PinMode> $PXi<PT, PM> {
                /// Erases the pin number from the type
                ///
                /// This is useful when you want to collect the pins into an array where you
                /// need all the elements to have the same type
                pub fn downgrade(self) -> $PXx<PT, PM> {
                    $PXx {
                        i: $i,
                        _pullup_state: PhantomData,
                        _pin_mode: PhantomData
                    }
                }

                /// Sets pull type: Floaing, PullUp, PullDown
                pub fn pull_type<NPT: PullType>(self, pt: NPT)
                                                -> $PXi<NPT, PM>
                {
                    let shift = 0 + ($i << 1);
                    let pupdr = unsafe { &(*$GPIOX::ptr()).pupdr };
                    let pd_bits:u32 = pt.pull_type().into();
                    pupdr.modify(|r, w| unsafe {
                        w.bits((r.bits() & !(0b11 << shift))
                               | (pd_bits << shift))
                    });

                    unsafe { transmute(self) }
                }

                // XXX: it maybe makes sense to disallow this
                //      when Pin is input already;
                //      need to think about that
                /// Sets io_mode to input
                pub fn input(self) -> $PXi<PT, Input> {
                    $Gpiox::set_pin_mode::<Input>($i);
                    unsafe { transmute(self) }
                }

                /// Sets io_mode to analog
                pub fn analog(self) -> $PXi<PT, Analog> {
                    $Gpiox::set_pin_mode::<Analog>($i);
                    unsafe { transmute(self) }
                }

                /// Set io_mode to output
                pub fn output(self) -> $PXi<PT, Output<PushPull, LowSpeed>> {
                    let result: $PXi<PT, Output<PushPull, LowSpeed>> =
                        unsafe { transmute(self) };
                    // ensure output type and speed are set
                    let result2 = result
                        .output_type(PushPull)
                        .output_speed(LowSpeed);
                    $Gpiox::set_pin_mode::<Output<PushPull, LowSpeed>>($i);
                    result2
                }

                /// Set io_mode to altfn and set alternating function
                pub fn alternating<AFN: AltFnNum>(self, af: AFN) -> $PXi<PT, AltFn<AFN, PushPull, LowSpeed>> {
                    let result: $PXi<PT, AltFn<AFN, PushPull, LowSpeed>> =
                        unsafe { transmute(self) };
                    // ensure output type, speed, and afnum are set
                    let result2 = result
                        .alt_fn(af)
                        .output_type(PushPull)
                        .output_speed(LowSpeed);
                    $Gpiox::set_pin_mode::<AltFn<AFN, PushPull, LowSpeed>>($i);
                    result2
                }
            }

            impl<PT: PullType, OT: OutputType, OS: OutputSpeed> $PXi<PT, Output<OT, OS>> {
                /// Set output type
                pub fn output_type<NOT: OutputType>(self, ot: NOT) -> $PXi<PT, Output<NOT, OS>> {
                    $Gpiox::set_output_type($i, ot);
                    unsafe { transmute(self) }
                }

                /// Set output type to PushPull
                pub fn push_pull(self) -> $PXi<PT, Output<PushPull, OS>> {
                    self.output_type(PushPull)
                }

                /// Set output type to OpenDrain
                pub fn open_drain(self) -> $PXi<PT, Output<OpenDrain, OS>> {
                    self.output_type(OpenDrain)
                }

                /// Set output speed
                pub fn output_speed<NOS: OutputSpeed>(self, os: NOS) -> $PXi<PT, Output<OT, NOS>> {
                    $Gpiox::set_output_speed($i, os);
                    unsafe { transmute(self) }
                }
            }

            impl<PT: PullType, AFN: AltFnNum, OT: OutputType, OS: OutputSpeed> $PXi<PT, AltFn<AFN, OT, OS>> {
                /// Set output type
                pub fn output_type<NOT: OutputType>(self, ot: NOT) -> $PXi<PT, AltFn<AFN, NOT, OS>> {
                    $Gpiox::set_output_type($i, ot);
                    unsafe { transmute(self) }
                }

                /// Set output speed
                pub fn output_speed<NOS: OutputSpeed>(self, os: NOS) -> $PXi<PT, AltFn<AFN, OT, NOS>> {
                    $Gpiox::set_output_speed($i, os);
                    unsafe { transmute(self) }
                }

                /// Set altfn
                pub fn alt_fn<NAFN: AltFnNum>(self, af: NAFN) -> $PXi<PT, AltFn<NAFN, OT, OS>> {
                    let index = $i & (8 - 1);
                    let shift: usize = 0 + (index << 2);
                    let af_bits: u32 = af.alt_fn_num().into();
                    let afr = unsafe { &(*$GPIOX::ptr()).$AFR };
                    afr.modify(|r, w| unsafe {
                        w.bits((r.bits() & !(0b1111 << shift))
                               | (af_bits << shift))
                    });

                    unsafe { transmute(self) }
                }
            }

            #[allow(deprecated)]
            impl<PT: PullType, OT:OutputType, OS:OutputSpeed> OutputPin
                for $PXi<PT, Output<OT, OS>> {
                    fn set_high(&mut self) {
                        // NOTE(unsafe) atomic write to a stateless register
                        unsafe { (*$GPIOX::ptr()).bsrr.write(|w| w.bits(1 << $i)) }
                    }

                    fn set_low(&mut self) {
                        // NOTE(unsafe) atomic write to a stateless register
                        unsafe { (*$GPIOX::ptr()).bsrr.write(|w| w.bits(1 << (16 + $i))) }
                    }
                }

            #[allow(deprecated)]
            impl<PT: PullType, AN: AltFnNum, OT:OutputType, OS:OutputSpeed> OutputPin
                for $PXi<PT, AltFn<AN, OT, OS>> {
                    fn set_high(&mut self) {
                        // NOTE(unsafe) atomic write to a stateless register
                        unsafe { (*$GPIOX::ptr()).bsrr.write(|w| w.bits(1 << $i)) }
                    }

                    fn set_low(&mut self) {
                        // NOTE(unsafe) atomic write to a stateless register
                        unsafe { (*$GPIOX::ptr()).bsrr.write(|w| w.bits(1 << (16 + $i))) }
                    }
                }

            #[allow(deprecated)]
            impl<PT: PullType, OT:OutputType, OS:OutputSpeed> StatefulOutputPin
                for $PXi<PT, Output<OT, OS>> {
                    fn is_set_high(&self) -> bool {
                        !self.is_set_low()
                    }

                    fn is_set_low(&self) -> bool {
                        // NOTE(unsafe) atomic read with no side effects
                        unsafe { (*$GPIOX::ptr()).odr.read().bits() & (1 << $i) == 0 }
                    }
                }

            impl<PT: PullType, OT:OutputType, OS:OutputSpeed> v2::toggleable::Default
                for $PXi<PT, Output<OT, OS>> {}

            #[allow(deprecated)]
            impl<PT: PullType> InputPin for $PXi<PT, Input> {
                fn is_high(&self) -> bool {
                    !self.is_low()
                }

                fn is_low(&self) -> bool {
                    // NOTE(unsafe) atomic read with no side effects
                    unsafe { (*$GPIOX::ptr()).idr.read().bits() & (1 << $i) == 0 }
                }
            }

        )+

    }
}

/// GPIO pin group [A-F]
pub enum Group {
    /// GPIOA
    A,
    /// GPIOB
    B,
    /// GPIOC
    C,
    /// GPIOD
    D,
    /// GPIOE
    E,
    /// GPIOF
    F,
    /// GPIOG
    G,
}

gpio!(GPIOA, Gpioa, gpioa, iopaen, ioparst, A, PAx, [
    PA0: (pa0, 0, afrl),
    PA1: (pa1, 1, afrl),
    PA2: (pa2, 2, afrl),
    PA3: (pa3, 3, afrl),
    PA4: (pa4, 4, afrl),
    PA5: (pa5, 5, afrl),
    PA6: (pa6, 6, afrl),
    PA7: (pa7, 7, afrl),
    PA8: (pa8, 8, afrh),
    PA9: (pa9, 9, afrh),
    PA10: (pa10, 10, afrh),
    PA11: (pa11, 11, afrh),
    PA12: (pa12, 12, afrh),
    PA13: (pa13, 13, afrh),
    PA14: (pa14, 14, afrh),
    PA15: (pa15, 15, afrh),
]);

gpio!(GPIOB, Gpiob, gpiob, iopben, iopbrst, B, PBx, [
    PB0: (pb0, 0, afrl),
    PB1: (pb1, 1, afrl),
    PB2: (pb2, 2, afrl),
    PB3: (pb3, 3, afrl),
    PB4: (pb4, 4, afrl),
    PB5: (pb5, 5, afrl),
    PB6: (pb6, 6, afrl),
    PB7: (pb7, 7, afrl),
    PB8: (pb8, 8, afrh),
    PB9: (pb9, 9, afrh),
    PB10: (pb10, 10, afrh),
    PB11: (pb11, 11, afrh),
    PB12: (pb12, 12, afrh),
    PB13: (pb13, 13, afrh),
    PB14: (pb14, 14, afrh),
    PB15: (pb15, 15, afrh),
]);

gpio!(GPIOC, Gpioc, gpioc, iopcen, iopcrst, C, PCx, [
    PC0: (pc0, 0, afrl),
    PC1: (pc1, 1, afrl),
    PC2: (pc2, 2, afrl),
    PC3: (pc3, 3, afrl),
    PC4: (pc4, 4, afrl),
    PC5: (pc5, 5, afrl),
    PC6: (pc6, 6, afrl),
    PC7: (pc7, 7, afrl),
    PC8: (pc8, 8, afrh),
    PC9: (pc9, 9, afrh),
    PC10: (pc10, 10, afrh),
    PC11: (pc11, 11, afrh),
    PC12: (pc12, 12, afrh),
    PC13: (pc13, 13, afrh),
    PC14: (pc14, 14, afrh),
    PC15: (pc15, 15, afrh),
]);

gpio!(GPIOD, Gpiod, gpiod, iopden, iopdrst, D, PDx, [
    PD0: (pd0, 0, afrl),
    PD1: (pd1, 1, afrl),
    PD2: (pd2, 2, afrl),
    PD3: (pd3, 3, afrl),
    PD4: (pd4, 4, afrl),
    PD5: (pd5, 5, afrl),
    PD6: (pd6, 6, afrl),
    PD7: (pd7, 7, afrl),
    PD8: (pd8, 8, afrh),
    PD9: (pd9, 9, afrh),
    PD10: (pd10, 10, afrh),
    PD11: (pd11, 11, afrh),
    PD12: (pd12, 12, afrh),
    PD13: (pd13, 13, afrh),
    PD14: (pd14, 14, afrh),
    PD15: (pd15, 15, afrh),
]);

gpio!(GPIOE, Gpioe, gpioe, iopeen, ioperst, E, PEx, [
    PE0: (pe0, 0, afrl),
    PE1: (pe1, 1, afrl),
    PE2: (pe2, 2, afrl),
    PE3: (pe3, 3, afrl),
    PE4: (pe4, 4, afrl),
    PE5: (pe5, 5, afrl),
    PE6: (pe6, 6, afrl),
    PE7: (pe7, 7, afrl),
    PE8: (pe8, 8, afrh),
    PE9: (pe9, 9, afrh),
    PE10: (pe10, 10, afrh),
    PE11: (pe11, 11, afrh),
    PE12: (pe12, 12, afrh),
    PE13: (pe13, 13, afrh),
    PE14: (pe14, 14, afrh),
    PE15: (pe15, 15, afrh),
]);

gpio!(GPIOF, Gpiof, gpiof, iopfen, iopfrst, F, PFx, [
    PF0: (pf0, 0, afrl),
    PF1: (pf1, 1, afrl),
    PF2: (pf2, 2, afrl),
    PF4: (pf3, 4, afrl),
    PF6: (pf6, 6, afrl),
    PF9: (pf9, 9, afrh),
    PF10: (pf10, 10, afrh),
]);