[][src]Module embedded_hal_mock::i2c

I²C mock implementations.

Usage

extern crate embedded_hal;
extern crate embedded_hal_mock;

use embedded_hal::prelude::*;
use embedded_hal::blocking::i2c::{Read, Write, WriteRead};
use embedded_hal_mock::i2c::{Mock as I2cMock, Transaction as I2cTransaction};

// Configure expectations
let expectations = [
    I2cTransaction::write(0xaa, vec![1, 2]),
    I2cTransaction::read(0xbb, vec![3, 4]),
];
let mut i2c = I2cMock::new(&expectations);

// Writing
i2c.write(0xaa, &vec![1, 2]).unwrap();

// Reading
let mut buf = vec![0u8; 2];
i2c.read(0xbb, &mut buf).unwrap();
assert_eq!(buf, vec![3, 4]);

// Finalise expectations
i2c.done();

Transactions

There are currently three transaction types:

  • Read: This expects an I²C read command and will return the wrapped bytes.
  • Write: This expects an I²C write command with the wrapped bytes.
  • WriteRead: This expects an I²C write_read command where the expected bytes are written and the response bytes are returned.

Testing Error Handling

If you want to test error handling of your code, you can attach an error to a transaction. When the transaction is executed, an error is returned.

use std::io::ErrorKind;
use embedded_hal_mock::MockError;

// Configure expectations
let expectations = [
    I2cTransaction::write(0xaa, vec![1, 2]),
    I2cTransaction::read(0xbb, vec![3, 4]).with_error(MockError::Io(ErrorKind::Other)),
];
let mut i2c = I2cMock::new(&expectations);

// Writing returns without an error
i2c.write(0xaa, &vec![1, 2]).unwrap();

// Reading returns an error
let mut buf = vec![0u8; 2];
let err = i2c.read(0xbb, &mut buf).unwrap_err();
assert_eq!(err, MockError::Io(ErrorKind::Other));

// Finalise expectations
i2c.done();

Structs

Transaction

I2C Transaction type

Enums

Mode

I2C Transaction modes

Type Definitions

Mock

Mock I2C implementation