gd32e2-hal 0.10.1

HAL for the GD32E23x series (Cortex-M23), currently the GD32E230
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! General-purpose I/O.
//!
//! A pin's port, number and mode all live in its type, so the compiler rejects
//! whatever the current mode doesn't support: an [`Input`] pin has no
//! `set_high`, and an alternate function the pin doesn't have won't compile.
//!
//! Pins are handed out by [`GpioExt::split`], which consumes the port and
//! enables its clock, so a pin can neither be obtained twice nor used unclocked.
//! Modes are changed with the `into_*` methods, each returning a new type.
//!
//! ```ignore
//! let parts = dp.gpioa.split(&mut rcu);
//! let mut led = parts.pa5.into_output();
//! led.set_high().unwrap();
//! let tx = parts.pa9.into_alternate::<1>();
//! ```
//!
//! Two modes are special. `PA13`/`PA14` start as [`Debugger`] rather than as
//! inputs, because after reset they really are wired to SWD; using them for
//! anything else takes an `unsafe` step that acknowledges losing debug access.
//! And [`Pin::lock`] freezes a pin's configuration until the next chip reset,
//! which the type reflects as [`Locked`] — with no way back, since the hardware
//! has none either.

use core::convert::Infallible;
use core::marker::PhantomData;

use embedded_hal::digital::{ErrorType, InputPin, OutputPin, StatefulOutputPin};

use crate::pac;
use crate::rcu::Rcu;

const CTL_INPUT: u32 = 0b00;
const CTL_OUTPUT: u32 = 0b01;
const CTL_AF: u32 = 0b10;
const CTL_ANALOG: u32 = 0b11;

const OMODE_PUSH_PULL: u32 = 0b0;
const OMODE_OPEN_DRAIN: u32 = 0b1;

/// Mode: digital input.
pub struct Input;
/// Output type: driven both high and low.
pub struct PushPull;
/// Output type: driven low, released high — needs a pull-up to reach a high level.
pub struct OpenDrain;
/// Mode: digital output, of type `OTYPE` ([`PushPull`] or [`OpenDrain`]).
pub struct Output<OTYPE> {
    _otype: PhantomData<OTYPE>,
}
/// Mode: analog, the input mode the ADC requires.
pub struct Analog;
/// Mode: alternate function `AF`, routing the pin to a peripheral.
pub struct Alternate<const AF: u8>;
/// Mode: serial-wire debug, the reset state of `PA13`/`PA14`.
///
/// Deliberately not [`Input`]: those pins are genuinely driving SWD out of reset.
/// Leaving this state requires [`Pin::activate`], which is `unsafe` because it
/// gives up debug access.
pub struct Debugger;
/// Mode: configuration frozen until the next chip reset, wrapping the mode it
/// was locked in.
///
/// Reading and writing the pin still work exactly as they did before locking;
/// only reconfiguration is barred.
pub struct Locked<MODE> {
    _mode: PhantomData<MODE>,
}

/// A single pin: `P` is the port (`'A'`, `'B'` or `'F'`), `N` the pin number.
///
/// Zero-sized — the identity lives entirely in the type, so passing a pin around
/// costs nothing at runtime.
pub struct Pin<const P: char, const N: u8, MODE> {
    _mode: PhantomData<MODE>,
}

/// Internal pull resistor.
#[derive(Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Pull {
    /// No pull resistor.
    Floating = 0b00,
    /// Pulled up to the supply.
    Up = 0b01,
    /// Pulled down to ground.
    Down = 0b10,
}

/// Output slew rate. Slower edges radiate less; faster ones are needed for
/// high-speed peripherals.
#[derive(Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[allow(missing_docs)]
pub enum Speed {
    Mhz2 = 0b00,
    Mhz10 = 0b01,
    Mhz50 = 0b11,
}

/// Marks `AF` as a valid alternate function number for this pin.
///
/// Populated from the datasheet's pin table, so [`Pin::into_alternate`] rejects
/// a number the pin doesn't have. Which numbers are valid depends on the chip
/// variant feature.
pub trait ValidAf<const AF: u8> {}

