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
// TODO - clean these up
#![allow(unused_imports)]
#![allow(non_camel_case_types)]

use core::marker::PhantomData;

/// Input mode (type state)
pub struct Input<MODE> {
    _mode: PhantomData<MODE>,
}

/// Floating input (type state)
pub struct Floating;
// /// Pulled down input (type state)
// pub struct PullDown;
// /// Pulled up input (type state)
// pub struct PullUp;

/// Output mode (type state)
pub struct Output<MODE> {
    _mode: PhantomData<MODE>,
}

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

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

/// Push pull output (type state)
pub struct PushPull;
/// Open drain output (type state)
pub struct OpenDrain;

// /// Alternate function
// pub struct Alternate<MODE> {
//     _mode: PhantomData<MODE>,
// }


/// Represents a digital input or output level
pub enum Level {
    Low,
    High,
}


macro_rules! gpio {
    (
        $PX:ident, $pxsvd:ident, $px:ident, $Pg:ident [
            $($PXi:ident: ($pxi:ident, $i:expr, $MODE:ty),)+
        ]
    ) => {
        /// GPIO
        pub mod $px {
            use super::{
                // Alternate,
                Floating,
                GpioExt,
                Input,
                Level,
                OpenDrain,
                Output,
                // PullDown, PullUp,
                PushPull,

                PhantomData,
            };

            use crate::target;
            use crate::target::$PX;
            use crate::target::$pxsvd::{
                pin_cnf,
                PIN_CNF,
            };
            use crate::hal::digital::{OutputPin, StatefulOutputPin, InputPin};

            // ===============================================================
            // Implement Generic Pins for this port, which allows you to use
            // other peripherals without having to be completely rust-generic
            // across all of the possible pins
            // ===============================================================
            /// Generic $PX pin
            pub struct $Pg<MODE> {
                pub pin: u8,
                _mode: PhantomData<MODE>,
            }

            impl<MODE> $Pg<MODE> {
                /// Convert the pin to be a floating input
                pub fn into_floating_input(self) -> $Pg<Input<Floating>> {
                    unsafe { &(*$PX::ptr()).pin_cnf[self.pin as usize] }.write(|w| {
                        w.dir().input()
                         .input().connect()
                         .pull().disabled()
                         .drive().s0s1()
                         .sense().disabled()
                    });

                    $Pg {
                        _mode: PhantomData,
                        pin: self.pin
                    }
                }

                /// Convert the pin to be a push-pull output with normal drive
                pub fn into_push_pull_output(self, initial_output: Level)
                    -> $Pg<Output<PushPull>>
                {
                    let mut pin = $Pg {
                        _mode: PhantomData,
                        pin: self.pin
                    };

                    match initial_output {
                        Level::Low  => pin.set_low(),
                        Level::High => pin.set_high(),
                    }

                    unsafe { &(*$PX::ptr()).pin_cnf[self.pin as usize] }.write(|w| {
                        w.dir().output()
                         .input().connect() // AJM - hack for SPI
                         .pull().disabled()
                         .drive().s0s1()
                         .sense().disabled()
                    });

                    pin
                }

                /// Convert the pin to be an open-drain output
                ///
                /// This method currently does not support configuring an
                /// internal pull-up or pull-down resistor.
                pub fn into_open_drain_output(self,
                    config:         OpenDrainConfig,
                    initial_output: Level,
                )
                    -> $Pg<Output<OpenDrain>>
                {
                    let mut pin = $Pg {
                        _mode: PhantomData,
                        pin: self.pin
                    };

                    match initial_output {
                        Level::Low  => pin.set_low(),
                        Level::High => pin.set_high(),
                    }

                    // This is safe, as we restrict our access to the dedicated
                    // register for this pin.
                    let pin_cnf = unsafe {
                        &(*$PX::ptr()).pin_cnf[self.pin as usize]
                    };
                    pin_cnf.write(|w| {
                        w
                            .dir().output()
                            .input().disconnect()
                            .pull().disabled()
                            .drive().variant(config.variant())
                            .sense().disabled()
                    });

                    pin
                }
            }

            impl<MODE> InputPin for $Pg<Input<MODE>> {
                fn is_high(&self) -> bool {
                    !self.is_low()
                }

                fn is_low(&self) -> bool {
                    unsafe { ((*$PX::ptr()).in_.read().bits() & (1 << self.pin)) == 0 }
                }
            }

            impl<MODE> OutputPin for $Pg<Output<MODE>> {
                /// Set the output as high
                fn set_high(&mut self) {
                    // NOTE(unsafe) atomic write to a stateless register - TODO(AJM) verify?
                    // TODO - I wish I could do something like `.pins$i()`...
                    unsafe { (*$PX::ptr()).outset.write(|w| w.bits(1u32 << self.pin)); }
                }

                /// Set the output as low
                fn set_low(&mut self) {
                    // NOTE(unsafe) atomic write to a stateless register - TODO(AJM) verify?
                    // TODO - I wish I could do something like `.pins$i()`...
                    unsafe { (*$PX::ptr()).outclr.write(|w| w.bits(1u32 << self.pin)); }
                }
            }

            impl<MODE> StatefulOutputPin for $Pg<Output<MODE>> {
                /// Is the output pin set as high?
                fn is_set_high(&self) -> bool {
                    !self.is_set_low()
                }

                /// Is the output pin set as low?
                fn is_set_low(&self) -> bool {
                    // NOTE(unsafe) atomic read with no side effects - TODO(AJM) verify?
                    // TODO - I wish I could do something like `.pins$i()`...
                    unsafe { ((*$PX::ptr()).out.read().bits() & (1 << self.pin)) == 0 }
                }
            }

            // ===============================================================
            // This chunk allows you to obtain an nrf52-hal gpio from the
            // upstream nrf52 gpio definitions by defining a trait
            // ===============================================================
            /// GPIO parts
            pub struct Parts {
                $(
                    /// Pin
                    pub $pxi: $PXi<$MODE>,
                )+
            }

            impl GpioExt for $PX {
                type Parts = Parts;

                fn split(self) -> Parts {
                    Parts {
                        $(
                            $pxi: $PXi {
                                _mode: PhantomData,
                            },
                        )+
                    }
                }
            }

            // ===============================================================
            // Implement each of the typed pins usable through the nrf52-hal
            // defined interface
            // ===============================================================
            $(
                pub struct $PXi<MODE> {
                    _mode: PhantomData<MODE>,
                }


                impl<MODE> $PXi<MODE> {
                    /// Convert the pin to be a floating input
                    pub fn into_floating_input(self) -> $PXi<Input<Floating>> {
                        unsafe { &(*$PX::ptr()).pin_cnf[$i] }.write(|w| {
                            w.dir().input()
                             .input().connect()
                             .pull().disabled()
                             .drive().s0s1()
                             .sense().disabled()
                        });

                        $PXi {
                            _mode: PhantomData,
                        }
                    }

                    /// Convert the pin to bepin a push-pull output with normal drive
                    pub fn into_push_pull_output(self, initial_output: Level)
                        -> $PXi<Output<PushPull>>
                    {
                        let mut pin = $PXi {
                            _mode: PhantomData,
                        };

                        match initial_output {
                            Level::Low  => pin.set_low(),
                            Level::High => pin.set_high(),
                        }

                        unsafe { &(*$PX::ptr()).pin_cnf[$i] }.write(|w| {
                            w.dir().output()
                             .input().disconnect()
                             .pull().disabled()
                             .drive().s0s1()
                             .sense().disabled()
                        });

                        pin
                    }

                    /// Convert the pin to be an open-drain output
                    ///
                    /// This method currently does not support configuring an
                    /// internal pull-up or pull-down resistor.
                    pub fn into_open_drain_output(self,
                        config:         OpenDrainConfig,
                        initial_output: Level,
                    )
                        -> $PXi<Output<OpenDrain>>
                    {
                        let mut pin = $PXi {
                            _mode: PhantomData,
                        };

                        match initial_output {
                            Level::Low  => pin.set_low(),
                            Level::High => pin.set_high(),
                        }

                        // This is safe, as we restrict our access to the
                        // dedicated register for this pin.
                        let pin_cnf = unsafe {
                            &(*$PX::ptr()).pin_cnf[$i]
                        };
                        pin_cnf.write(|w| {
                            w
                                .dir().output()
                                .input().disconnect()
                                .pull().disabled()
                                .drive().variant(config.variant())
                                .sense().disabled()
                        });

                        pin
                    }

                    /// Degrade to a generic pin struct, which can be used with peripherals
                    pub fn degrade(self) -> $Pg<MODE> {
                        $Pg {
                            _mode: PhantomData,
                            pin: $i
                        }
                    }
                }

                impl<MODE> InputPin for $PXi<Input<MODE>> {
                    fn is_high(&self) -> bool {
                        !self.is_low()
                    }

                    fn is_low(&self) -> bool {
                        unsafe { ((*$PX::ptr()).in_.read().bits() & (1 << $i)) == 0 }
                    }
                }

                impl<MODE> OutputPin for $PXi<Output<MODE>> {
                    /// Set the output as high
                    fn set_high(&mut self) {
                        // NOTE(unsafe) atomic write to a stateless register - TODO(AJM) verify?
                        // TODO - I wish I could do something like `.pins$i()`...
                        unsafe { (*$PX::ptr()).outset.write(|w| w.bits(1u32 << $i)); }
                    }

                    /// Set the output as low
                    fn set_low(&mut self) {
                        // NOTE(unsafe) atomic write to a stateless register - TODO(AJM) verify?
                        // TODO - I wish I could do something like `.pins$i()`...
                        unsafe { (*$PX::ptr()).outclr.write(|w| w.bits(1u32 << $i)); }
                    }
                }

                impl<MODE> StatefulOutputPin for $PXi<Output<MODE>> {
                    /// Is the output pin set as high?
                    fn is_set_high(&self) -> bool {
                        !self.is_set_low()
                    }

                    /// Is the output pin set as low?
                    fn is_set_low(&self) -> bool {
                        // NOTE(unsafe) atomic read with no side effects - TODO(AJM) verify?
                        // TODO - I wish I could do something like `.pins$i()`...
                        unsafe { ((*$PX::ptr()).out.read().bits() & (1 << $i)) == 0 }
                    }
                }
            )+

            /// Pin configuration for open-drain mode
            pub enum OpenDrainConfig {
                Disconnect0Standard1,
                Disconnect0HighDrive1,
                Standard0Disconnect1,
                HighDrive0Disconnect1,
            }

            impl OpenDrainConfig {
                fn variant(self) -> pin_cnf::DRIVEW {
                    use self::OpenDrainConfig::*;

                    match self {
                        Disconnect0Standard1  => pin_cnf::DRIVEW::D0S1,
                        Disconnect0HighDrive1 => pin_cnf::DRIVEW::D0H1,
                        Standard0Disconnect1  => pin_cnf::DRIVEW::S0D1,
                        HighDrive0Disconnect1 => pin_cnf::DRIVEW::H0D1,
                    }
                }
            }
        }
    }
}

