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
//! Working with GPIO pins.
//! The pins are associated with the PORT hardware.  This module
//! defines a `split` method on the `PORT` type that is used to safely
//! reference the individual pin configuration.
//! The IO pins can be switched into alternate function modes, which
//! routes the pins to different peripherals depending on the mode
//! for the pin.   The pin configuration is reflected through the
//! use of type states to make the interface (ideally, or at least practically)
//! impossible to misuse.
use target_device::port::{DIRCLR, DIRSET, OUTCLR, OUTSET, PINCFG0_, PMUX0_};

#[cfg(feature = "samd21g18a")]
use target_device::port::{PINCFG1_, PMUX1_};

use core::marker::PhantomData;
use hal::digital::OutputPin;
use target_device::PORT;

#[cfg(feature = "unproven")]
use hal::digital::{InputPin, StatefulOutputPin, ToggleableOutputPin};

/// The GpioExt trait allows splitting the PORT hardware into
/// its constituent pin parts.
pub trait GpioExt {
    type Parts;

    /// Consume and split the device into its constitent parts
    fn split(self) -> Self::Parts;
}

/// Represents a pin configured for input.
/// The MODE type is typically one of `Floating`, `PullDown` or
/// `PullUp`.
pub struct Input<MODE> {
    _mode: PhantomData<MODE>,
}

/// Represents a pin configured for output.
/// The MODE type is typically one of `PushPull`, or
/// `OpenDrain`.
pub struct Output<MODE> {
    _mode: PhantomData<MODE>,
}

// The following collection of types is used to encode the
// state of the pin at compile time and helps to avoid misuse.

/// Floating Input
pub struct Floating;
/// Pulled down Input
pub struct PullDown;
/// Pulled up Input
pub struct PullUp;

/// Totem Pole aka Push-Pull
pub struct PushPull;
/// Open drain output
pub struct OpenDrain;

/// Peripheral Function A
pub struct PfA;
/// Peripheral Function B
pub struct PfB;
/// Peripheral Function C
pub struct PfC;
/// Peripheral Function D
pub struct PfD;
/// Peripheral Function E
pub struct PfE;
/// Peripheral Function F
pub struct PfF;
/// Peripheral Function G
pub struct PfG;
/// Peripheral Function H
pub struct PfH;
/// Peripheral Function I
pub struct PfI;

/// A trait that makes it easier to generically manage
/// converting a pin from its current state into some
/// other functional mode.  The configuration change
/// requires exclusive access to the Port hardware,
/// which is why this isn't simply the standard `Into`
/// trait.
pub trait IntoFunction<T> {
    /// Consume the pin and configure it to operate in
    /// the mode T.
    fn into_function(self, port: &mut Port) -> T;
}