macro_rules! pin_af {
    ( $( $p:literal $n:literal => [ $($af:literal),* $(,)? ] ),* $(,)? ) => {
        $( $( impl<MODE> ValidAf<$af> for Pin<$p, $n, MODE> {} )* )*
    };
}

// AF map from datasheet Table 2-13/2-14 (die-level). The table carries three
// footnotes marking functions that exist only on some variants of the series:
//   (1) GD32E230x4 only          -> feature `gd32e230x4`
//   (2) GD32E230x8/6             -> features `gd32e230x6` + `gd32e230x8`
//   (3) GD32E230x8 only          -> feature `gd32e230x8`
// Entries whose AF number exists on every variant live in the common block
// below, even when the *function* behind it differs per variant (e.g. PA2 AF1
// is USART0_TX on x4 but USART1_TX on x8) — `ValidAf` only gates the number.
// The AF numbers that exist on some variants only are added by the gated
// blocks that follow. Which peripheral a pin belongs to is decided separately,
// by `usart_pins!` / `spi_pins!`, which are gated the same way.
pin_af! {
    // ---- Port A ----
    'A' 0  => [1, 7],                // 1:USART0_CTS(1)/USART1_CTS(2) 7:CMP_OUT
    'A' 1  => [0, 1],                // 0:EVENTOUT 1:USART0_RTS/DE(1) | USART1_RTS/DE(2)
    'A' 2  => [1],                   // 1:USART0_TX(1) | USART1_TX(2)
    'A' 3  => [1],                   // 1:USART0_RX(1) | USART1_RX(2)
    'A' 4  => [0, 1, 4],             // 0:SPI0_NSS/I2S0_WS 1:USART0_CK(1)|USART1_CK(2) 4:TIMER13_CH0
    'A' 5  => [0],                   // 0:SPI0_SCK/I2S0_CK
    'A' 6  => [0, 1, 2, 5, 6, 7],    // 0:SPI0_MISO 1:TIMER2_CH0 2:TIMER0_BRKIN 5:TIMER15_CH0 6:EVENTOUT 7:CMP_OUT
    'A' 7  => [0, 1, 2, 4, 5, 6],    // 0:SPI0_MOSI 1:TIMER2_CH1 2:TIMER0_CH0_ON 4:TIMER13_CH0 5:TIMER16_CH0 6:EVENTOUT
    'A' 8  => [0, 1, 2, 3],          // 0:CK_OUT 1:USART0_CK 2:TIMER0_CH0 3:EVENTOUT
    'A' 9  => [1, 2, 4, 5],          // 1:USART0_TX 2:TIMER0_CH1 4:I2C0_SCL 5:CK_OUT
    'A' 10 => [0, 1, 2, 4],          // 0:TIMER16_BRKIN 1:USART0_RX 2:TIMER0_CH2 4:I2C0_SDA
    'A' 11 => [0, 1, 2, 4, 7],       // 0:EVENTOUT 1:USART0_CTS 2:TIMER0_CH3 4:I2C0_SMBA 7:CMP_OUT
    'A' 12 => [0, 1, 2, 4],          // 0:EVENTOUT 1:USART0_RTS/DE 2:TIMER0_ETI 4:I2C0_TXFRAME
    'A' 13 => [0, 1],                // 0:SWDIO 1:IFRP_OUT
    'A' 14 => [0, 1],                // 0:SWCLK 1:USART0_TX(1) | USART1_TX(2)
    'A' 15 => [0, 1, 3],             // 0:SPI0_NSS/I2S0_WS 1:USART0_RX(1)|USART1_RX(2) 3:EVENTOUT
    // ---- Port B ----
    'B' 0  => [0, 1, 2],             // 0:EVENTOUT 1:TIMER2_CH2 2:TIMER0_CH1_ON
    'B' 1  => [1, 2, 3],             // 1:TIMER2_CH3 2:TIMER13_CH0 3:TIMER0_CH2_ON
    'B' 2  => [1],                   // 1:TIMER2_ETI
    'B' 3  => [0, 1],                // 0:SPI0_SCK/I2S0_CK 1:EVENTOUT
    'B' 4  => [0, 1, 2, 4, 6],       // 0:SPI0_MISO 1:TIMER2_CH0 2:EVENTOUT 4:I2C0_TXFRAME 6:TIMER16_BRKIN
    'B' 5  => [0, 1, 2, 3],          // 0:SPI0_MOSI 1:TIMER2_CH1 2:I2C0_SMBA 3:TIMER15_BRKIN
    'B' 6  => [0, 1, 2],             // 0:USART0_TX 1:I2C0_SCL 2:TIMER15_CH0_ON
    'B' 7  => [0, 1, 2],             // 0:USART0_RX 1:I2C0_SDA 2:TIMER16_CH0_ON
    'B' 8  => [1, 2],                // 1:I2C0_SCL 2:TIMER15_CH0
    'B' 9  => [0, 1, 2, 3, 5],       // 0:IFRP_OUT 1:I2C0_SDA 2:TIMER16_CH0 3:EVENTOUT 5:I2S0_MCK
    'B' 11 => [0],                   // 0:EVENTOUT
    'B' 12 => [1, 2],                // 1:EVENTOUT 2:TIMER0_BRKIN
    'B' 13 => [2],                   // 2:TIMER0_CH0_ON
    'B' 14 => [2],                   // 2:TIMER0_CH1_ON
    'B' 15 => [2],                   // 2:TIMER0_CH2_ON
    // NB: 'B' 10 has no variant-independent AF — every one of its functions is
    // footnoted, so it appears only in the gated blocks below.
}

