Casting to embedded hal

I am trying to build a library which only uses the embedded hal traits but struggling to understand how to do it for the Write function for uart

I see there is a
embedded_hal_nb::serial::ErrorType
embedded_hal_nb::serial::Write

But cannot figure out how to make the esp-hal function Write convert to these types.

uart: Box<dyn embedded_hal_nb::serial::Write<Error = Box>>

So I have a struct

#[cfg(feature = "feature2")]
pub struct My8Device {
    uart: Box<dyn embedded_hal_nb::serial::Write<Error = Box<dyn embedded_hal_nb::serial::Error>>>,
}

I don't want to include the esp-hal in the library because I want it re-usable for stm32 etc. I kind of assumed (bad word I know) that this is why the embedded hal exists.

A little new to rust to apologies if this is a stupid question.

Thanks as ever

If you don't need a trait object (Box<dyn Write>) and can work with generics, you can rewrite your code like this:

pub struct My8Device<T: embedded_hal_nb::serial::Write> {
    uart: T,
}

This allows your library's users to use any UART implementation that implements the Write trait. The associated type (Error) is defined in each specific UART implementation.

1 Like

So is there no way to wrap the write. I also wanted to use SerialPort for linux?

I know nothing about SerialPort for Linux, but if it doesn’t implement the embedded-hal traits, it won’t work—whether you use a trait object or generics.

I would use embedded-io and/or embedded-io-async instead of embedded-hal-nb for new projects. As far as I can see it's where the ecosystem is leaning towards.

Worked like a charm, think I stared at it too long or a low caffeine day. Thanks