// rustfmt wants to keep indenting the nested macro on each run,
// so disable it for this whole block :-/
#[cfg_attr(rustfmt, rustfmt_skip)]
macro_rules! pin {
    (
        $PinType:ident,
        $pin_ident:ident,
        $pin_no:expr,
        $dirset:ident,
        $dirclr:ident,
        $pincfg:ident,
        $outset:ident,
        $outclr:ident,
        $pinmux:ident,
        $out:ident,
        $outtgl:ident,
        $in:ident
    ) => {
        // Helper for pmux peripheral function configuration
        macro_rules! function {
            ($FuncType:ty, $func_ident:ident, $variant:ident) => {

        impl<MODE> $PinType<MODE> {
            /// Configures the pin to operate with a peripheral
            pub fn $func_ident(
                self,
                port: &mut Port
            ) -> $PinType<$FuncType> {
                port.$pinmux()[$pin_no >> 1].modify(|_, w| {
                    if $pin_no & 1 == 1 {
                        // Odd-numbered pin
                        w.pmuxo().$variant()
                    } else {
                        // Even-numbered pin
                        w.pmuxe().$variant()
                    }
                });
                port.$pincfg()[$pin_no].write(|bits| {
                    bits.pmuxen().set_bit()
                });

                $PinType { _mode: PhantomData }
            }
        }
        impl<MODE> IntoFunction<$PinType<$FuncType>> for $PinType<MODE> {
            fn into_function(self, port: &mut Port) -> $PinType<$FuncType> {
                self.$func_ident(port)
            }
        }

            };
        }

        /// Represents the IO pin with the matching name.
        pub struct $PinType<MODE> {
            _mode: PhantomData<MODE>,
        }

        function!(PfA, into_function_a, a);
        function!(PfB, into_function_b, b);
        function!(PfC, into_function_c, c);
        function!(PfD, into_function_d, d);
        function!(PfE, into_function_e, e);
        function!(PfF, into_function_f, f);
        function!(PfG, into_function_g, g);
        function!(PfH, into_function_h, h);

        impl<MODE> $PinType<MODE> {

            // TODO: datasheet mentions this, but is likely for
            // a slightly different variant
            // function!(PfI, into_function_i, i);

            /// Configures the pin to operate as a floating input
            pub fn into_floating_input(self, port: &mut Port) -> $PinType<Input<Floating>> {
                port.$dirclr().write(|bits| unsafe {
                    bits.bits(1 << $pin_no);
                    bits
                });

                port.$pincfg()[$pin_no].write(|bits| {
                    bits.pmuxen().clear_bit();
                    bits.inen().set_bit();
                    bits.pullen().clear_bit();
                    bits.drvstr().clear_bit();
                    bits
                });

                $PinType { _mode: PhantomData }
            }

            /// Configures the pin to operate as a pulled down input pin
            pub fn into_pull_down_input(self, port: &mut Port) -> $PinType<Input<PullDown>> {
                port.$dirclr().write(|bits| unsafe {
                    bits.bits(1 << $pin_no);
                    bits
                });

                port.$pincfg()[$pin_no].write(|bits| {
                    bits.pmuxen().clear_bit();
                    bits.inen().set_bit();
                    bits.pullen().set_bit();
                    bits.drvstr().clear_bit();
                    bits
                });

                // Pull down
                port.$outclr().write(|bits| unsafe {
                    bits.bits(1 << $pin_no);
                    bits
                });

                $PinType { _mode: PhantomData }
            }

            /// Configures the pin to operate as a pulled up input pin
            pub fn into_pull_up_input(self, port: &mut Port) -> $PinType<Input<PullUp>> {
                port.$dirclr().write(|bits| unsafe {
                    bits.bits(1 << $pin_no);
                    bits
                });

                port.$pincfg()[$pin_no].write(|bits| {
                    bits.pmuxen().clear_bit();
                    bits.inen().set_bit();
                    bits.pullen().set_bit();
                    bits.drvstr().clear_bit();
                    bits
                });

                // Pull up
                port.$outset().write(|bits| unsafe {
                    bits.bits(1 << $pin_no);
                    bits
                });

                $PinType { _mode: PhantomData }
            }

            /// Configures the pin to operate as an open drain output
            pub fn into_open_drain_output(self, port: &mut Port) -> $PinType<Output<OpenDrain>> {
                port.$dirset().write(|bits| unsafe {
                    bits.bits(1 << $pin_no);
                    bits
                });

                port.$pincfg()[$pin_no].write(|bits| {
                    bits.pmuxen().clear_bit();
                    bits.inen().clear_bit();
                    bits.pullen().clear_bit();
                    bits.drvstr().clear_bit();
                    bits
                });

                $PinType { _mode: PhantomData }
            }

            /// Configures the pin to operate as a push-pull output
            pub fn into_push_pull_output(self, port: &mut Port) -> $PinType<Output<PushPull>> {
                port.$dirset().write(|bits| unsafe {
                    bits.bits(1 << $pin_no);
                    bits
                });

                port.$pincfg()[$pin_no].write(|bits| {
                    bits.pmuxen().clear_bit();
                    bits.inen().set_bit();
                    bits.pullen().clear_bit();
                    bits.drvstr().clear_bit();
                    bits
                });

                $PinType { _mode: PhantomData }
            }
        }

        impl $PinType<Output<OpenDrain>> {
            /// Control state of the internal pull up
            pub fn internal_pull_up(&mut self, port: &mut Port, on: bool) {
                port.$pincfg()[$pin_no].write(|bits| {
                    if on {
                        bits.pullen().set_bit();
                    } else {
                        bits.pullen().clear_bit();
                    }
                    bits
                });
            }
        }

        impl<MODE> $PinType<Output<MODE>> {
            /// Toggle the logic level of the pin; if it is currently
            /// high, set it low and vice versa.
            pub fn toggle(&mut self) {
                self.toggle_impl();
            }

            fn toggle_impl(&mut self) {
                unsafe {
                    (*PORT::ptr()).$outtgl.write(|bits| {
                        bits.bits(1 << $pin_no);
                        bits
                    });
                }
            }
        }

        #[cfg(feature = "unproven")]
        impl<MODE> ToggleableOutputPin for $PinType<Output<MODE>> {
            fn toggle(&mut self) {
                self.toggle_impl();
            }
        }

        #[cfg(feature = "unproven")]
        impl<MODE> InputPin for $PinType<Input<MODE>> {
            fn is_high(&self) -> bool {
                unsafe { (((*PORT::ptr()).$in.read().bits()) & (1 << $pin_no)) != 0 }
            }

            fn is_low(&self) -> bool {
                unsafe { (((*PORT::ptr()).$in.read().bits()) & (1 << $pin_no)) == 0 }
            }
        }

        #[cfg(feature = "unproven")]
        impl<MODE> StatefulOutputPin for $PinType<Output<MODE>> {
            fn is_set_high(&self) -> bool {
                unsafe { (((*PORT::ptr()).$out.read().bits()) & (1 << $pin_no)) != 0 }
            }

            fn is_set_low(&self) -> bool {
                unsafe { (((*PORT::ptr()).$out.read().bits()) & (1 << $pin_no)) == 0 }
            }
        }


        impl<MODE> OutputPin for $PinType<Output<MODE>> {
            fn set_high(&mut self) {
                unsafe {
                    (*PORT::ptr()).$outset.write(|bits| {
                        bits.bits(1 << $pin_no);
                        bits
                    });
                }
            }

            fn set_low(&mut self) {
                unsafe {
                    (*PORT::ptr()).$outclr.write(|bits| {
                        bits.bits(1 << $pin_no);
                        bits
                    });
                }
            }
        }
    };
}