// ---- (1) GD32E230x4 only ----
#[cfg(feature = "gd32e230x4")]
pin_af! {
    'B' 10 => [1],                   // 1:I2C0_SCL
    'B' 11 => [1],                   // 1:I2C0_SDA
    'B' 12 => [0],                   // 0:SPI0_NSS
    'B' 13 => [0],                   // 0:SPI0_SCK
    'B' 14 => [0],                   // 0:SPI0_MISO
    'B' 15 => [0],                   // 0:SPI0_MOSI
}

// ---- (2) GD32E230x8/6 ----
#[cfg(any(feature = "gd32e230x6", feature = "gd32e230x8"))]
pin_af! {
    'A' 8  => [4],                   // 4:USART1_TX
    'B' 0  => [4],                   // 4:USART1_RX
}

// ---- (3) GD32E230x8 only ----
#[cfg(feature = "gd32e230x8")]
pin_af! {
    'A' 0  => [4],                   // 4:I2C1_SCL
    'A' 1  => [4, 5],                // 4:I2C1_SDA 5:TIMER14_CH0_ON
    'A' 2  => [0],                   // 0:TIMER14_CH0
    'A' 3  => [0],                   // 0:TIMER14_CH1
    'A' 4  => [6],                   // 6:SPI1_NSS
    'A' 9  => [0],                   // 0:TIMER14_BRKIN
    'A' 11 => [5, 6],                // 5:I2C1_SCL 6:SPI1_IO2
    'A' 12 => [5, 6],                // 5:I2C1_SDA 6:SPI1_IO3
    'A' 13 => [6],                   // 6:SPI1_MISO
    'A' 14 => [6],                   // 6:SPI1_MOSI
    'A' 15 => [6],                   // 6:SPI1_NSS
    'B' 1  => [6],                   // 6:SPI1_SCK
    'B' 9  => [7],                   // 7:SPI1_NSS
    'B' 10 => [1, 6, 7],             // 1:I2C1_SCL 6:SPI1_IO2 7:SPI1_SCK
    'B' 11 => [1, 6],                // 1:I2C1_SDA 6:SPI1_IO3
    'B' 12 => [0, 4],                // 0:SPI1_NSS 4:I2C1_SMBA
    'B' 13 => [0, 1, 5],             // 0:SPI1_SCK 1:I2C1_TXFRAME 5:I2C1_SCL
    'B' 14 => [0, 1, 5],             // 0:SPI1_MISO 1:TIMER14_CH0 5:I2C1_SDA
    'B' 15 => [0, 1, 3],             // 0:SPI1_MOSI 1:TIMER14_CH1 3:TIMER14_CH0_ON
}

