Skip to content

Commit d187dc0

Browse files
Add a doc example for i2c::RefCellDevice
1 parent 3a7c3ca commit d187dc0

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

embedded-hal-bus/src/i2c/refcell.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,63 @@ pub struct RefCellDevice<'a, T> {
1212

1313
impl<'a, T> RefCellDevice<'a, T> {
1414
/// Create a new `RefCellDevice`
15+
///
16+
/// # Examples
17+
///
18+
/// Assuming there is a pressure sensor with address `0x42` on the same bus as a temperature sensor
19+
/// with address `0x20`; [`RefCellDevice`] can be used to give access to both of these sensors
20+
/// from a single `i2c` instance.
21+
///
22+
/// ```
23+
/// use embedded_hal_bus::i2c;
24+
/// use core::cell::RefCell;
25+
/// # use embedded_hal::i2c::{self as hali2c, SevenBitAddress, TenBitAddress, I2c, Operation, ErrorKind};
26+
/// # pub struct Sensor<I2C> {
27+
/// # i2c: I2C,
28+
/// # address: u8,
29+
/// # }
30+
/// # impl<I2C: I2c> Sensor<I2C> {
31+
/// # pub const fn new(i2c: I2C, address: u8) -> Self {
32+
/// # Self { i2c, address }
33+
/// # }
34+
/// # }
35+
/// # type PressureSensor = Sensor;
36+
/// # type TemperatureSensor = Sensor;
37+
/// # pub struct I2c0;
38+
/// # #[derive(Debug, Copy, Clone, Eq, PartialEq)]
39+
/// # pub enum Error { }
40+
/// # impl hali2c::Error for Error {
41+
/// # fn kind(&self) -> hali2c::ErrorKind {
42+
/// # ErrorKind::Other
43+
/// # }
44+
/// # }
45+
/// # impl hali2c::ErrorType for I2c0 {
46+
/// # type Error = Error;
47+
/// # }
48+
/// # impl I2c<SevenBitAddress> for I2c0 {
49+
/// # fn transaction(&mut self, address: u8, operations: &mut [Operation<'_>]) -> Result<(), Self::Error> {
50+
/// # Ok(())
51+
/// # }
52+
/// # }
53+
/// # struct Hal;
54+
/// # impl Hal {
55+
/// # fn i2c(&self) -> I2c0 {
56+
/// # I2c0
57+
/// # }
58+
/// # }
59+
/// # let hal = Hal;
60+
///
61+
/// let i2c = hal.i2c();
62+
/// let i2c_ref_cell = RefCell::new(i2c);
63+
/// let mut temperature_sensor = TemperatureSensor::new(
64+
/// i2c::RefCellDevice::new(&i2c_ref_cell),
65+
/// 0x20,
66+
/// );
67+
/// let mut pressure_sensor = PressureSensor::new(
68+
/// i2c::RefCellDevice::new(&i2c_ref_cell),
69+
/// 0x42,
70+
/// );
71+
/// ```
1572
pub fn new(bus: &'a RefCell<T>) -> Self {
1673
Self { bus }
1774
}

0 commit comments

Comments
 (0)