/// Opaque port reference
pub struct Port {
    _0: (),
}

impl Port {
    fn dirset0(&mut self) -> &DIRSET {
        unsafe { &(*PORT::ptr()).dirset0 }
    }
    fn dirclr0(&mut self) -> &DIRCLR {
        unsafe { &(*PORT::ptr()).dirclr0 }
    }
    fn pincfg0(&mut self) -> &[PINCFG0_; 32] {
        unsafe { &(*PORT::ptr()).pincfg0_ }
    }
    fn outset0(&mut self) -> &OUTSET {
        unsafe { &(*PORT::ptr()).outset0 }
    }
    fn outclr0(&mut self) -> &OUTCLR {
        unsafe { &(*PORT::ptr()).outclr0 }
    }
    fn pmux0(&mut self) -> &[PMUX0_; 16] {
        unsafe { &(*PORT::ptr()).pmux0_ }
    }

    #[cfg(feature = "samd21g18a")]
    fn dirset1(&mut self) -> &DIRSET {
        unsafe { &(*PORT::ptr()).dirset1 }
    }
    #[cfg(feature = "samd21g18a")]
    fn dirclr1(&mut self) -> &DIRCLR {
        unsafe { &(*PORT::ptr()).dirclr1 }
    }
    #[cfg(feature = "samd21g18a")]
    fn pincfg1(&mut self) -> &[PINCFG1_; 32] {
        unsafe { &(*PORT::ptr()).pincfg1_ }
    }
    #[cfg(feature = "samd21g18a")]
    fn outset1(&mut self) -> &OUTSET {
        unsafe { &(*PORT::ptr()).outset1 }
    }
    #[cfg(feature = "samd21g18a")]
    fn outclr1(&mut self) -> &OUTCLR {
        unsafe { &(*PORT::ptr()).outclr1 }
    }
    #[cfg(feature = "samd21g18a")]
    fn pmux1(&mut self) -> &[PMUX1_; 16] {
        unsafe { &(*PORT::ptr()).pmux1_ }
    }
}

