1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! A driver for the TI INA260 magnetometer
//!
//! This driver was built using [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal/~0.1
//!
//! # Examples
//!
//! None

#![no_std]

use embedded_hal as hal;

use core::mem;

use crate::hal::blocking::i2c::{Write, WriteRead};
use cast::{i32, u16, u32};

#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
pub enum Register {
    // Configuration Register
    CONFIG = 0x00,
    // Contains the value of the current flowing through the shunt resistor
    CURRENT = 0x01,
    // Bus voltage measurement data
    VOLTAGE = 0x02,
    // Contains the value of the calculated power being delivered to the load
    POWER = 0x03,
    // Alert configuration and conversion ready flag
    MASK_ENABLE = 0x06,
    // Contains the limit value to compare to the selected alert function
    ALERT_LIMIT = 0x07,
    // Contains unique manufacturer identification number
    MANUFACTURER_ID = 0xFE,
    // Contains unique die identification number
    DIE_ID = 0xFF,
}

impl Register {
    #[inline(always)]
    pub fn addr(self) -> u8 {
        self as u8
    }
}

#[allow(dead_code)]
#[derive(Copy, Clone)]
/// Averaging Mode
/// Determines the number of samples that are collected and averaged.
pub enum Averaging {
    // No averaging (default)
    AVG1 = 0b0000_0000_0000_0000,
    // 4 times averaging
    AVG4 = 0b0000_0010_0000_0000,
    // 16 times averaging
    AVG16 = 0b0000_0100_0000_0000,
    // 64 times averaging
    AVG64 = 0b0000_0110_0000_0000,
    // 128 times averaging
    AVG128 = 0b0000_1000_0000_0000,
    // 256 times averaging
    AVG256 = 0b0000_1010_0000_0000,
    // 512 times averaging
    AVG512 = 0b0000_1100_0000_0000,
    // 1024 times averaging
    AVG1024 = 0b0000_1110_0000_0000,
}

impl Averaging {
    #[inline(always)]
    pub fn bits(self) -> u16 {
        self as u16
    }
}

#[allow(dead_code)]
#[derive(Copy, Clone)]
/// Bus Voltage Conversion Time
/// Sets the conversion time for the bus voltage measurement
pub enum BVConvTime {
    // Conversion time = 140 µs
    US140 = 0b0000_0000_0000_0000,
    // Conversion time = 204 µs
    US204 = 0b0000_0000_0100_0000,
    // Conversion time = 332 µs
    US332 = 0b0000_0000_1000_0000,
    // Conversion time = 588 µs
    US588 = 0b0000_0000_1100_0000,
    // Conversion time = 1.1 ms (default)
    MS1_1 = 0b0000_0001_0000_0000,
    // Conversion time = 2.116 ms
    MS2_116 = 0b0000_0001_0100_0000,
    // Conversion time = 4.156 ms
    MS4_156 = 0b0000_0001_1000_0000,
    // Conversion time = 8.244 ms
    MS8_244 = 0b0000_0001_1100_0000,
}

impl BVConvTime {
    #[inline(always)]
    pub fn bits(self) -> u16 {
        self as u16
    }
}

#[allow(dead_code)]
#[derive(Copy, Clone)]
/// Shunt Current Conversion Time
/// Sets the conversion time for the shunt current measurement
pub enum SCConvTime {
    // Conversion time = 140 µs
    US140 = 0b0000_0000_0000_0000,
    // Conversion time = 204 µs
    US204 = 0b0000_0000_0000_1000,
    // Conversion time = 332 µs
    US332 = 0b0000_0000_0001_0000,
    // Conversion time = 588 µs
    US588 = 0b0000_0000_0001_1000,
    // Conversion time = 1.1 ms (default)
    MS1_1 = 0b0000_0000_0010_0000,
    // Conversion time = 2.116 ms
    MS2_116 = 0b0000_0000_0010_1000,
    // Conversion time = 4.156 ms
    MS4_156 = 0b0000_0000_0011_0000,
    // Conversion time = 8.244 ms
    MS8_244 = 0b0000_0000_0011_1000,
}

impl SCConvTime {
    #[inline(always)]
    pub fn bits(self) -> u16 {
        self as u16
    }
}

