-
Notifications
You must be signed in to change notification settings - Fork 86
Add SdCardDevice trait #185
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
avsaase
wants to merge
8
commits into
rust-embedded-community:develop
Choose a base branch
from
avsaase:sd-card-device
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
cfeb777
Add SdCardDevice trait
avsaase af92c87
Wording
avsaase 3ae7018
Add init function
avsaase 469f2c9
typos
avsaase bf5eca5
Add docs
avsaase 9bf0162
Use named structs instead of tuples
avsaase 986469f
Rename SdCardDevice to SdCardSpiDevice
avsaase 0aff382
Remove redundant map_err
avsaase File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,262 @@ | ||
//! SD card SPI device trait and provided implementations. | ||
|
||
use core::cell::RefCell; | ||
|
||
use embedded_hal::{ | ||
digital::OutputPin, | ||
spi::{Operation, SpiBus}, | ||
}; | ||
|
||
/// Trait for SD cards connected via SPI. | ||
pub trait SdCardSpiDevice { | ||
/// Perform a transaction against the device. | ||
/// | ||
/// This is similar to [`embedded_hal::spi::SpiDevice::transaction`], except that this sends | ||
/// a dummy `0xFF` byte to the device after deasserting the CS pin but before unlocking the | ||
/// bus. | ||
fn transaction( | ||
&mut self, | ||
operations: &mut [Operation<'_, u8>], | ||
) -> Result<(), SdCardDeviceError>; | ||
|
||
/// Send 80 clock pulses to the device with CS deasserted. | ||
fn send_clock_pulses(&mut self) -> Result<(), SdCardDeviceError>; | ||
|
||
/// Do a read within a transaction. | ||
/// | ||
/// This is a convenience method equivalent to `device.transaction(&mut [Operation::Read(buf)])`. | ||
/// | ||
/// See also: [`SdCardDevice::transaction`], [`embedded_hal::spi::SpiBus::read`] | ||
#[inline] | ||
fn read(&mut self, buf: &mut [u8]) -> Result<(), SdCardDeviceError> { | ||
self.transaction(&mut [Operation::Read(buf)]) | ||
} | ||
|
||
/// Do a write within a transaction. | ||
/// | ||
/// This is a convenience method equivalent to `device.transaction(&mut [Operation::Write(buf)])`. | ||
/// | ||
/// See also: [`SdCardDevice::transaction`], [`embedded_hal::spi::SpiBus::write`] | ||
#[inline] | ||
fn write(&mut self, buf: &[u8]) -> Result<(), SdCardDeviceError> { | ||
self.transaction(&mut [Operation::Write(buf)]) | ||
} | ||
|
||
/// Do a transfer within a transaction. | ||
/// | ||
/// This is a convenience method equivalent to `device.transaction(&mut [Operation::Transfer(read, write)]`. | ||
/// | ||
/// See also: [`SdCardDevice::transaction`], [`embedded_hal::spi::SpiBus::transfer`] | ||
#[inline] | ||
fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), SdCardDeviceError> { | ||
self.transaction(&mut [Operation::Transfer(read, write)]) | ||
} | ||
|
||
/// Do an in-place transfer within a transaction. | ||
/// | ||
/// This is a convenience method equivalent to `device.transaction(&mut [Operation::TransferInPlace(buf)]`. | ||
/// | ||
/// See also: [`SdCardDevice::transaction`], [`embedded_hal::spi::SpiBus::transfer_in_place`] | ||
#[inline] | ||
fn transfer_in_place(&mut self, buf: &mut [u8]) -> Result<(), SdCardDeviceError> { | ||
self.transaction(&mut [Operation::TransferInPlace(buf)]) | ||
} | ||
} | ||
|
||
/// Errors that can occur when using the [`SdCardDevice`]. | ||
#[derive(Copy, Clone, Eq, PartialEq, Debug)] | ||
#[cfg_attr(feature = "defmt-log", derive(defmt::Format))] | ||
#[non_exhaustive] | ||
pub enum SdCardDeviceError { | ||
/// An operation on the inner SPI bus failed. | ||
Spi, | ||
/// Setting the value of the Chip Select (CS) pin failed. | ||
Cs, | ||
} | ||
|
||
/// A wrapper around a SPI bus and a CS pin, using a `RefCell`. | ||
/// | ||
/// This allows sharing the bus within the same thread. | ||
pub struct RefCellSdCardDevice<'a, BUS, CS> { | ||
bus: &'a RefCell<BUS>, | ||
cs: CS, | ||
} | ||
|
||
impl<'a, BUS, CS> RefCellSdCardDevice<'a, BUS, CS> { | ||
/// Create a new `RefCellSdCardDevice`. | ||
pub fn new(bus: &'a RefCell<BUS>, cs: CS) -> Self { | ||
Self { bus, cs } | ||
} | ||
} | ||
|
||
impl<BUS, CS> SdCardSpiDevice for RefCellSdCardDevice<'_, BUS, CS> | ||
where | ||
BUS: SpiBus, | ||
CS: OutputPin, | ||
{ | ||
fn transaction( | ||
&mut self, | ||
operations: &mut [Operation<'_, u8>], | ||
) -> Result<(), SdCardDeviceError> { | ||
let mut bus = self.bus.borrow_mut(); | ||
bus_transaction(&mut *bus, &mut self.cs, operations) | ||
} | ||
|
||
fn send_clock_pulses(&mut self) -> Result<(), SdCardDeviceError> { | ||
let mut bus = self.bus.borrow_mut(); | ||
send_clock_pulses(&mut *bus, &mut self.cs) | ||
} | ||
} | ||
|
||
#[cfg(feature = "embassy-sync-06")] | ||
mod embassy_sync_06 { | ||
use core::cell::RefCell; | ||
|
||
use ::embassy_sync_06::blocking_mutex; | ||
|
||
use super::*; | ||
|
||
/// A wrapper around a SPI bus and a CS pin, using an `embassy-sync` blocking mutex. | ||
/// | ||
/// This allows sharing the bus with according to the `embassy-sync` mutex model. | ||
/// See [`blocking_mutex::Mutex`] for more details. | ||
|
||
pub struct EmbassyMutexSdCardDevice<'a, BUS, CS, M> { | ||
bus: &'a blocking_mutex::Mutex<M, RefCell<BUS>>, | ||
cs: CS, | ||
} | ||
|
||
impl<'a, BUS, CS, M> EmbassyMutexSdCardDevice<'a, BUS, CS, M> { | ||
/// Create a new `EmbassyMutexSdCardDevice`. | ||
pub fn new(bus: &'a blocking_mutex::Mutex<M, RefCell<BUS>>, cs: CS) -> Self { | ||
Self { bus, cs } | ||
} | ||
} | ||
|
||
impl<CS, BUS, M> SdCardSpiDevice for EmbassyMutexSdCardDevice<'_, BUS, CS, M> | ||
where | ||
CS: OutputPin, | ||
BUS: SpiBus, | ||
M: blocking_mutex::raw::RawMutex, | ||
{ | ||
fn transaction( | ||
&mut self, | ||
operations: &mut [Operation<'_, u8>], | ||
) -> Result<(), SdCardDeviceError> { | ||
self.bus.lock(|bus| { | ||
let mut bus = bus.borrow_mut(); | ||
bus_transaction(&mut *bus, &mut self.cs, operations) | ||
}) | ||
} | ||
|
||
fn send_clock_pulses(&mut self) -> Result<(), SdCardDeviceError> { | ||
self.bus.lock(|bus| { | ||
let mut bus = bus.borrow_mut(); | ||
send_clock_pulses(&mut *bus, &mut self.cs) | ||
}) | ||
} | ||
} | ||
} | ||
|
||
#[cfg(feature = "embassy-sync-06")] | ||
pub use embassy_sync_06::*; | ||
|
||
#[cfg(feature = "embedded-hal-bus-03")] | ||
mod embedded_hal_bus_03 { | ||
use ::embedded_hal_bus_03::spi::ExclusiveDevice; | ||
use embedded_hal::spi::SpiDevice; | ||
|
||
use super::*; | ||
|
||
// `ExclusiveDevice` represents exclusive access to the bus so there's no need to send the dummy | ||
// byte after deasserting the CS pin. We can delegate the implementation to the `embedded_hal` trait. | ||
|
||
impl<CS, BUS, D> SdCardSpiDevice for ExclusiveDevice<BUS, CS, D> | ||
where | ||
BUS: SpiBus, | ||
CS: OutputPin, | ||
D: embedded_hal::delay::DelayNs, | ||
{ | ||
fn transaction( | ||
&mut self, | ||
operations: &mut [Operation<'_, u8>], | ||
) -> Result<(), SdCardDeviceError> { | ||
<Self as SpiDevice>::transaction(self, operations).map_err(|_| SdCardDeviceError::Spi) | ||
} | ||
|
||
fn send_clock_pulses(&mut self) -> Result<(), SdCardDeviceError> { | ||
let bus = self.bus_mut(); | ||
|
||
// There's no way to access the CS pin here so we can't set it high. Most likely it is already high so this is probably fine(?) | ||
|
||
let send_res = bus.write(&[0xFF; 10]); | ||
|
||
// On failure, it's important to still flush. | ||
let flush_res = bus.flush().map_err(|_| SdCardDeviceError::Spi); | ||
|
||
send_res.map_err(|_| SdCardDeviceError::Spi)?; | ||
flush_res.map_err(|_| SdCardDeviceError::Spi)?; | ||
Ok(()) | ||
} | ||
} | ||
} | ||
|
||
/// Perform a transaction against the device. This sends a dummy `0xFF` byte to the device after | ||
/// deasserting the CS pin but before unlocking the bus. | ||
fn bus_transaction<BUS, CS>( | ||
bus: &mut BUS, | ||
cs: &mut CS, | ||
operations: &mut [Operation<'_, u8>], | ||
) -> Result<(), SdCardDeviceError> | ||
where | ||
BUS: SpiBus, | ||
CS: OutputPin, | ||
{ | ||
cs.set_low().map_err(|_| SdCardDeviceError::Cs)?; | ||
|
||
let op_res = operations.iter_mut().try_for_each(|op| match op { | ||
Operation::Read(buf) => bus.read(buf), | ||
Operation::Write(buf) => bus.write(buf), | ||
Operation::Transfer(read, write) => bus.transfer(read, write), | ||
Operation::TransferInPlace(buf) => bus.transfer_in_place(buf), | ||
Operation::DelayNs(_) => { | ||
// We don't use delays in SPI transations in this crate so it fine to panic here. | ||
panic!("Tried to use a delay in a SPI transaction. This is a bug in embedded-sdmmc.") | ||
} | ||
}); | ||
|
||
// On failure, it's important to still flush and deassert CS. | ||
let flush_res = bus.flush(); | ||
let cs_res = cs.set_high(); | ||
|
||
op_res.map_err(|_| SdCardDeviceError::Spi)?; | ||
flush_res.map_err(|_| SdCardDeviceError::Spi)?; | ||
cs_res.map_err(|_| SdCardDeviceError::Cs)?; | ||
|
||
// Write the dummy byte | ||
let dummy_res = bus.write(&[0xFF]); | ||
let flush_res = bus.flush(); | ||
|
||
dummy_res.map_err(|_| SdCardDeviceError::Spi)?; | ||
flush_res.map_err(|_| SdCardDeviceError::Spi)?; | ||
|
||
Ok(()) | ||
} | ||
|
||
/// Send 80 clock pulses to the device with CS deasserted. This is needed to initialize the SD card. | ||
fn send_clock_pulses<BUS, CS>(bus: &mut BUS, cs: &mut CS) -> Result<(), SdCardDeviceError> | ||
where | ||
BUS: SpiBus, | ||
CS: OutputPin, | ||
{ | ||
cs.set_high().map_err(|_| SdCardDeviceError::Cs)?; | ||
let send_res = bus.write(&[0xFF; 10]); | ||
|
||
// On failure, it's important to still flush. | ||
let flush_res = bus.flush(); | ||
|
||
send_res.map_err(|_| SdCardDeviceError::Spi)?; | ||
flush_res.map_err(|_| SdCardDeviceError::Spi)?; | ||
|
||
Ok(()) | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This example needs to be kept in sync with the copy in readme-test.