macro_rules! port {
    ([
       $($PinTypeA:ident: ($pin_identA:ident, $pin_noA:expr),)+
    ],[
       $($PinTypeB:ident: ($pin_identB:ident, $pin_noB:expr),)+
    ]) => {

/// Holds the GPIO Port peripheral and broken out pin instances
pub struct Parts {
    /// Opaque port reference
    pub port: Port,

    $(
        /// Pin $pin_identA
        pub $pin_identA: $PinTypeA<Input<Floating>>,
    )+
    $(
        /// Pin $pin_identB
        #[cfg(feature = "samd21g18a")]
        pub $pin_identB: $PinTypeB<Input<Floating>>,
    )+
}

impl GpioExt for PORT {
    type Parts = Parts;

    /// Split the PORT peripheral into discrete pins
    fn split(self) -> Parts {
        Parts {
            port: Port {_0: ()},
            $(
                $pin_identA: $PinTypeA { _mode: PhantomData },
            )+
            $(
                #[cfg(feature = "samd21g18a")]
                $pin_identB: $PinTypeB { _mode: PhantomData },
            )+
        }
    }
}

$(
    pin!($PinTypeA, $pin_identA, $pin_noA, dirset0, dirclr0,
        pincfg0, outset0, outclr0, pmux0, out0, outtgl0, in0);
)+
$(
    #[cfg(feature = "samd21g18a")]
    pin!($PinTypeB, $pin_identB, $pin_noB, dirset1, dirclr1,
        pincfg1, outset1, outclr1, pmux1, out1, outtgl1, in1);
)+

    };
}

port!([
    Pa0: (pa0, 0),
    Pa1: (pa1, 1),
    Pa2: (pa2, 2),
    Pa3: (pa3, 3),
    Pa4: (pa4, 4),
    Pa5: (pa5, 5),
    Pa6: (pa6, 6),
    Pa7: (pa7, 7),
    Pa8: (pa8, 8),
    Pa9: (pa9, 9),
    Pa10: (pa10, 10),
    Pa11: (pa11, 11),
    Pa12: (pa12, 12),
    Pa13: (pa13, 13),
    Pa14: (pa14, 14),
    Pa15: (pa15, 15),
    Pa16: (pa16, 16),
    Pa17: (pa17, 17),
    Pa18: (pa18, 18),
    Pa19: (pa19, 19),
    Pa20: (pa20, 20),
    Pa21: (pa21, 21),
    Pa22: (pa22, 22),
    Pa23: (pa23, 23),
    Pa24: (pa24, 24),
    Pa25: (pa25, 25),
    Pa26: (pa26, 26),
    Pa27: (pa27, 27),
    Pa28: (pa28, 28),
    Pa29: (pa29, 29),
    Pa30: (pa30, 30),
    Pa31: (pa31, 31),
],[
    Pb0: (pb0, 0),
    Pb1: (pb1, 1),
    Pb2: (pb2, 2),
    Pb3: (pb3, 3),
    Pb4: (pb4, 4),
    Pb5: (pb5, 5),
    Pb6: (pb6, 6),
    Pb7: (pb7, 7),
    Pb8: (pb8, 8),
    Pb9: (pb9, 9),
    Pb10: (pb10, 10),
    Pb11: (pb11, 11),
    Pb12: (pb12, 12),
    Pb13: (pb13, 13),
    Pb14: (pb14, 14),
    Pb15: (pb15, 15),
    Pb16: (pb16, 16),
    Pb17: (pb17, 17),
    Pb18: (pb18, 18),
    Pb19: (pb19, 19),
    Pb20: (pb20, 20),
    Pb21: (pb21, 21),
    Pb22: (pb22, 22),
    Pb23: (pb23, 23),
    Pb24: (pb24, 24),
    Pb25: (pb25, 25),
    Pb26: (pb26, 26),
    Pb27: (pb27, 27),
    Pb28: (pb28, 28),
    Pb29: (pb29, 29),
    Pb30: (pb30, 30),
    Pb31: (pb31, 31),
]);

/// This macro is a helper for defining a `Pins` type in a board support
/// crate.  This type is used to provide more meaningful aliases for the
/// various GPIO pins for a given board.
#[macro_export]
macro_rules! define_pins {
    ($(#[$topattr:meta])* struct $Type:ident,
     target_device: $target_device:ident,
     $( $(#[$attr:meta])* pin $name:ident = $pin_ident:ident),+ , ) => {

$crate::paste::item! {
    $(#[$topattr])*
    pub struct $Type {
        /// Opaque port reference
        pub port: Port,

        $(
            $(#[$attr])*
            pub $name: gpio::[<P $pin_ident>]<Input<Floating>>
        ),+
    }
}

impl $Type {
    /// Returns the pins for the device
    $crate::paste::item! {
        pub fn new(port: $target_device::PORT) -> Self {
            let pins = port.split();
            $Type {
                port: pins.port,
                $(
                $name: pins.[<p $pin_ident>]
                ),+
            }
        }
    }
}
}}