#[allow(dead_code)]
#[derive(Copy, Clone)]
/// Operating Mode
/// Selects continuous, triggered, or power-down mode of operation.
pub enum OperMode {
    // Power-Down (or Shutdown)
    SHUTDOWN = 0b0000_0000_0000_0000,
    // = Shunt Current, Triggered
    SCT = 0b0000_0000_0000_0001,
    // = Shunt Current, Triggered
    BVT = 0b0000_0000_0000_0010,
    // = Shunt Current + Bus Voltage, Triggered
    SCBVT = 0b0000_0000_0000_0011,
    // = Shunt Current, Continuous
    SCC = 0b0000_0000_0000_0101,
    // = Bus Voltage, Continuous
    BVC = 0b0000_0000_0000_0110,
    // = Shunt Current + Bus Voltage, Continuous (default)
    SCBVC = 0b0000_0000_0000_0111,
}

impl OperMode {
    #[inline(always)]
    pub fn bits(self) -> u16 {
        self as u16
    }
}

#[inline(always)]
fn write_register<I2C>(
    i2c: &mut I2C,
    address: u8,
    reg: Register,
    data: u16,
) -> Result<(), I2C::Error>
where
    I2C: Write,
{
    i2c.write(
        address,
        &[reg.addr(), (data >> 8) as u8, (data & 255) as u8],
    )
}

pub struct INA260NonOwned<I2C> {
    address: u8,
    state: u16,
    _marker: core::marker::PhantomData<I2C>,
}

