rust-embedded / embedded-hal

A Hardware Abstraction Layer (HAL) for embedded systems
Apache License 2.0
2.01k stars 202 forks source link

Is there a common way to handle inverted pins? #366

Closed DrTobe closed 2 years ago

DrTobe commented 2 years ago

On my current development board some digital pins between MCU and peripheral are inverted. For the peripheral device driver I am working on, I have to handle this pin inversion somehow. The stm32l4xx-hal for the MCU does not allow pin inversion, which seems to be the right thing because it describes/handles the pin states at the MCU chip boundary. But handling the inversion in the device driver itself feels wrong, too, because the device driver should only care about its own chip boundary in my opinion.

So I thought about creating a simple type InvertedPin which implements the different embedded-hal traits for gpio pins and just inverts everything. This seems to be such a common thing to do that I thought initially that this could also be incorporated into embedded-hal itself. But regarding the fact that embedded-hal is only a collection of traits, this would not belong there.

In https://github.com/rust-embedded/embedded-hal/issues/68#issuecomment-379065191, there was a suggestion to create a hal-support crate and "negating a pin" was mentioned as a possible feature. But to my knowledge, no such crate exists currently.

So is there already any common way to handle this which I have overlooked? If not, what are your opinions on this topic?

adamgreig commented 2 years ago

There's https://crates.io/crates/switch-hal which handles some level of things like this, but it's probably not ideal for using in a generic driver.

eldruin commented 2 years ago

It is a bit funny that independently of this, I published an inverted-pin crate exactly yesterday :) It implements the straightforward boilerplate of wrapping an output or input pin and calling the opposite methods. e.g. calling set_high() on an InvertedPin calls set_low() on the wrapped output pin. You can wrap the output pin in an inverted pin in your code and pass that to your driver. Would that fit your use case?

DrTobe commented 2 years ago

I published an inverted-pin crate exactly yesterday :)

You are kidding me :) I had a look at crates.io a few days ago so I was quite sure there was not such a package.

And yes, this fits my use case, this is exactly what I had in mind, even the code looks like I had imagined it. Thanks for being faster than me ;)