Add AnyPin::downcast (#3783)

This commit is contained in:
Dániel Buga 2025-07-10 14:53:30 +02:00 committed by GitHub
parent cbdb4f05ba
commit fbac30993a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 51 additions and 0 deletions

View File

@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The functions of the `RadioClockController` have been split up to the modem peripheral structs. The clock management is now provided by the `ModemClockController`. (#3687)
- Added GPIO11-GPIO17 to ESP32-C2. (#3726)
- Added the feature `requires-unstable` (#3772)
- `AnyPin::downcast` to allow retrieving the original GPIO type (#3783)
### Changed

View File

@ -2167,6 +2167,56 @@ impl InputPin for AnyPin<'_> {
}
impl OutputPin for AnyPin<'_> {}
for_each_gpio! {
($n:literal, $gpio:ident $($_rest:tt)*) => {
impl<'lt> TryFrom<AnyPin<'lt>> for crate::peripherals::$gpio<'lt> {
type Error = AnyPin<'lt>;
fn try_from(any_pin: AnyPin<'lt>) -> Result<Self, Self::Error> {
if any_pin.number() == $n {
Ok(unsafe { Self::steal() })
} else {
Err(any_pin)
}
}
}
};
}
impl AnyPin<'_> {
#[procmacros::doc_replace]
/// Attempts to downcast the pin into the underlying GPIO instance.
///
/// ## Example
///
/// ```rust,no_run
/// # {before_snippet}
/// #
/// use esp_hal::{
/// gpio::AnyPin,
/// peripherals::{GPIO2, GPIO4},
/// };
///
/// let any_pin2 = AnyPin::from(peripherals.GPIO2);
/// let any_pin3 = AnyPin::from(peripherals.GPIO3);
///
/// let gpio2 = any_pin2
/// .downcast::<GPIO2>()
/// .expect("This downcast succeeds because AnyPin was created from GPIO2");
/// let gpio4 = any_pin3
/// .downcast::<GPIO4>()
/// .expect_err("This AnyPin was created from GPIO3, it cannot be downcast to GPIO4");
/// #
/// # {after_snippet}
/// ```
pub fn downcast<P: Pin>(self) -> Result<P, Self>
where
Self: TryInto<P, Error = Self>,
{
self.try_into()
}
}
#[cfg(not(esp32h2))]
impl RtcPin for AnyPin<'_> {
#[cfg(xtensa)]