Skip to content

Commit 694553c

Browse files
committed
Fix spi transactions
1 parent 850cfc1 commit 694553c

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed

src/spi.rs

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -88,19 +88,27 @@ mod embedded_hal_impl {
8888

8989
impl SpiDeviceRead for Spidev {
9090
fn read_transaction(&mut self, operations: &mut [&mut [u8]]) -> Result<(), Self::Error> {
91-
for buf in operations {
92-
SpiBusRead::read(self, buf)?;
93-
}
91+
let mut transfers: Vec<_> = operations
92+
.iter_mut()
93+
.map(|op| SpidevTransfer::read(op))
94+
.collect();
95+
self.0
96+
.transfer_multiple(&mut transfers)
97+
.map_err(|err| SPIError { err })?;
9498
self.flush()?;
9599
Ok(())
96100
}
97101
}
98102

99103
impl SpiDeviceWrite for Spidev {
100104
fn write_transaction(&mut self, operations: &[&[u8]]) -> Result<(), Self::Error> {
101-
for buf in operations {
102-
SpiBusWrite::write(self, buf)?;
103-
}
105+
let mut transfers: Vec<_> = operations
106+
.iter()
107+
.map(|op| SpidevTransfer::write(op))
108+
.collect();
109+
self.0
110+
.transfer_multiple(&mut transfers)
111+
.map_err(|err| SPIError { err })?;
104112
self.flush()?;
105113
Ok(())
106114
}
@@ -111,12 +119,24 @@ mod embedded_hal_impl {
111119
&mut self,
112120
operations: &mut [SpiOperation<'_, u8>],
113121
) -> Result<(), Self::Error> {
114-
operations.iter_mut().try_for_each(|op| match op {
115-
SpiOperation::Read(buf) => SpiBusRead::read(self, buf),
116-
SpiOperation::Write(buf) => SpiBusWrite::write(self, buf),
117-
SpiOperation::Transfer(read, write) => SpiBus::transfer(self, read, write),
118-
SpiOperation::TransferInPlace(buf) => SpiBus::transfer_in_place(self, buf),
119-
})?;
122+
let mut transfers: Vec<_> = operations
123+
.iter_mut()
124+
.map(|op| match op {
125+
SpiOperation::Read(buf) => SpidevTransfer::read(buf),
126+
SpiOperation::Write(buf) => SpidevTransfer::write(buf),
127+
SpiOperation::Transfer(read, write) => SpidevTransfer::read_write(write, read),
128+
SpiOperation::TransferInPlace(buf) => {
129+
let tx = unsafe {
130+
let p = buf.as_ptr();
131+
std::slice::from_raw_parts(p, buf.len())
132+
};
133+
SpidevTransfer::read_write(tx, buf)
134+
}
135+
})
136+
.collect();
137+
self.0
138+
.transfer_multiple(&mut transfers)
139+
.map_err(|err| SPIError { err })?;
120140
self.flush()?;
121141
Ok(())
122142
}

0 commit comments

Comments
 (0)