/// Marks a mode whose pin may be reconfigured.
///
/// [`Debugger`] and [`Locked`] deliberately don't implement it, which is what
/// makes the `into_*` methods and the setters unavailable on them.
pub trait Active {}

impl Active for Input {}
impl Active for Analog {}
impl<const AF: u8> Active for Alternate<AF> {}
impl<OTYPE> Active for Output<OTYPE> {}

/// Marks a pin on a port that has a `LOCK` register, gating [`Pin::lock`].
///
/// Ports A and B have one; port F does not.
pub trait HasLock {}
impl<const N: u8, MODE> HasLock for Pin<'A', N, MODE> {}
impl<const N: u8, MODE> HasLock for Pin<'B', N, MODE> {}

impl<const P: char, const N: u8> Pin<P, N, Debugger> {
    /// Releases an SWD pin for general-purpose use, giving up debug access.
    ///
    /// # Safety
    ///
    /// This only relabels the type from `Debugger` to `Input` — it performs no
    /// register write. The pin remains physically in SWD mode until a
    /// subsequent `into_*()` call reconfigures `CTL`. The caller must follow up
    /// with one, or the type will no longer match the hardware state.
    pub unsafe fn activate(self) -> Pin<P, N, Input> {
        Pin { _mode: PhantomData }
    }
}

impl<const P: char, const N: u8, MODE> Pin<P, N, MODE> {
    fn reg(&self) -> &pac::gpioa::RegisterBlock {
        let ptr = match P {
            'A' => pac::Gpioa::ptr(),
            'B' => pac::Gpiob::ptr() as *const _,
            'F' => pac::Gpiof::ptr() as *const _, // AFSEL0/1 and LOCK registers are unavailable
            _ => unreachable!(),
        };
        unsafe { &*ptr }
    }

    fn read_pin(&self) -> bool {
        let bits = self.reg().istat().read().bits();
        ((bits >> N) & 0b1) == 0b1
    }

    fn read_octl(&self) -> bool {
        let bits = self.reg().octl().read().bits();
        ((bits >> N) & 0b1) == 0b1
    }
    fn set_bop(&self) {
        self.reg().bop().write(|w| unsafe { w.bits(1 << N) });
    }

    fn set_bc(&self) {
        self.reg().bc().write(|w| unsafe { w.bits(1 << N) });
    }

    fn set_tg(&self) {
        self.reg().tg().write(|w| unsafe { w.bits(1 << N) });
    }
}

