stm32l0xx-hal
stm32l0xx-hal copied to clipboard
Alternative Functions as Pin Modes
In stm32l0xx-hal, we implement traits for pins in any mode and then configure the proper mode for those pins in a setup
trait method. For example, for serial:
impl<MODE> TxPin<USART4> for PA0<MODE> {
fn setup(&self) {
self.set_alt_mode(AltMode::AF6);
}
}
In contrast, in the stm32f0xx-hal, alternative functions are pin modes, just like Input or Output:
/// Alternate mode
pub struct Alternate<MODE> {
_mode: PhantomData<MODE>,
}
/// Pin
pub struct PA0<MODE> {
_mode: PhantomData<MODE>,
}
impl<MODE> PA0<MODE> {
/// Configures the pin to operate in AF0 mode
pub fn into_alternate_af0(self, _cs: &CriticalSection) -> PA0<Alternate<AF0>> {
_set_alternate_mode($i, 0);
PA0 { _mode: PhantomData }
}
...
The trait impls are purely marker traits and expect the pins to be in the proper state.
I think this is the much nicer design for three reasons:
- The user is aware that pins need to be put into the correct mode, it's not something that happens implicitly. Furthermore, if the pin already is in the right mode, then nothing needs to be done.
- These marker traits can be easily implemented using a "universal pin mappings" macro, see https://github.com/stm32-rs/stm32f0xx-hal/pull/29
- Since the
setup
method is not implemented for every pin, the resulting binary might be smaller (unless this is optimized out by the compiler).
Thoughts?