Skip to content

Commit

Permalink
Add support for writing u8 commands
Browse files Browse the repository at this point in the history
The Sensirion SHT4x series uses 8 bit commands and the new function
write_command_u8 has been added to support these devices as well.

For the sake of a clean naming scheme, write_command_u16 is provided as
a replacement for write_command. The latter is still available but
deprecated.

Using suffixes to distinguish between u8 and u16 commands has been
chosen because there is no trait for to_be_bytes which would allow to
use a generic function. The crate num_traits provides the trait PrimInt
which covers to_be but not to_be_bytes. See
rust-num/num-traits#189 for details.
  • Loading branch information
sirhcel committed Dec 29, 2021
1 parent 8728692 commit 1152973
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion src/i2c.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Helper functions for the u16 word based I²C communication.
//! Helper functions for I²C communication.

use crate::crc8;
use embedded_hal::blocking::i2c;
Expand All @@ -20,10 +20,29 @@ impl<W: i2c::Write, R: i2c::Read> From<crc8::Error> for Error<W, R> {
}

/// Write an u16 command to the I²C bus.
#[deprecated(note = "Please use `write_command_u16` instead.")]
pub fn write_command<I2cWrite: i2c::Write>(
i2c: &mut I2cWrite,
addr: u8,
command: u16,
) -> Result<(), I2cWrite::Error> {
write_command_u16(i2c, addr, command)
}

/// Write an u8 command to the I²C bus.
pub fn write_command_u8<I2cWrite: i2c::Write>(
i2c: &mut I2cWrite,
addr: u8,
command: u8,
) -> Result<(), I2cWrite::Error> {
i2c.write(addr, &command.to_be_bytes())
}

/// Write an u16 command to the I²C bus.
pub fn write_command_u16<I2cWrite: i2c::Write>(
i2c: &mut I2cWrite,
addr: u8,
command: u16,
) -> Result<(), I2cWrite::Error> {
i2c.write(addr, &command.to_be_bytes())
}
Expand Down Expand Up @@ -79,6 +98,7 @@ mod tests {
}

#[test]
#[allow(deprecated)]
fn write_command() {
let expectations = [Transaction::write(0x58, vec![0xab, 0xcd])];
let mut mock = I2cMock::new(&expectations);
Expand All @@ -87,4 +107,24 @@ mod tests {

mock.done();
}

#[test]
fn write_command_u8() {
let expectations = [Transaction::write(0x58, vec![0xab])];
let mut mock = I2cMock::new(&expectations);

i2c::write_command_u8(&mut mock, 0x58, 0xab).unwrap();

mock.done();
}

#[test]
fn write_command_u16() {
let expectations = [Transaction::write(0x58, vec![0xab, 0xcd])];
let mut mock = I2cMock::new(&expectations);

i2c::write_command_u16(&mut mock, 0x58, 0xabcd).unwrap();

mock.done();
}
}

0 comments on commit 1152973

Please sign in to comment.