embedded_hal_bus/i2c/
critical_section.rs
1use core::cell::RefCell;
2use critical_section::Mutex;
3use embedded_hal::i2c::{ErrorType, I2c};
4
5pub struct CriticalSectionDevice<'a, T> {
13 bus: &'a Mutex<RefCell<T>>,
14}
15
16impl<'a, T> CriticalSectionDevice<'a, T> {
17 #[inline]
19 pub fn new(bus: &'a Mutex<RefCell<T>>) -> Self {
20 Self { bus }
21 }
22}
23
24impl<'a, T> ErrorType for CriticalSectionDevice<'a, T>
25where
26 T: I2c,
27{
28 type Error = T::Error;
29}
30
31impl<'a, T> I2c for CriticalSectionDevice<'a, T>
32where
33 T: I2c,
34{
35 #[inline]
36 fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> {
37 critical_section::with(|cs| {
38 let bus = &mut *self.bus.borrow_ref_mut(cs);
39 bus.read(address, read)
40 })
41 }
42
43 #[inline]
44 fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> {
45 critical_section::with(|cs| {
46 let bus = &mut *self.bus.borrow_ref_mut(cs);
47 bus.write(address, write)
48 })
49 }
50
51 #[inline]
52 fn write_read(
53 &mut self,
54 address: u8,
55 write: &[u8],
56 read: &mut [u8],
57 ) -> Result<(), Self::Error> {
58 critical_section::with(|cs| {
59 let bus = &mut *self.bus.borrow_ref_mut(cs);
60 bus.write_read(address, write, read)
61 })
62 }
63
64 #[inline]
65 fn transaction(
66 &mut self,
67 address: u8,
68 operations: &mut [embedded_hal::i2c::Operation<'_>],
69 ) -> Result<(), Self::Error> {
70 critical_section::with(|cs| {
71 let bus = &mut *self.bus.borrow_ref_mut(cs);
72 bus.transaction(address, operations)
73 })
74 }
75}