Skip to main content

mpu9250_i2c/
i2c_tools.rs

1/*****************************************************************************
2 *                                                                           *
3 *  Copyright 2018 Simon M. Werner                                           *
4 *                                                                           *
5 *  Licensed under the Apache License, Version 2.0 (the "License");          *
6 *  you may not use this file except in compliance with the License.         *
7 *  You may obtain a copy of the License at                                  *
8 *                                                                           *
9 *      http://www.apache.org/licenses/LICENSE-2.0                           *
10 *                                                                           *
11 *  Unless required by applicable law or agreed to in writing, software      *
12 *  distributed under the License is distributed on an "AS IS" BASIS,        *
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
14 *  See the License for the specific language governing permissions and      *
15 *  limitations under the License.                                           *
16 *                                                                           *
17 *****************************************************************************/
18
19extern crate embedded_hal;
20
21use self::embedded_hal::blocking::i2c::{Read, Write, WriteRead};
22
23#[derive(Clone, Copy)]
24pub struct I2CTools<I2C> {
25  i2c: I2C,
26}
27
28impl<I2C, E> I2CTools<I2C>
29where
30  I2C: Read<Error = E> + Write<Error = E> + WriteRead<Error = E>,
31{
32  /// Creates a new driver
33  pub fn new(i2c: I2C) -> Result<Self, E> {
34    Ok(Self { i2c })
35  }
36
37  pub fn write_byte(&mut self, address: u8, reg: u8, val: u8) -> Result<(), E> {
38    let bytes = [reg, val];
39    self.i2c.write(address, &bytes)
40  }
41
42  pub fn read_byte(&mut self, address: u8, reg: u8) -> Result<u8, E> {
43    let bytes: &mut [u8] = &mut [0; 1];
44    self.read_bytes(address, reg, bytes)?;
45    Ok(bytes[0])
46  }
47
48  pub fn read_bytes(&mut self, address: u8, reg: u8, bytes: &mut [u8]) -> Result<(), E> {
49    let cmd_bytes = [reg];
50    self.i2c.write_read(address, &cmd_bytes, bytes)
51  }
52
53  pub fn u8_to_i16_be(&self, byte: &mut [u8], offset: usize) -> i16 {
54    (i16::from(byte[offset]) << 8) + i16::from(byte[offset + 1])
55  }
56  pub fn u8_to_i16_le(&self, byte: &mut [u8], offset: usize) -> i16 {
57    (i16::from(byte[offset + 1]) << 8) + i16::from(byte[offset])
58  }
59}