impl<const P: char, const N: u8, MODE> Pin<P, N, MODE>
where
    MODE: Active,
{
    fn set_mode(&self, mode: u32) {
        let offset = N * 2;
        self.reg()
            .ctl()
            .modify(|r, w| unsafe { w.bits((r.bits() & !(0b11 << offset)) | (mode << offset)) });
    }
    fn set_af(&self, af: u32) {
        let is_afsel0 = N < 8;
        let offset = (N % 8) * 4;
        if is_afsel0 {
            self.reg().afsel0().modify(|r, w| unsafe {
                w.bits((r.bits() & !(0b1111 << offset)) | (af << offset))
            });
        } else {
            self.reg().afsel1().modify(|r, w| unsafe {
                w.bits((r.bits() & !(0b1111 << offset)) | (af << offset))
            });
        }
    }
    fn set_pud(&self, bits: u32) {
        let offset = N * 2;
        self.reg()
            .pud()
            .modify(|r, w| unsafe { w.bits((r.bits() & !(0b11 << offset)) | (bits << offset)) });
    }
    fn set_ospd(&self, bits: u32) {
        let offset = N * 2;
        self.reg()
            .ospd()
            .modify(|r, w| unsafe { w.bits((r.bits() & !(0b11 << offset)) | (bits << offset)) });
    }
    fn set_omode(&self, bits: u32) {
        let offset = N;
        self.reg()
            .omode()
            .modify(|r, w| unsafe { w.bits((r.bits() & !(0b1 << offset)) | (bits << offset)) });
    }
    fn set_lk(&self, lkk: bool) {
        self.reg().lock().modify(|_, w| {
            let w = match N {
                0 => w.lk0().locked(),
                1 => w.lk1().locked(),
                2 => w.lk2().locked(),
                3 => w.lk3().locked(),
                4 => w.lk4().locked(),
                5 => w.lk5().locked(),
                6 => w.lk6().locked(),
                7 => w.lk7().locked(),
                8 => w.lk8().locked(),
                9 => w.lk9().locked(),
                10 => w.lk10().locked(),
                11 => w.lk11().locked(),
                12 => w.lk12().locked(),
                13 => w.lk13().locked(),
                14 => w.lk14().locked(),
                15 => w.lk15().locked(),
                _ => unreachable!(),
            };
            if lkk {
                w.lkk().active()
            } else {
                w.lkk().not_active()
            }
        });
    }

    /// Reconfigures the pin as a digital input.
    pub fn into_input(self) -> Pin<P, N, Input> {
        self.set_mode(CTL_INPUT);
        Pin { _mode: PhantomData }
    }
    /// Reconfigures the pin as a push-pull output.
    pub fn into_push_pull_output(self) -> Pin<P, N, Output<PushPull>> {
        self.set_mode(CTL_OUTPUT);
        self.set_omode(OMODE_PUSH_PULL);
        Pin { _mode: PhantomData }
    }
    /// Reconfigures the pin as an open-drain output.
    ///
    /// The pin can also be read back in this mode, which shared buses such as
    /// I²C rely on.
    pub fn into_open_drain_output(self) -> Pin<P, N, Output<OpenDrain>> {
        self.set_mode(CTL_OUTPUT);
        self.set_omode(OMODE_OPEN_DRAIN);
        Pin { _mode: PhantomData }
    }
    /// Reconfigures the pin as an output; shorthand for the push-pull variant.
    pub fn into_output(self) -> Pin<P, N, Output<PushPull>> {
        self.into_push_pull_output()
    }
    /// Reconfigures the pin as an analog input, as required by the ADC.
    pub fn into_analog(self) -> Pin<P, N, Analog> {
        self.set_mode(CTL_ANALOG);
        Pin { _mode: PhantomData }
    }
    /// Routes the pin to a peripheral through alternate function `AF`.
    ///
    /// Only numbers this pin actually has will compile — see [`ValidAf`]. The
    /// number stays in the returned type, so a driver can demand the exact
    /// function it needs.
    pub fn into_alternate<const AF: u8>(self) -> Pin<P, N, Alternate<AF>>
    where
        Self: ValidAf<AF>,
    {
        self.set_mode(CTL_AF);
        self.set_af(AF as u32);
        Pin { _mode: PhantomData }
    }
    /// Freezes the pin's configuration until the next chip reset.
    ///
    /// Mode, pull, output type, speed and alternate function all stop responding
    /// to writes. There is no way to undo this, in hardware or in the type: the
    /// returned [`Locked`] pin can still be read and written, but never
    /// reconfigured. Only available on ports that have a `LOCK` register.
    pub fn lock(self) -> Pin<P, N, Locked<MODE>>
    where
        Self: HasLock,
    {
        // LKK write sequence from the manual: 1 -> 0 -> 1.
        self.set_lk(true);
        self.set_lk(false);
        self.set_lk(true);
        for _ in 0..2 {
            self.reg().lock().read();
        }
        Pin { _mode: PhantomData }
    }

    /// Selects the internal pull resistor.
    pub fn set_pull(&self, p: Pull) {
        self.set_pud(p as u32);
    }
    /// Selects the output slew rate.
    pub fn set_speed(&self, s: Speed) {
        self.set_ospd(s as u32);
    }
}

