embassy_stm32/
gpio.rs

1//! General-purpose Input/Output (GPIO)
2
3#![macro_use]
4use core::convert::Infallible;
5
6use critical_section::CriticalSection;
7use embassy_hal_internal::{impl_peripheral, Peri, PeripheralType};
8
9use crate::pac::gpio::{self, vals};
10use crate::peripherals;
11
12/// GPIO flexible pin.
13///
14/// This pin can either be a disconnected, input, or output pin, or both. The level register bit will remain
15/// set while not in output mode, so the pin's level will be 'remembered' when it is not in output
16/// mode.
17pub struct Flex<'d> {
18    pub(crate) pin: Peri<'d, AnyPin>,
19}
20
21impl<'d> Flex<'d> {
22    /// Wrap the pin in a `Flex`.
23    ///
24    /// The pin remains disconnected. The initial output level is unspecified, but can be changed
25    /// before the pin is put into output mode.
26    ///
27    #[inline]
28    pub fn new(pin: Peri<'d, impl Pin>) -> Self {
29        // Pin will be in disconnected state.
30        Self { pin: pin.into() }
31    }
32
33    /// Put the pin into input mode.
34    ///
35    /// The internal weak pull-up and pull-down resistors will be enabled according to `pull`.
36    #[inline(never)]
37    pub fn set_as_input(&mut self, pull: Pull) {
38        critical_section::with(|_| {
39            let r = self.pin.block();
40            let n = self.pin.pin() as usize;
41            #[cfg(gpio_v1)]
42            {
43                let cnf = match pull {
44                    Pull::Up => {
45                        r.bsrr().write(|w| w.set_bs(n, true));
46                        vals::CnfIn::PULL
47                    }
48                    Pull::Down => {
49                        r.bsrr().write(|w| w.set_br(n, true));
50                        vals::CnfIn::PULL
51                    }
52                    Pull::None => vals::CnfIn::FLOATING,
53                };
54
55                r.cr(n / 8).modify(|w| {
56                    w.set_mode(n % 8, vals::Mode::INPUT);
57                    w.set_cnf_in(n % 8, cnf);
58                });
59            }
60            #[cfg(gpio_v2)]
61            {
62                r.pupdr().modify(|w| w.set_pupdr(n, pull.to_pupdr()));
63                r.otyper().modify(|w| w.set_ot(n, vals::Ot::PUSH_PULL));
64                r.moder().modify(|w| w.set_moder(n, vals::Moder::INPUT));
65            }
66        });
67    }
68
69    /// Put the pin into push-pull output mode.
70    ///
71    /// The pin level will be whatever was set before (or low by default). If you want it to begin
72    /// at a specific level, call `set_high`/`set_low` on the pin first.
73    ///
74    /// The internal weak pull-up and pull-down resistors will be disabled.
75    #[inline(never)]
76    pub fn set_as_output(&mut self, speed: Speed) {
77        critical_section::with(|_| {
78            let r = self.pin.block();
79            let n = self.pin.pin() as usize;
80            #[cfg(gpio_v1)]
81            {
82                r.cr(n / 8).modify(|w| {
83                    w.set_mode(n % 8, speed.to_mode());
84                    w.set_cnf_out(n % 8, vals::CnfOut::PUSH_PULL);
85                });
86            }
87            #[cfg(gpio_v2)]
88            {
89                r.pupdr().modify(|w| w.set_pupdr(n, vals::Pupdr::FLOATING));
90                r.otyper().modify(|w| w.set_ot(n, vals::Ot::PUSH_PULL));
91                r.ospeedr().modify(|w| w.set_ospeedr(n, speed.to_ospeedr()));
92                r.moder().modify(|w| w.set_moder(n, vals::Moder::OUTPUT));
93            }
94        });
95    }
96
97    /// Put the pin into input + open-drain output mode.
98    ///
99    /// The hardware will drive the line low if you set it to low, and will leave it floating if you set
100    /// it to high, in which case you can read the input to figure out whether another device
101    /// is driving the line low.
102    ///
103    /// The pin level will be whatever was set before (or low by default). If you want it to begin
104    /// at a specific level, call `set_high`/`set_low` on the pin first.
105    ///
106    /// The internal weak pull-up and pull-down resistors will be disabled.
107    #[inline(never)]
108    pub fn set_as_input_output(&mut self, speed: Speed) {
109        #[cfg(gpio_v1)]
110        critical_section::with(|_| {
111            let r = self.pin.block();
112            let n = self.pin.pin() as usize;
113            r.cr(n / 8).modify(|w| w.set_mode(n % 8, speed.to_mode()));
114            r.cr(n / 8).modify(|w| w.set_cnf_out(n % 8, vals::CnfOut::OPEN_DRAIN));
115        });
116
117        #[cfg(gpio_v2)]
118        self.set_as_input_output_pull(speed, Pull::None);
119    }
120
121    /// Put the pin into input + open-drain output mode with internal pullup or pulldown.
122    ///
123    /// This works like [`Self::set_as_input_output()`], but it also allows to enable the internal
124    /// weak pull-up or pull-down resistors.
125    #[inline(never)]
126    #[cfg(gpio_v2)]
127    pub fn set_as_input_output_pull(&mut self, speed: Speed, pull: Pull) {
128        critical_section::with(|_| {
129            let r = self.pin.block();
130            let n = self.pin.pin() as usize;
131            r.pupdr().modify(|w| w.set_pupdr(n, pull.to_pupdr()));
132            r.otyper().modify(|w| w.set_ot(n, vals::Ot::OPEN_DRAIN));
133            r.ospeedr().modify(|w| w.set_ospeedr(n, speed.to_ospeedr()));
134            r.moder().modify(|w| w.set_moder(n, vals::Moder::OUTPUT));
135        });
136    }
137
138    /// Put the pin into analog mode
139    ///
140    /// This mode is used by ADC and COMP but usually there is no need to set this manually
141    /// as the mode change is handled by the driver.
142    #[inline]
143    pub fn set_as_analog(&mut self) {
144        // TODO: does this also need a critical section, like other methods?
145        self.pin.set_as_analog();
146    }
147
148    /// Put the pin into AF mode, unchecked.
149    ///
150    /// This puts the pin into the AF mode, with the requested number and AF type. This is
151    /// completely unchecked, it can attach the pin to literally any peripheral, so use with care.
152    #[inline]
153    pub fn set_as_af_unchecked(&mut self, af_num: u8, af_type: AfType) {
154        critical_section::with(|_| {
155            self.pin.set_as_af(af_num, af_type);
156        });
157    }
158
159    /// Get whether the pin input level is high.
160    #[inline]
161    pub fn is_high(&self) -> bool {
162        !self.is_low()
163    }
164
165    /// Get whether the pin input level is low.
166    #[inline]
167    pub fn is_low(&self) -> bool {
168        let state = self.pin.block().idr().read().idr(self.pin.pin() as _);
169        state == vals::Idr::LOW
170    }
171
172    /// Get the current pin input level.
173    #[inline]
174    pub fn get_level(&self) -> Level {
175        self.is_high().into()
176    }
177
178    /// Get whether the output level is set to high.
179    #[inline]
180    pub fn is_set_high(&self) -> bool {
181        !self.is_set_low()
182    }
183
184    /// Get whether the output level is set to low.
185    #[inline]
186    pub fn is_set_low(&self) -> bool {
187        let state = self.pin.block().odr().read().odr(self.pin.pin() as _);
188        state == vals::Odr::LOW
189    }
190
191    /// Get the current output level.
192    #[inline]
193    pub fn get_output_level(&self) -> Level {
194        self.is_set_high().into()
195    }
196
197    /// Set the output as high.
198    #[inline]
199    pub fn set_high(&mut self) {
200        self.pin.set_high();
201    }
202
203    /// Set the output as low.
204    #[inline]
205    pub fn set_low(&mut self) {
206        self.pin.set_low();
207    }
208
209    /// Set the output level.
210    #[inline]
211    pub fn set_level(&mut self, level: Level) {
212        match level {
213            Level::Low => self.pin.set_low(),
214            Level::High => self.pin.set_high(),
215        }
216    }
217
218    /// Toggle the output level.
219    #[inline]
220    pub fn toggle(&mut self) {
221        if self.is_set_low() {
222            self.set_high()
223        } else {
224            self.set_low()
225        }
226    }
227}
228
229impl<'d> Drop for Flex<'d> {
230    #[inline]
231    fn drop(&mut self) {
232        critical_section::with(|_| {
233            self.pin.set_as_disconnected();
234        });
235    }
236}
237
238/// Pull setting for an input.
239#[derive(Debug, Eq, PartialEq, Copy, Clone)]
240#[cfg_attr(feature = "defmt", derive(defmt::Format))]
241pub enum Pull {
242    /// No pull
243    None,
244    /// Pull up
245    Up,
246    /// Pull down
247    Down,
248}
249
250impl Pull {
251    #[cfg(gpio_v2)]
252    const fn to_pupdr(self) -> vals::Pupdr {
253        match self {
254            Pull::None => vals::Pupdr::FLOATING,
255            Pull::Up => vals::Pupdr::PULL_UP,
256            Pull::Down => vals::Pupdr::PULL_DOWN,
257        }
258    }
259}
260
261/// Speed setting for an output.
262///
263/// These vary depending on the chip, check the reference manual and datasheet ("I/O port
264/// characteristics") for details.
265#[derive(Debug, Copy, Clone)]
266#[cfg_attr(feature = "defmt", derive(defmt::Format))]
267pub enum Speed {
268    #[cfg_attr(gpio_v1, doc = "Output speed OUTPUT2MHZ")]
269    #[cfg_attr(gpio_v2, doc = "Output speed 00")]
270    Low,
271    #[cfg_attr(gpio_v1, doc = "Output speed OUTPUT10MHZ")]
272    #[cfg_attr(gpio_v2, doc = "Output speed 01")]
273    Medium,
274    #[cfg_attr(gpio_v2, doc = "Output speed 10")]
275    #[cfg(not(any(gpio_v1, syscfg_f0)))]
276    High,
277    #[cfg_attr(gpio_v1, doc = "Output speed OUTPUT50MHZ")]
278    #[cfg_attr(gpio_v2, doc = "Output speed 11")]
279    VeryHigh,
280}
281
282impl Speed {
283    #[cfg(gpio_v1)]
284    const fn to_mode(self) -> vals::Mode {
285        match self {
286            Speed::Low => vals::Mode::OUTPUT2MHZ,
287            Speed::Medium => vals::Mode::OUTPUT10MHZ,
288            Speed::VeryHigh => vals::Mode::OUTPUT50MHZ,
289        }
290    }
291
292    #[cfg(gpio_v2)]
293    const fn to_ospeedr(self: Speed) -> vals::Ospeedr {
294        match self {
295            Speed::Low => vals::Ospeedr::LOW_SPEED,
296            Speed::Medium => vals::Ospeedr::MEDIUM_SPEED,
297            #[cfg(not(syscfg_f0))]
298            Speed::High => vals::Ospeedr::HIGH_SPEED,
299            Speed::VeryHigh => vals::Ospeedr::VERY_HIGH_SPEED,
300        }
301    }
302}
303
304/// GPIO input driver.
305pub struct Input<'d> {
306    pub(crate) pin: Flex<'d>,
307}
308
309impl<'d> Input<'d> {
310    /// Create GPIO input driver for a [Pin] with the provided [Pull] configuration.
311    #[inline]
312    pub fn new(pin: Peri<'d, impl Pin>, pull: Pull) -> Self {
313        let mut pin = Flex::new(pin);
314        pin.set_as_input(pull);
315        Self { pin }
316    }
317
318    /// Get whether the pin input level is high.
319    #[inline]
320    pub fn is_high(&self) -> bool {
321        self.pin.is_high()
322    }
323
324    /// Get whether the pin input level is low.
325    #[inline]
326    pub fn is_low(&self) -> bool {
327        self.pin.is_low()
328    }
329
330    /// Get the current pin input level.
331    #[inline]
332    pub fn get_level(&self) -> Level {
333        self.pin.get_level()
334    }
335}
336
337/// Digital input or output level.
338#[derive(Debug, Eq, PartialEq, Copy, Clone)]
339#[cfg_attr(feature = "defmt", derive(defmt::Format))]
340pub enum Level {
341    /// Low
342    Low,
343    /// High
344    High,
345}
346
347impl From<bool> for Level {
348    fn from(val: bool) -> Self {
349        match val {
350            true => Self::High,
351            false => Self::Low,
352        }
353    }
354}
355
356impl From<Level> for bool {
357    fn from(level: Level) -> bool {
358        match level {
359            Level::Low => false,
360            Level::High => true,
361        }
362    }
363}
364
365/// GPIO output driver.
366///
367/// Note that pins will **return to their floating state** when `Output` is dropped.
368/// If pins should retain their state indefinitely, either keep ownership of the
369/// `Output`, or pass it to [`core::mem::forget`].
370pub struct Output<'d> {
371    pub(crate) pin: Flex<'d>,
372}
373
374impl<'d> Output<'d> {
375    /// Create GPIO output driver for a [Pin] with the provided [Level] and [Speed] configuration.
376    #[inline]
377    pub fn new(pin: Peri<'d, impl Pin>, initial_output: Level, speed: Speed) -> Self {
378        let mut pin = Flex::new(pin);
379        match initial_output {
380            Level::High => pin.set_high(),
381            Level::Low => pin.set_low(),
382        }
383        pin.set_as_output(speed);
384        Self { pin }
385    }
386
387    /// Set the output as high.
388    #[inline]
389    pub fn set_high(&mut self) {
390        self.pin.set_high();
391    }
392
393    /// Set the output as low.
394    #[inline]
395    pub fn set_low(&mut self) {
396        self.pin.set_low();
397    }
398
399    /// Set the output level.
400    #[inline]
401    pub fn set_level(&mut self, level: Level) {
402        self.pin.set_level(level)
403    }
404
405    /// Is the output pin set as high?
406    #[inline]
407    pub fn is_set_high(&self) -> bool {
408        self.pin.is_set_high()
409    }
410
411    /// Is the output pin set as low?
412    #[inline]
413    pub fn is_set_low(&self) -> bool {
414        self.pin.is_set_low()
415    }
416
417    /// What level output is set to
418    #[inline]
419    pub fn get_output_level(&self) -> Level {
420        self.pin.get_output_level()
421    }
422
423    /// Toggle pin output
424    #[inline]
425    pub fn toggle(&mut self) {
426        self.pin.toggle();
427    }
428}
429
430/// GPIO output open-drain driver.
431///
432/// Note that pins will **return to their floating state** when `OutputOpenDrain` is dropped.
433/// If pins should retain their state indefinitely, either keep ownership of the
434/// `OutputOpenDrain`, or pass it to [`core::mem::forget`].
435pub struct OutputOpenDrain<'d> {
436    pub(crate) pin: Flex<'d>,
437}
438
439impl<'d> OutputOpenDrain<'d> {
440    /// Create a new GPIO open drain output driver for a [Pin] with the provided [Level] and [Speed].
441    #[inline]
442    pub fn new(pin: Peri<'d, impl Pin>, initial_output: Level, speed: Speed) -> Self {
443        let mut pin = Flex::new(pin);
444        match initial_output {
445            Level::High => pin.set_high(),
446            Level::Low => pin.set_low(),
447        }
448        pin.set_as_input_output(speed);
449        Self { pin }
450    }
451
452    /// Create a new GPIO open drain output driver for a [Pin] with the provided [Level], [Speed]
453    /// and [Pull].
454    #[inline]
455    #[cfg(gpio_v2)]
456    pub fn new_pull(pin: Peri<'d, impl Pin>, initial_output: Level, speed: Speed, pull: Pull) -> Self {
457        let mut pin = Flex::new(pin);
458        match initial_output {
459            Level::High => pin.set_high(),
460            Level::Low => pin.set_low(),
461        }
462        pin.set_as_input_output_pull(speed, pull);
463        Self { pin }
464    }
465
466    /// Get whether the pin input level is high.
467    #[inline]
468    pub fn is_high(&self) -> bool {
469        !self.pin.is_low()
470    }
471
472    /// Get whether the pin input level is low.
473    #[inline]
474    pub fn is_low(&self) -> bool {
475        self.pin.is_low()
476    }
477
478    /// Get the current pin input level.
479    #[inline]
480    pub fn get_level(&self) -> Level {
481        self.pin.get_level()
482    }
483
484    /// Set the output as high.
485    #[inline]
486    pub fn set_high(&mut self) {
487        self.pin.set_high();
488    }
489
490    /// Set the output as low.
491    #[inline]
492    pub fn set_low(&mut self) {
493        self.pin.set_low();
494    }
495
496    /// Set the output level.
497    #[inline]
498    pub fn set_level(&mut self, level: Level) {
499        self.pin.set_level(level);
500    }
501
502    /// Get whether the output level is set to high.
503    #[inline]
504    pub fn is_set_high(&self) -> bool {
505        self.pin.is_set_high()
506    }
507
508    /// Get whether the output level is set to low.
509    #[inline]
510    pub fn is_set_low(&self) -> bool {
511        self.pin.is_set_low()
512    }
513
514    /// Get the current output level.
515    #[inline]
516    pub fn get_output_level(&self) -> Level {
517        self.pin.get_output_level()
518    }
519
520    /// Toggle pin output
521    #[inline]
522    pub fn toggle(&mut self) {
523        self.pin.toggle()
524    }
525}
526
527/// GPIO output type
528#[derive(Debug, Copy, Clone)]
529#[cfg_attr(feature = "defmt", derive(defmt::Format))]
530pub enum OutputType {
531    /// Drive the pin both high or low.
532    PushPull,
533    /// Drive the pin low, or don't drive it at all if the output level is high.
534    OpenDrain,
535}
536
537impl OutputType {
538    #[cfg(gpio_v1)]
539    const fn to_cnf_out(self) -> vals::CnfOut {
540        match self {
541            OutputType::PushPull => vals::CnfOut::ALT_PUSH_PULL,
542            OutputType::OpenDrain => vals::CnfOut::ALT_OPEN_DRAIN,
543        }
544    }
545
546    #[cfg(gpio_v2)]
547    const fn to_ot(self) -> vals::Ot {
548        match self {
549            OutputType::PushPull => vals::Ot::PUSH_PULL,
550            OutputType::OpenDrain => vals::Ot::OPEN_DRAIN,
551        }
552    }
553}
554
555/// Alternate function type settings.
556#[derive(Copy, Clone)]
557#[cfg(gpio_v1)]
558pub struct AfType {
559    mode: vals::Mode,
560    cnf: u8,
561    pull: Pull,
562}
563
564#[cfg(gpio_v1)]
565impl AfType {
566    /// Input with optional pullup or pulldown.
567    pub const fn input(pull: Pull) -> Self {
568        let cnf_in = match pull {
569            Pull::Up | Pull::Down => vals::CnfIn::PULL,
570            Pull::None => vals::CnfIn::FLOATING,
571        };
572        Self {
573            mode: vals::Mode::INPUT,
574            cnf: cnf_in.to_bits(),
575            pull,
576        }
577    }
578
579    /// Output with output type and speed and no pull-up or pull-down.
580    pub const fn output(output_type: OutputType, speed: Speed) -> Self {
581        Self {
582            mode: speed.to_mode(),
583            cnf: output_type.to_cnf_out().to_bits(),
584            pull: Pull::None,
585        }
586    }
587}
588
589#[inline(never)]
590#[cfg(gpio_v1)]
591fn set_as_af(pin_port: u8, _af_num: u8, af_type: AfType) {
592    let pin = unsafe { AnyPin::steal(pin_port) };
593    let r = pin.block();
594    let n = pin._pin() as usize;
595
596    r.cr(n / 8).modify(|w| {
597        w.set_mode(n % 8, af_type.mode);
598        // note that we are writing the CNF field, which is exposed as both `cnf_in` and `cnf_out`
599        // in the PAC. the choice of `cnf_in` instead of `cnf_out` in this code is arbitrary and
600        // does not affect the result.
601        w.set_cnf_in(n % 8, vals::CnfIn::from_bits(af_type.cnf));
602    });
603
604    match af_type.pull {
605        Pull::Up => r.bsrr().write(|w| w.set_bs(n, true)),
606        Pull::Down => r.bsrr().write(|w| w.set_br(n, true)),
607        Pull::None => {}
608    }
609}
610
611/// Alternate function type settings.
612#[derive(Copy, Clone)]
613#[cfg(gpio_v2)]
614pub struct AfType {
615    pupdr: vals::Pupdr,
616    ot: vals::Ot,
617    ospeedr: vals::Ospeedr,
618}
619
620#[cfg(gpio_v2)]
621impl AfType {
622    /// Input with optional pullup or pulldown.
623    pub const fn input(pull: Pull) -> Self {
624        Self {
625            pupdr: pull.to_pupdr(),
626            ot: vals::Ot::PUSH_PULL,
627            ospeedr: vals::Ospeedr::LOW_SPEED,
628        }
629    }
630
631    /// Output with output type and speed and no pull-up or pull-down.
632    pub const fn output(output_type: OutputType, speed: Speed) -> Self {
633        Self::output_pull(output_type, speed, Pull::None)
634    }
635
636    /// Output with output type, speed and pull-up or pull-down;
637    pub const fn output_pull(output_type: OutputType, speed: Speed, pull: Pull) -> Self {
638        Self {
639            pupdr: pull.to_pupdr(),
640            ot: output_type.to_ot(),
641            ospeedr: speed.to_ospeedr(),
642        }
643    }
644}
645
646#[inline(never)]
647#[cfg(gpio_v2)]
648fn set_as_af(pin_port: u8, af_num: u8, af_type: AfType) {
649    let pin = unsafe { AnyPin::steal(pin_port) };
650    let r = pin.block();
651    let n = pin._pin() as usize;
652
653    r.afr(n / 8).modify(|w| w.set_afr(n % 8, af_num));
654    r.pupdr().modify(|w| w.set_pupdr(n, af_type.pupdr));
655    r.otyper().modify(|w| w.set_ot(n, af_type.ot));
656    r.ospeedr().modify(|w| w.set_ospeedr(n, af_type.ospeedr));
657    r.moder().modify(|w| w.set_moder(n, vals::Moder::ALTERNATE));
658}
659
660#[inline(never)]
661#[cfg(gpio_v2)]
662fn set_speed(pin_port: u8, speed: Speed) {
663    let pin = unsafe { AnyPin::steal(pin_port) };
664    let r = pin.block();
665    let n = pin._pin() as usize;
666
667    r.ospeedr().modify(|w| w.set_ospeedr(n, speed.to_ospeedr()));
668}
669
670#[inline(never)]
671fn set_as_analog(pin_port: u8) {
672    let pin = unsafe { AnyPin::steal(pin_port) };
673    let r = pin.block();
674    let n = pin._pin() as usize;
675
676    #[cfg(gpio_v1)]
677    r.cr(n / 8).modify(|w| {
678        w.set_mode(n % 8, vals::Mode::INPUT);
679        w.set_cnf_in(n % 8, vals::CnfIn::ANALOG);
680    });
681
682    #[cfg(gpio_v2)]
683    r.moder().modify(|w| w.set_moder(n, vals::Moder::ANALOG));
684}
685
686#[inline(never)]
687fn get_pull(pin_port: u8) -> Pull {
688    let pin = unsafe { AnyPin::steal(pin_port) };
689    let r = pin.block();
690    let n = pin._pin() as usize;
691
692    #[cfg(gpio_v1)]
693    return match r.cr(n / 8).read().mode(n % 8) {
694        vals::Mode::INPUT => match r.cr(n / 8).read().cnf_in(n % 8) {
695            vals::CnfIn::PULL => match r.odr().read().odr(n) {
696                vals::Odr::LOW => Pull::Down,
697                vals::Odr::HIGH => Pull::Up,
698            },
699            _ => Pull::None,
700        },
701        _ => Pull::None,
702    };
703
704    #[cfg(gpio_v2)]
705    return match r.pupdr().read().pupdr(n) {
706        vals::Pupdr::FLOATING => Pull::None,
707        vals::Pupdr::PULL_DOWN => Pull::Down,
708        vals::Pupdr::PULL_UP => Pull::Up,
709        vals::Pupdr::_RESERVED_3 => Pull::None,
710    };
711}
712
713pub(crate) trait SealedPin {
714    fn pin_port(&self) -> u8;
715
716    #[inline]
717    fn _pin(&self) -> u8 {
718        self.pin_port() % 16
719    }
720
721    #[inline]
722    fn _port(&self) -> u8 {
723        self.pin_port() / 16
724    }
725
726    #[inline]
727    fn block(&self) -> gpio::Gpio {
728        crate::_generated::gpio_block(self._port() as _)
729    }
730
731    /// Set the output as high.
732    #[inline]
733    fn set_high(&self) {
734        let n = self._pin() as _;
735        self.block().bsrr().write(|w| w.set_bs(n, true));
736    }
737
738    /// Set the output as low.
739    #[inline]
740    fn set_low(&self) {
741        let n = self._pin() as _;
742        self.block().bsrr().write(|w| w.set_br(n, true));
743    }
744
745    #[inline]
746    fn set_as_af(&self, af_num: u8, af_type: AfType) {
747        set_as_af(self.pin_port(), af_num, af_type)
748    }
749
750    #[inline]
751    #[cfg(gpio_v2)]
752    fn set_speed(&self, speed: Speed) {
753        set_speed(self.pin_port(), speed)
754    }
755
756    #[inline]
757    fn set_as_analog(&self) {
758        set_as_analog(self.pin_port());
759    }
760
761    /// Set the pin as "disconnected", ie doing nothing and consuming the lowest
762    /// amount of power possible.
763    ///
764    /// This is currently the same as [`Self::set_as_analog()`] but is semantically different
765    /// really. Drivers should `set_as_disconnected()` pins when dropped.
766    ///
767    /// Note that this also disables the internal weak pull-up and pull-down resistors.
768    #[inline]
769    fn set_as_disconnected(&self) {
770        self.set_as_analog();
771    }
772
773    /// Get the pull-up configuration.
774    #[inline]
775    fn pull(&self) -> Pull {
776        critical_section::with(|_| get_pull(self.pin_port()))
777    }
778}
779
780/// GPIO pin trait.
781#[allow(private_bounds)]
782pub trait Pin: PeripheralType + Into<AnyPin> + SealedPin + Sized + 'static {
783    /// EXTI channel assigned to this pin.
784    ///
785    /// For example, PC4 uses EXTI4.
786    #[cfg(feature = "exti")]
787    type ExtiChannel: crate::exti::Channel;
788
789    /// Number of the pin within the port (0..31)
790    #[inline]
791    fn pin(&self) -> u8 {
792        self._pin()
793    }
794
795    /// Port of the pin
796    #[inline]
797    fn port(&self) -> u8 {
798        self._port()
799    }
800}
801
802/// Type-erased GPIO pin
803pub struct AnyPin {
804    pin_port: u8,
805}
806
807impl AnyPin {
808    /// Unsafely create an `AnyPin` from a pin+port number.
809    ///
810    /// `pin_port` is `port_num * 16 + pin_num`, where `port_num` is 0 for port `A`, 1 for port `B`, etc...
811    #[inline]
812    pub unsafe fn steal(pin_port: u8) -> Peri<'static, Self> {
813        Peri::new_unchecked(Self { pin_port })
814    }
815
816    #[inline]
817    fn _port(&self) -> u8 {
818        self.pin_port / 16
819    }
820
821    /// Get the GPIO register block for this pin.
822    #[cfg(feature = "unstable-pac")]
823    #[inline]
824    pub fn block(&self) -> gpio::Gpio {
825        crate::_generated::gpio_block(self._port() as _)
826    }
827}
828
829impl_peripheral!(AnyPin);
830impl Pin for AnyPin {
831    #[cfg(feature = "exti")]
832    type ExtiChannel = crate::exti::AnyChannel;
833}
834impl SealedPin for AnyPin {
835    #[inline]
836    fn pin_port(&self) -> u8 {
837        self.pin_port
838    }
839}
840
841// ====================
842
843foreach_pin!(
844    ($pin_name:ident, $port_name:ident, $port_num:expr, $pin_num:expr, $exti_ch:ident) => {
845        impl Pin for peripherals::$pin_name {
846            #[cfg(feature = "exti")]
847            type ExtiChannel = peripherals::$exti_ch;
848        }
849        impl SealedPin for peripherals::$pin_name {
850            #[inline]
851            fn pin_port(&self) -> u8 {
852                $port_num * 16 + $pin_num
853            }
854        }
855
856        impl From<peripherals::$pin_name> for AnyPin {
857            fn from(val: peripherals::$pin_name) -> Self {
858                Self {
859                    pin_port: val.pin_port(),
860                }
861            }
862        }
863    };
864);
865
866pub(crate) unsafe fn init(_cs: CriticalSection) {
867    #[cfg(afio)]
868    crate::rcc::enable_and_reset_with_cs::<crate::peripherals::AFIO>(_cs);
869
870    crate::_generated::init_gpio();
871}
872
873impl<'d> embedded_hal_02::digital::v2::InputPin for Input<'d> {
874    type Error = Infallible;
875
876    #[inline]
877    fn is_high(&self) -> Result<bool, Self::Error> {
878        Ok(self.is_high())
879    }
880
881    #[inline]
882    fn is_low(&self) -> Result<bool, Self::Error> {
883        Ok(self.is_low())
884    }
885}
886
887impl<'d> embedded_hal_02::digital::v2::OutputPin for Output<'d> {
888    type Error = Infallible;
889
890    #[inline]
891    fn set_high(&mut self) -> Result<(), Self::Error> {
892        self.set_high();
893        Ok(())
894    }
895
896    #[inline]
897    fn set_low(&mut self) -> Result<(), Self::Error> {
898        self.set_low();
899        Ok(())
900    }
901}
902
903impl<'d> embedded_hal_02::digital::v2::StatefulOutputPin for Output<'d> {
904    #[inline]
905    fn is_set_high(&self) -> Result<bool, Self::Error> {
906        Ok(self.is_set_high())
907    }
908
909    /// Is the output pin set as low?
910    #[inline]
911    fn is_set_low(&self) -> Result<bool, Self::Error> {
912        Ok(self.is_set_low())
913    }
914}
915
916impl<'d> embedded_hal_02::digital::v2::ToggleableOutputPin for Output<'d> {
917    type Error = Infallible;
918    #[inline]
919    fn toggle(&mut self) -> Result<(), Self::Error> {
920        self.toggle();
921        Ok(())
922    }
923}
924
925impl<'d> embedded_hal_02::digital::v2::InputPin for OutputOpenDrain<'d> {
926    type Error = Infallible;
927
928    fn is_high(&self) -> Result<bool, Self::Error> {
929        Ok(self.is_high())
930    }
931
932    fn is_low(&self) -> Result<bool, Self::Error> {
933        Ok(self.is_low())
934    }
935}
936
937impl<'d> embedded_hal_02::digital::v2::OutputPin for OutputOpenDrain<'d> {
938    type Error = Infallible;
939
940    #[inline]
941    fn set_high(&mut self) -> Result<(), Self::Error> {
942        self.set_high();
943        Ok(())
944    }
945
946    #[inline]
947    fn set_low(&mut self) -> Result<(), Self::Error> {
948        self.set_low();
949        Ok(())
950    }
951}
952
953impl<'d> embedded_hal_02::digital::v2::StatefulOutputPin for OutputOpenDrain<'d> {
954    #[inline]
955    fn is_set_high(&self) -> Result<bool, Self::Error> {
956        Ok(self.is_set_high())
957    }
958
959    /// Is the output pin set as low?
960    #[inline]
961    fn is_set_low(&self) -> Result<bool, Self::Error> {
962        Ok(self.is_set_low())
963    }
964}
965
966impl<'d> embedded_hal_02::digital::v2::ToggleableOutputPin for OutputOpenDrain<'d> {
967    type Error = Infallible;
968    #[inline]
969    fn toggle(&mut self) -> Result<(), Self::Error> {
970        self.toggle();
971        Ok(())
972    }
973}
974
975impl<'d> embedded_hal_02::digital::v2::InputPin for Flex<'d> {
976    type Error = Infallible;
977
978    #[inline]
979    fn is_high(&self) -> Result<bool, Self::Error> {
980        Ok(self.is_high())
981    }
982
983    #[inline]
984    fn is_low(&self) -> Result<bool, Self::Error> {
985        Ok(self.is_low())
986    }
987}
988
989impl<'d> embedded_hal_02::digital::v2::OutputPin for Flex<'d> {
990    type Error = Infallible;
991
992    #[inline]
993    fn set_high(&mut self) -> Result<(), Self::Error> {
994        self.set_high();
995        Ok(())
996    }
997
998    #[inline]
999    fn set_low(&mut self) -> Result<(), Self::Error> {
1000        self.set_low();
1001        Ok(())
1002    }
1003}
1004
1005impl<'d> embedded_hal_02::digital::v2::StatefulOutputPin for Flex<'d> {
1006    #[inline]
1007    fn is_set_high(&self) -> Result<bool, Self::Error> {
1008        Ok(self.is_set_high())
1009    }
1010
1011    /// Is the output pin set as low?
1012    #[inline]
1013    fn is_set_low(&self) -> Result<bool, Self::Error> {
1014        Ok(self.is_set_low())
1015    }
1016}
1017
1018impl<'d> embedded_hal_02::digital::v2::ToggleableOutputPin for Flex<'d> {
1019    type Error = Infallible;
1020    #[inline]
1021    fn toggle(&mut self) -> Result<(), Self::Error> {
1022        self.toggle();
1023        Ok(())
1024    }
1025}
1026
1027impl<'d> embedded_hal_1::digital::ErrorType for Input<'d> {
1028    type Error = Infallible;
1029}
1030
1031impl<'d> embedded_hal_1::digital::InputPin for Input<'d> {
1032    #[inline]
1033    fn is_high(&mut self) -> Result<bool, Self::Error> {
1034        Ok((*self).is_high())
1035    }
1036
1037    #[inline]
1038    fn is_low(&mut self) -> Result<bool, Self::Error> {
1039        Ok((*self).is_low())
1040    }
1041}
1042
1043impl<'d> embedded_hal_1::digital::ErrorType for Output<'d> {
1044    type Error = Infallible;
1045}
1046
1047impl<'d> embedded_hal_1::digital::OutputPin for Output<'d> {
1048    #[inline]
1049    fn set_high(&mut self) -> Result<(), Self::Error> {
1050        Ok(self.set_high())
1051    }
1052
1053    #[inline]
1054    fn set_low(&mut self) -> Result<(), Self::Error> {
1055        Ok(self.set_low())
1056    }
1057}
1058
1059impl<'d> embedded_hal_1::digital::StatefulOutputPin for Output<'d> {
1060    #[inline]
1061    fn is_set_high(&mut self) -> Result<bool, Self::Error> {
1062        Ok((*self).is_set_high())
1063    }
1064
1065    /// Is the output pin set as low?
1066    #[inline]
1067    fn is_set_low(&mut self) -> Result<bool, Self::Error> {
1068        Ok((*self).is_set_low())
1069    }
1070}
1071
1072impl<'d> embedded_hal_1::digital::ErrorType for OutputOpenDrain<'d> {
1073    type Error = Infallible;
1074}
1075
1076impl<'d> embedded_hal_1::digital::InputPin for OutputOpenDrain<'d> {
1077    #[inline]
1078    fn is_high(&mut self) -> Result<bool, Self::Error> {
1079        Ok((*self).is_high())
1080    }
1081
1082    #[inline]
1083    fn is_low(&mut self) -> Result<bool, Self::Error> {
1084        Ok((*self).is_low())
1085    }
1086}
1087
1088impl<'d> embedded_hal_1::digital::OutputPin for OutputOpenDrain<'d> {
1089    #[inline]
1090    fn set_high(&mut self) -> Result<(), Self::Error> {
1091        Ok(self.set_high())
1092    }
1093
1094    #[inline]
1095    fn set_low(&mut self) -> Result<(), Self::Error> {
1096        Ok(self.set_low())
1097    }
1098}
1099
1100impl<'d> embedded_hal_1::digital::StatefulOutputPin for OutputOpenDrain<'d> {
1101    #[inline]
1102    fn is_set_high(&mut self) -> Result<bool, Self::Error> {
1103        Ok((*self).is_set_high())
1104    }
1105
1106    /// Is the output pin set as low?
1107    #[inline]
1108    fn is_set_low(&mut self) -> Result<bool, Self::Error> {
1109        Ok((*self).is_set_low())
1110    }
1111}
1112
1113impl<'d> embedded_hal_1::digital::InputPin for Flex<'d> {
1114    #[inline]
1115    fn is_high(&mut self) -> Result<bool, Self::Error> {
1116        Ok((*self).is_high())
1117    }
1118
1119    #[inline]
1120    fn is_low(&mut self) -> Result<bool, Self::Error> {
1121        Ok((*self).is_low())
1122    }
1123}
1124
1125impl<'d> embedded_hal_1::digital::OutputPin for Flex<'d> {
1126    #[inline]
1127    fn set_high(&mut self) -> Result<(), Self::Error> {
1128        Ok(self.set_high())
1129    }
1130
1131    #[inline]
1132    fn set_low(&mut self) -> Result<(), Self::Error> {
1133        Ok(self.set_low())
1134    }
1135}
1136
1137impl<'d> embedded_hal_1::digital::ErrorType for Flex<'d> {
1138    type Error = Infallible;
1139}
1140
1141impl<'d> embedded_hal_1::digital::StatefulOutputPin for Flex<'d> {
1142    #[inline]
1143    fn is_set_high(&mut self) -> Result<bool, Self::Error> {
1144        Ok((*self).is_set_high())
1145    }
1146
1147    /// Is the output pin set as low?
1148    #[inline]
1149    fn is_set_low(&mut self) -> Result<bool, Self::Error> {
1150        Ok((*self).is_set_low())
1151    }
1152}