rust-embedded / embedded-hal

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

Generic bus traits #615

Open tamba91 opened 2 weeks ago

tamba91 commented 2 weeks ago

Hi, Lot of sensors can be used with both I2C and SPI, so why not defining a generic I/O trait that is bus independent like the std::io trait that is not available in a no_std program. In my drivers i had to define my own bus independent trait.

Vollbrecht commented 2 weeks ago

There exist https://github.com/rust-embedded/embedded-hal/tree/master/embedded-io and its used for uart. Though at the end of the day, somewhere you need to plug two things together, e.g using a spi or a i2c interface.

Making a generic version that can either hold a spi or a i2c is probably not plesent to work with. Here is why i think that is: For the Driver implementer he still would need to handle the difference in the i2c or spi protocol, so he would not gain much. From a hal perspective it would not be that bad to provide a wrapper, but the burden is here for the end user to handle the generic stuff correctly. There is a reason why most hal's currently try to axe as much generics as possible in there public facing API's.

tamba91 commented 1 week ago

Thanks for your answer, i'm trying to implement embedded-io traits but i'm having troubles in implementing embedded_io::ErrorType trait for I2C and SPI structs. How should I map the I2C and SPI errors?

Rahix commented 1 week ago

I think it would be valuable to have something like Linux' regmap API (only introduction I could quickly find) to abstract away the bus details in device drivers. This could be implemented on top of embedded-hal traits.

tamba91 commented 1 week ago

In the embedded-hal logic, HAL developers implement the embedded-hal traits, and driver developers use them. This division of responsibilities works well to maintain clear boundaries between hardware abstraction layers and driver logic.

However, it might be beneficial to consider providing traits that driver developers can implement if necessary, like in this case of SPI or I2C when dealing with a sensor. In this case this type of traits could be added to the embedded-hal-bus crate, which is used for bus sharing, but the functionality of these crate could be extended in this way.