impl<const P: char, const N: u8, OTYPE> Pin<P, N, Output<OTYPE>> {
    /// Drives the pin high.
    pub fn set_high(&self) {
        self.set_bop();
    }
    /// Drives the pin low.
    pub fn set_low(&self) {
        self.set_bc();
    }
    /// Inverts the driven level.
    pub fn toggle(&self) {
        self.set_tg();
    }
    /// Returns whether the pin is *being driven* high.
    ///
    /// Reads back `OCTL`, i.e. what was last written, not what the wire is at —
    /// for the latter on an open-drain pin see [`is_high`](Pin::is_high).
    pub fn is_set_high(&self) -> bool {
        self.read_octl()
    }
    /// Returns whether the pin is *being driven* low.
    pub fn is_set_low(&self) -> bool {
        !self.read_octl()
    }
}

impl<const P: char, const N: u8> Pin<P, N, Input> {
    /// Returns whether the input reads high.
    pub fn is_high(&self) -> bool {
        self.read_pin()
    }
    /// Returns whether the input reads low.
    pub fn is_low(&self) -> bool {
        !self.read_pin()
    }
}

impl<const P: char, const N: u8> Pin<P, N, Output<OpenDrain>> {
    /// Returns whether the wire reads high.
    ///
    /// Open-drain can only pull low, so this reports the actual line level —
    /// which another device on a shared bus may be holding down against us.
    pub fn is_high(&self) -> bool {
        self.read_pin()
    }
    /// Returns whether the wire reads low.
    pub fn is_low(&self) -> bool {
        !self.read_pin()
    }
}

impl<const P: char, const N: u8, OTYPE> ErrorType for Pin<P, N, Output<OTYPE>> {
    type Error = Infallible;
}
impl<const P: char, const N: u8, OTYPE> OutputPin for Pin<P, N, Output<OTYPE>> {
    fn set_high(&mut self) -> Result<(), Self::Error> {
        self.set_bop();
        Ok(())
    }
    fn set_low(&mut self) -> Result<(), Self::Error> {
        self.set_bc();
        Ok(())
    }
}

impl<const P: char, const N: u8, OTYPE> StatefulOutputPin for Pin<P, N, Output<OTYPE>> {
    fn is_set_high(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_octl())
    }
    fn is_set_low(&mut self) -> Result<bool, Self::Error> {
        Ok(!self.read_octl())
    }
    fn toggle(&mut self) -> Result<(), Self::Error> {
        self.set_tg();
        Ok(())
    }
}

impl<const P: char, const N: u8> ErrorType for Pin<P, N, Input> {
    type Error = Infallible;
}
impl<const P: char, const N: u8> InputPin for Pin<P, N, Input> {
    fn is_high(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_pin())
    }
    fn is_low(&mut self) -> Result<bool, Self::Error> {
        Ok(!self.read_pin())
    }
}

impl<const P: char, const N: u8> InputPin for Pin<P, N, Output<OpenDrain>> {
    fn is_high(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_pin())
    }
    fn is_low(&mut self) -> Result<bool, Self::Error> {
        Ok(!self.read_pin())
    }
}

impl<const P: char, const N: u8, MODE> Pin<P, N, Locked<MODE>>
where
    Pin<P, N, MODE>: OutputPin,
{
    /// Drives the pin high.
    pub fn set_high(&self) {
        self.set_bop();
    }
    /// Drives the pin low.
    pub fn set_low(&self) {
        self.set_bc();
    }
}

impl<const P: char, const N: u8, MODE> Pin<P, N, Locked<MODE>>
where
    Pin<P, N, MODE>: StatefulOutputPin,
{
    /// Inverts the driven level.
    pub fn toggle(&self) {
        self.set_tg();
    }
    /// Returns whether the pin is *being driven* high, read back from `OCTL`.
    pub fn is_set_high(&self) -> bool {
        self.read_octl()
    }
    /// Returns whether the pin is *being driven* low, read back from `OCTL`.
    pub fn is_set_low(&self) -> bool {
        !self.read_octl()
    }
}