// ===========================================================================
// Definition of all the items used by the macros above.
//
// For now, it is a little repetitive, especially as the nrf52 only has one
// 32-bit GPIO port (P0)
// ===========================================================================
gpio!(P0, p0, p0, P0_Pin [
    P0_00: (p0_00,  0, Input<Floating>),
    P0_01: (p0_01,  1, Input<Floating>),
    P0_02: (p0_02,  2, Input<Floating>),
    P0_03: (p0_03,  3, Input<Floating>),
    P0_04: (p0_04,  4, Input<Floating>),
    P0_05: (p0_05,  5, Input<Floating>),
    P0_06: (p0_06,  6, Input<Floating>),
    P0_07: (p0_07,  7, Input<Floating>),
    P0_08: (p0_08,  8, Input<Floating>),
    P0_09: (p0_09,  9, Input<Floating>),
    P0_10: (p0_10, 10, Input<Floating>),
    P0_11: (p0_11, 11, Input<Floating>),
    P0_12: (p0_12, 12, Input<Floating>),
    P0_13: (p0_13, 13, Input<Floating>),
    P0_14: (p0_14, 14, Input<Floating>),
    P0_15: (p0_15, 15, Input<Floating>),
    P0_16: (p0_16, 16, Input<Floating>),
    P0_17: (p0_17, 17, Input<Floating>),
    P0_18: (p0_18, 18, Input<Floating>),
    P0_19: (p0_19, 19, Input<Floating>),
    P0_20: (p0_20, 20, Input<Floating>),
    P0_21: (p0_21, 21, Input<Floating>),
    P0_22: (p0_22, 22, Input<Floating>),
    P0_23: (p0_23, 23, Input<Floating>),
    P0_24: (p0_24, 24, Input<Floating>),
    P0_25: (p0_25, 25, Input<Floating>),
    P0_26: (p0_26, 26, Input<Floating>),
    P0_27: (p0_27, 27, Input<Floating>),
    P0_28: (p0_28, 28, Input<Floating>),
    P0_29: (p0_29, 29, Input<Floating>),
    P0_30: (p0_30, 30, Input<Floating>),
    P0_31: (p0_31, 31, Input<Floating>),
]);

// The p1 types are present in the p0 module generated from the
// svd, but we want to export them in a p1 module from this crate.
#[cfg(feature = "52840")]
gpio!(P1, p0, p1, P1_Pin [
    P1_00: (p1_00,  0, Input<Floating>),
    P1_01: (p1_01,  1, Input<Floating>),
    P1_02: (p1_02,  2, Input<Floating>),
    P1_03: (p1_03,  3, Input<Floating>),
    P1_04: (p1_04,  4, Input<Floating>),
    P1_05: (p1_05,  5, Input<Floating>),
    P1_06: (p1_06,  6, Input<Floating>),
    P1_07: (p1_07,  7, Input<Floating>),
    P1_08: (p1_08,  8, Input<Floating>),
    P1_09: (p1_09,  9, Input<Floating>),
    P1_10: (p1_10, 10, Input<Floating>),
    P1_11: (p1_11, 11, Input<Floating>),
    P1_12: (p1_12, 12, Input<Floating>),
    P1_13: (p1_13, 13, Input<Floating>),
    P1_14: (p1_14, 14, Input<Floating>),
    P1_15: (p1_15, 15, Input<Floating>),
]);