Skip to content

Commit dc2ce92

Browse files
Add proper error handling if CS is not dropped
1 parent 1888287 commit dc2ce92

File tree

1 file changed

+14
-2
lines changed
  • embassy-embedded-hal/src/shared_bus/asynch

1 file changed

+14
-2
lines changed

embassy-embedded-hal/src/shared_bus/asynch/spi.rs

+14-2
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ where
7272
self.cs.set_low().map_err(SpiDeviceError::Cs)?;
7373

7474
let cs_drop = OnDrop::new(|| {
75+
// This drop guard deasserts CS pin if the async operation is cancelled.
76+
// Errors are ignored in this drop handler, as there's nothing we can do about them.
77+
// If the async operation is completed without cancellation, this handler will not
78+
// be run, and the CS pin will be deasserted with proper error handling.
7579
let _ = self.cs.set_high();
7680
});
7781

@@ -102,10 +106,15 @@ where
102106

103107
// On failure, it's important to still flush and deassert CS.
104108
let flush_res = bus.flush().await;
105-
drop(cs_drop);
109+
110+
// Now that all the async operations are done, we defuse the CS guard,
111+
// and manually set the CS pin low (to better handle the possible errors).
112+
cs_drop.defuse();
113+
let cs_res = self.cs.set_high();
106114

107115
let op_res = op_res.map_err(SpiDeviceError::Spi)?;
108116
flush_res.map_err(SpiDeviceError::Spi)?;
117+
cs_res.map_err(SpiDeviceError::Cs)?;
109118

110119
Ok(op_res)
111120
}
@@ -160,6 +169,7 @@ where
160169
self.cs.set_low().map_err(SpiDeviceError::Cs)?;
161170

162171
let cs_drop = OnDrop::new(|| {
172+
// Please see comment in SpiDevice for an explanation of this drop handler.
163173
let _ = self.cs.set_high();
164174
});
165175

@@ -190,10 +200,12 @@ where
190200

191201
// On failure, it's important to still flush and deassert CS.
192202
let flush_res = bus.flush().await;
193-
drop(cs_drop);
203+
cs_drop.defuse();
204+
let cs_res = self.cs.set_high();
194205

195206
let op_res = op_res.map_err(SpiDeviceError::Spi)?;
196207
flush_res.map_err(SpiDeviceError::Spi)?;
208+
cs_res.map_err(SpiDeviceError::Cs)?;
197209

198210
Ok(op_res)
199211
}

0 commit comments

Comments
 (0)