spi-memory
spi-memory copied to clipboard
Borrow spi instead of owning
https://github.com/jonas-schievink/spi-memory/issues/19
This implementation isn't the most elegant. It could be improved by storing the mutable reference in the structure, but I don't have the skill to do this. The cost of my approach is that both the internal code, and API calls require passing &spi
each time. I still think it's worth it, since this allows you to use the same SPI peripherals for multiple devices, which is important.
I agree that supporting this use case somehow is important, but I'm not sure this is the best way to do that. What do other driver crates do to handle this?
If you use shared-bus
, or there was a impl<T: Transfer<u8>> Transfer<u8> for &mut T
, then we wouldn't have to change anything besides adding a free
method or a method that grants mutable access to the SPI bus. Even with just these methods you could work around this issue today by defining your own newtype around the SPI peripheral.
The other SPI peripheral I'm using, epd_waveshare uses mutable references in the functions, in a similar way to this.
this module I found as the first entry on the awsome-embedded list for SPi takes the SPI periph back with a destroy
method.
As far as I can tell, these are the two main approaches, but these are anecdotes.
I'd prefer to add a free
method then, since it doesn't force every user of this crate to always pass &mut spi
to all the functions.
We can also add a method that returns a mutable reference to the SPI, for temporary operations.
I feel like free/consuming can get verbose if you're using more than one device on the perhiph, since you need to constantly free/consume, track state, and hope all crates using this pattern handle use-while-freed elegantly. Using a mutable reference requires passing the periph every time (eg adding &mut spi
) to every method's arg list), but you don't need to track state, and it's not possible to accidentally use the perhip while it's not owned.
So overall, I think the borrow mut approach is both less verbose (Despite appearing more so at first), and less error-prone.
FYI I added enter and exit power_down
(low power) mode to this branch.
FWIW, I am also sharing SPI between spi-memory
and edp-waveshare
and had to deal with this issue. share-bus
allowed me to work around this, but would prefer a consistent use of the SPI resource between both libraries.