impl<I2C, E> INA260NonOwned<I2C>
where
    I2C: WriteRead<Error = E> + Write<Error = E>,
{
    /// Add a new driver for a INA260 chip found on the I2C bus at the specified address
    #[inline(always)]
    pub fn new(i2c: &mut I2C, address: u8) -> Result<Self, E> {
        let ina260 = Self {
            _marker: core::marker::PhantomData,
            address,
            state: OperMode::SCBVC.bits()
                | Averaging::AVG1.bits()
                | SCConvTime::MS1_1.bits()
                | BVConvTime::MS1_1.bits(),
        };
        write_register(i2c, address, Register::CONFIG, 0x8000)?;
        Ok(ina260)
    }

    /// Change the averaging mode of the INA260
    #[inline(always)]
    pub fn set_averaging_mode(&mut self, i2c: &mut I2C, a: Averaging) -> Result<(), E> {
        let bits = a.bits();
        let state = (self.state & !Averaging::AVG1024.bits()) | bits;
        write_register(i2c, self.address, Register::CONFIG, state)?;
        self.state = state;
        Ok(())
    }

    /// Change the operating mode of the INA260. Please note that if you change to Triggered mode,
    /// you'll have to call this method again each time you would like to get a new sample.
    #[inline(always)]
    pub fn set_operating_mode(&mut self, i2c: &mut I2C, o: OperMode) -> Result<(), E> {
        let bits = o.bits();
        let state = (self.state & !OperMode::SCBVC.bits()) | bits;
        write_register(i2c, self.address, Register::CONFIG, state)?;
        self.state = state;
        Ok(())
    }

    /// Change the shut current conversion time
    #[inline(always)]
    pub fn set_scconvtime_mode(&mut self, i2c: &mut I2C, s: SCConvTime) -> Result<(), E> {
        let bits = s.bits();
        let state = (self.state & !SCConvTime::MS8_244.bits()) | bits;
        write_register(i2c, self.address, Register::CONFIG, state)?;
        self.state = state;
        Ok(())
    }

    /// Change the bus voltage conversion time
    #[inline(always)]
    pub fn set_bvconvtime_mode(&mut self, i2c: &mut I2C, b: BVConvTime) -> Result<(), E> {
        let bits = b.bits();
        let state = (self.state & !BVConvTime::MS8_244.bits()) | bits;
        write_register(i2c, self.address, Register::CONFIG, state)?;
        self.state = state;
        Ok(())
    }

    /// Delivers the unique chip id
    #[inline(always)]
    pub fn did(&mut self, i2c: &mut I2C) -> Result<u16, E> {
        let mut buffer: [u8; 2] = unsafe { mem::uninitialized() };
        i2c.write_read(self.address, &[Register::DIE_ID.addr()], &mut buffer)?;

        Ok((u16(buffer[0]) << 8 | u16(buffer[1])) >> 4)
    }

    /// Delivers the die revision id
    #[inline(always)]
    pub fn rid(&mut self, i2c: &mut I2C) -> Result<u16, E> {
        let mut buffer: [u8; 2] = unsafe { mem::uninitialized() };
        i2c.write_read(self.address, &[Register::DIE_ID.addr()], &mut buffer)?;

        Ok(u16(buffer[1]) & 0b1111)
    }

    /// Delivers the measured raw current in 1.25mA per bit
    #[inline(always)]
    pub fn current_raw(&mut self, i2c: &mut I2C) -> Result<i16, E> {
        let mut buffer: [u8; 2] = unsafe { mem::uninitialized() };
        i2c.write_read(self.address, &[Register::CURRENT.addr()], &mut buffer)?;

        Ok((u16(buffer[0]) << 8 | u16(buffer[1])) as i16)
    }

    /// Delivers the measured current in uA
    #[inline(always)]
    pub fn current(&mut self, i2c: &mut I2C) -> Result<i32, E> {
        let raw = self.current_raw(i2c)?;
        Ok(i32(raw) * 1250)
    }

    /// Delivers the measured current in as tuple of full volts and tenth millivolts
    #[inline(always)]
    pub fn current_split(&mut self, i2c: &mut I2C) -> Result<(i8, u32), E> {
        let raw = i32::from(self.current_raw(i2c)?);
        if raw >= 0 {
            let full = (0..=raw).step_by(800).skip(1).count() as i32;
            let rest = (raw - (full * 800)) * 125;
            Ok((full as i8, rest as u32))
        } else {
            let full = -((raw..=0).step_by(800).skip(1).count() as i32);
            let rest = -(raw - (full * 800)) * 125;
            Ok((full as i8, rest as u32))
        }
    }

    /// Delivers the measured raw voltage in 1.25mV per bit
    #[inline(always)]
    pub fn voltage_raw(&mut self, i2c: &mut I2C) -> Result<u16, E> {
        let mut buffer: [u8; 2] = unsafe { mem::uninitialized() };
        i2c.write_read(self.address, &[Register::VOLTAGE.addr()], &mut buffer)?;

        Ok(u16(buffer[0]) << 8 | u16(buffer[1]))
    }

    /// Delivers the measured voltage in uV
    #[inline(always)]
    pub fn voltage(&mut self, i2c: &mut I2C) -> Result<u32, E> {
        let raw = self.voltage_raw(i2c)?;
        Ok(u32(raw) * 1250)
    }

    /// Delivers the measured voltage in as tuple of full volts and tenth millivolts
    #[inline(always)]
    pub fn voltage_split(&mut self, i2c: &mut I2C) -> Result<(u8, u32), E> {
        let raw = u32::from(self.voltage_raw(i2c)?);
        let full = (0..=raw).step_by(800).skip(1).count() as u32;
        let rest = (raw - (full * 800)) * 125;
        Ok((full as u8, rest))
    }

    /// Delivers the measured power in 10mW per bit
    #[inline(always)]
    pub fn power_raw(&mut self, i2c: &mut I2C) -> Result<u16, E> {
        let mut buffer: [u8; 2] = unsafe { mem::uninitialized() };
        i2c.write_read(self.address, &[Register::POWER.addr()], &mut buffer)?;

        Ok(u16(buffer[0]) << 8 | u16(buffer[1]))
    }

    /// Delivers the measured raw power in mW
    #[inline(always)]
    pub fn power(&mut self, i2c: &mut I2C) -> Result<u32, E> {
        let raw = self.power_raw(i2c)?;
        Ok(u32(raw) * 10)
    }

    /// Delivers the measured power in as tuple of full volts and tenth millivolts
    #[inline(always)]
    pub fn power_split(&mut self, i2c: &mut I2C) -> Result<(u8, u32), E> {
        let raw = u32::from(self.power_raw(i2c)?);
        let full = (0..=raw).step_by(100).skip(1).count() as u32;
        let rest = (raw - (full * 100)) * 1000;
        Ok((full as u8, rest))
    }
}