impl<const P: char, const N: u8, MODE> Pin<P, N, Locked<MODE>>
where
    Pin<P, N, MODE>: InputPin,
{
    /// Returns whether the pin reads high.
    pub fn is_high(&self) -> bool {
        self.read_pin()
    }
    /// Returns whether the pin reads low.
    pub fn is_low(&self) -> bool {
        !self.read_pin()
    }
}

impl<const P: char, const N: u8, MODE> ErrorType for Pin<P, N, Locked<MODE>> {
    type Error = Infallible;
}

impl<const P: char, const N: u8, MODE> OutputPin for Pin<P, N, Locked<MODE>>
where
    Pin<P, N, MODE>: OutputPin,
{
    fn set_high(&mut self) -> Result<(), Self::Error> {
        self.set_bop();
        Ok(())
    }
    fn set_low(&mut self) -> Result<(), Self::Error> {
        self.set_bc();
        Ok(())
    }
}

impl<const P: char, const N: u8, MODE> StatefulOutputPin for Pin<P, N, Locked<MODE>>
where
    Pin<P, N, MODE>: StatefulOutputPin,
{
    fn is_set_high(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_octl())
    }
    fn is_set_low(&mut self) -> Result<bool, Self::Error> {
        Ok(!self.read_octl())
    }
    fn toggle(&mut self) -> Result<(), Self::Error> {
        self.set_tg();
        Ok(())
    }
}

impl<const P: char, const N: u8, MODE> InputPin for Pin<P, N, Locked<MODE>>
where
    Pin<P, N, MODE>: InputPin,
{
    fn is_high(&mut self) -> Result<bool, Self::Error> {
        Ok(self.read_pin())
    }
    fn is_low(&mut self) -> Result<bool, Self::Error> {
        Ok(!self.read_pin())
    }
}

/// Extension trait splitting a GPIO port into its individual pins.
pub trait GpioExt {
    /// The struct of individual pins this port yields.
    type Parts;

    /// Enables the port's clock and returns its pins.
    ///
    /// Consumes the port, so its pins can only be obtained once — that is what
    /// keeps two parts of a program from configuring the same pin.
    fn split(self, rcu: &mut Rcu) -> Self::Parts;
}

macro_rules! gpio {
    ($Parts:ident, $Gpio:ty, $P:literal, [ $($name:ident : $num:literal : $mode:ty),+ $(,)? ]) => {
        /// The pins of this port, in their reset modes.
        pub struct $Parts {
            $(
                #[doc = concat!("Pin ", stringify!($name), ".")]
                pub $name: Pin<$P, $num, $mode>,
            )+
        }

        impl GpioExt for $Gpio {
            type Parts = $Parts;
            fn split(self, rcu: &mut Rcu) -> Self::Parts {
                <$Gpio as crate::rcu::Enable>::enable(rcu);
                $Parts { $( $name: Pin::<$P, $num, $mode> { _mode: PhantomData }, )+ }
            }
        }
    };
}

gpio!(PartsA, pac::Gpioa, 'A',
    [pa0:0:Input, pa1:1:Input, pa2:2:Input, pa3:3:Input, pa4:4:Input, pa5:5:Input, pa6:6:Input, pa7:7:Input,
     pa8:8:Input, pa9:9:Input, pa10:10:Input, pa11:11:Input, pa12:12:Input, pa13:13:Debugger, pa14:14:Debugger, pa15:15:Input]);

gpio!(PartsB, pac::Gpiob, 'B',
    [pb0:0:Input, pb1:1:Input, pb2:2:Input, pb3:3:Input, pb4:4:Input, pb5:5:Input, pb6:6:Input, pb7:7:Input,
     pb8:8:Input, pb9:9:Input, pb10:10:Input, pb11:11:Input, pb12:12:Input, pb13:13:Input, pb14:14:Input, pb15:15:Input]);

gpio!(PartsF, pac::Gpiof, 'F', [pf0:0:Input, pf1:1:Input]);