pub struct INA260<I2C>(I2C, INA260NonOwned<I2C>);

impl<I2C, E> INA260<I2C>
where
    I2C: WriteRead<Error = E> + Write<Error = E>,
{
    /// Add a new driver for a INA260 chip found on the I2C bus at the specified address
    #[inline(always)]
    pub fn new(mut i2c: I2C, address: u8) -> Result<Self, E> {
        let ina260 = INA260NonOwned::new(&mut i2c, address)?;
        Ok(Self(i2c, ina260))
    }

    /// Put the INA260 chip managed by the driver in shut down and release I2C resource
    #[inline(always)]
    pub fn release(mut self) -> I2C {
        let _ = self.set_operating_mode(OperMode::SHUTDOWN);
        self.0
    }

    /// Change the averaging mode of the INA260
    #[inline(always)]
    pub fn set_averaging_mode(&mut self, a: Averaging) -> Result<(), E> {
        self.1.set_averaging_mode(&mut self.0, a)
    }

    /// Change the operating mode of the INA260. Please note that if you change to Triggered mode,
    /// you'll have to call this method again each time you would like to get a new sample.
    #[inline(always)]
    pub fn set_operating_mode(&mut self, o: OperMode) -> Result<(), E> {
        self.1.set_operating_mode(&mut self.0, o)
    }

    /// Change the shut current conversion time
    #[inline(always)]
    pub fn set_scconvtime_mode(&mut self, s: SCConvTime) -> Result<(), E> {
        self.1.set_scconvtime_mode(&mut self.0, s)
    }

    /// Change the bus voltage conversion time
    #[inline(always)]
    pub fn set_bvconvtime_mode(&mut self, b: BVConvTime) -> Result<(), E> {
        self.1.set_bvconvtime_mode(&mut self.0, b)
    }

    /// Delivers the unique chip id
    #[inline(always)]
    pub fn did(&mut self) -> Result<u16, E> {
        self.1.did(&mut self.0)
    }

    /// Delivers the die revision id
    #[inline(always)]
    pub fn rid(&mut self) -> Result<u16, E> {
        self.1.rid(&mut self.0)
    }

    /// Delivers the measured raw current in 1.25mA per bit
    #[inline(always)]
    pub fn current_raw(&mut self) -> Result<i16, E> {
        self.1.current_raw(&mut self.0)
    }

    /// Delivers the measured current in uA
    #[inline(always)]
    pub fn current(&mut self) -> Result<i32, E> {
        self.1.current(&mut self.0)
    }

    /// Delivers the measured current in as tuple of full volts and tenth millivolts
    #[inline(always)]
    pub fn current_split(&mut self) -> Result<(i8, u32), E> {
        self.1.current_split(&mut self.0)
    }

    /// Delivers the measured raw voltage in 1.25mV per bit
    #[inline(always)]
    pub fn voltage_raw(&mut self) -> Result<u16, E> {
        self.1.voltage_raw(&mut self.0)
    }

    /// Delivers the measured voltage in uV
    #[inline(always)]
    pub fn voltage(&mut self) -> Result<u32, E> {
        self.1.voltage(&mut self.0)
    }

    /// Delivers the measured voltage in as tuple of full volts and tenth millivolts
    #[inline(always)]
    pub fn voltage_split(&mut self) -> Result<(u8, u32), E> {
        self.1.voltage_split(&mut self.0)
    }

    /// Delivers the measured power in 10mW per bit
    #[inline(always)]
    pub fn power_raw(&mut self) -> Result<u16, E> {
        self.1.power_raw(&mut self.0)
    }

    /// Delivers the measured raw power in mW
    #[inline(always)]
    pub fn power(&mut self) -> Result<u32, E> {
        self.1.power(&mut self.0)
    }

    /// Delivers the measured power in as tuple of full volts and tenth millivolts
    #[inline(always)]
    pub fn power_split(&mut self) -> Result<(u8, u32), E> {
        self.1.power_split(&mut self.0)
    }
}