ltr303 0.1.4

Platform agnostic Rust driver for the LTR-303 Ambient Light Sensor.
Documentation
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! # Introduction
//! This is a platform-agnostic Rust driver for the [`LTR-303 Ambient Light Sensor`](https://optoelectronics.liteon.com/en-global/Led/LED-Component/Detail/926/0/0/16/200) using [`embedded-hal`](https://github.com/rust-embedded/embedded-hal) traits.
//!
//! ## Supported devices
//! Tested with the following sensor(s):
//! - [LTR-303ALS-01](https://www.mouser.com/datasheet/2/239/Lite-On_LTR-303ALS-01_DS_ver%201.1-1175269.pdf)
//!
//! ## Usage
//! ### Setup
//!
//! Instantiate a new driver instance using a [blocking I²C HAL
//! implementation](https://docs.rs/embedded-hal/0.2.*/embedded_hal/blocking/i2c/index.html).
//! For example, using `linux-embedded-hal` and an LTR303 sensor:
//! ```no_run
//! use linux_embedded_hal::{I2cdev};
//! use ltr303;
//!
//! let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! let mut sensor = ltr303::LTR303::init(dev);
//! let config = ltr303::LTR303Config::default();
//! ```
//!
//! ### Device Info
//!
//! Then, you can query information about the sensor:
//!
//! ```no_run
//! # use linux_embedded_hal::{I2cdev};
//! # use ltr303;
//! # let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! # let mut sensor = ltr303::LTR303::init(dev);
//! let part_id = sensor.get_part_id().unwrap();
//! let mfc_id = sensor.get_mfc_id().unwrap();
//! ```
//!
//! ### Measurements
//!
//! For measuring the illuminance, simply start a measurement and wait for a result:
//! ```no_run
//! use linux_embedded_hal::{Delay, I2cdev};
//! # use ltr303;
//! # let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! # let mut sensor = ltr303::LTR303::init(dev);
//! let config = ltr303::LTR303Config::default();
//! sensor.start_measurement(&config).unwrap();
//! while sensor.data_ready().unwrap() != true {}
//!
//! let lux_val = sensor.get_lux_data().unwrap();
//! println!("LTR303 current lux phys: {}", lux_val.lux_phys);
//! ```
//!
#![no_std]
#[macro_use]
extern crate num_derive;
use embedded_hal::i2c;
use paste::paste;
use types::LuxData;
use types::RawData;

mod fields;
mod macros;
mod registers;
mod types;
pub use crate::fields::*;
pub use crate::registers::*;
pub use crate::types::Error;

const LTR303_BASE_ADDRESS: u8 = 0x29;

create_struct_with! (LTR303Config, {mode: Mode, gain: Gain, integration_time: IntegrationTime, measurement_rate: MeasurementRate, int_thrsh_up: u16, int_thrsh_down: u16});

impl Default for LTR303Config {
    fn default() -> Self {
        LTR303Config {
            mode: crate::Mode::STANDBY,
            gain: crate::Gain::Gain1x,
            integration_time: crate::IntegrationTime::Ms100,
            measurement_rate: crate::MeasurementRate::Ms500,
            int_thrsh_up: 0x0000,
            int_thrsh_down: 0xFFFF,
        }
    }
}

pub struct LTR303<I2C> {
    i2c: I2C,
    gain: Gain,
    integration_time: IntegrationTime,
}

impl<I2C, E> LTR303<I2C>
where
    I2C: i2c::I2c<Error = E>,
{
    /// Initializes the LTR303 driver while consuming the i2c bus
    pub fn init(i2c: I2C) -> Self {
        LTR303 {
            i2c,
            gain: Gain::Gain1x,
            integration_time: IntegrationTime::Ms100,
        }
    }

    /// Get the manufacturer ID stored inside LTR303. This ID should be 0x05.
    pub fn get_mfc_id(&mut self) -> Result<u8, Error<E>> {
        self.read_register(Register::MANUFAC_ID)
    }

    /// Get the part ID stored inside LTR303. This ID should be 0xA0.
    pub fn get_part_id(&mut self) -> Result<u8, Error<E>> {
        self.read_register(Register::PART_ID)
    }

    /// Destroy driver instance, return I²C bus instance.
    pub fn destroy(self) -> I2C {
        self.i2c
    }

    // Starts a single-shot measurement!
    pub fn start_measurement(&mut self, config: &LTR303Config) -> Result<(), Error<E>> {
        // Save the current gain and integration times => To be used when translating raw to phys
        self.gain = config.gain;
        self.integration_time = config.integration_time;

        // Configure gain, set active mode
        let control_reg = ControlRegister::default()
            .with_gain(config.gain)
            .with_mode(Mode::ACTIVE);

        // Then configure the integration time & measurement rate
        let meas_rate_reg = MeasRateRegister::default()
            .with_integration_time(config.integration_time)
            .with_measurement_rate(config.measurement_rate);

        self.write_register(Register::ALS_MEAS_RATE, meas_rate_reg.value())?;

        // Then, configure the thresholds for the interrupt!
        self.write_register(
            Register::ALS_THRES_LOW_0,
            config.int_thrsh_down.to_be_bytes()[1],
        )?;
        self.write_register(
            Register::ALS_THRES_LOW_1,
            config.int_thrsh_down.to_be_bytes()[0],
        )?;
        self.write_register(
            Register::ALS_THRES_UP_0,
            config.int_thrsh_up.to_be_bytes()[1],
        )?;
        self.write_register(
            Register::ALS_THRES_UP_1,
            config.int_thrsh_up.to_be_bytes()[0],
        )?;

        // Then enable interrupts
        // TODO: Implement similar to the other registers, with bits and InterruptReg.set_high(Flags::ISREnable)
        self.write_register(Register::INTERRUPT, 0b00000010)?;

        // Then we start a measurement
        self.write_register(Register::ALS_CONTR, control_reg.value())?;

        Ok(())
    }

    /// Returns the contents of the ALS_STATUS register.
    pub fn get_status(&mut self) -> Result<StatusRegister, Error<E>> {
        let data = self.read_register(Register::ALS_STATUS)?;

        let status_reg: StatusRegister = data.into();
        Ok(status_reg)
    }

    /// Check if new sensor data is ready.
    pub fn data_ready(&mut self) -> Result<bool, Error<E>> {
        let status = self.get_status()?;
        Ok(status.data_status.value == DataStatus::New)
    }

    /// Reads the Ambient Light Level from LTR303's registers and returns the physical
    /// lux value.
    pub fn get_lux_data(&mut self) -> Result<LuxData, Error<E>> {
        let raw_data = self.get_raw_data()?;

        Ok(LuxData {
            lux_raw: raw_data,
            lux_phys: raw_to_lux(
                raw_data.ch1_raw,
                raw_data.ch0_raw,
                self.gain,
                self.integration_time,
            ),
        })
    }

    /// Puts the sensor in a low-power Standby mode where it consumes 5uA of current.
    pub fn standby(&mut self) -> Result<(), Error<E>> {
        self.write_register(
            Register::ALS_CONTR,
            ControlRegister::default().with_mode(Mode::STANDBY).value(),
        )?;
        Ok(())
    }
}

impl<I2C, E> LTR303<I2C>
where
    I2C: i2c::I2c<Error = E>,
{
    fn write_register(&mut self, register: u8, data: u8) -> Result<(), Error<E>> {
        self.i2c
            .write(LTR303_BASE_ADDRESS, &[register, data])
            .map_err(Error::I2C)
            .and(Ok(()))
    }

    fn read_register(&mut self, register: u8) -> Result<u8, Error<E>> {
        let mut data: [u8; 1] = [0];
        self.i2c
            .write_read(LTR303_BASE_ADDRESS, &[register], &mut data)
            .map_err(Error::I2C)
            .and(Ok(data[0]))
    }

    fn get_raw_data(&mut self) -> Result<RawData, Error<E>> {
        // Read raw illuminance data
        // Use a single transaction to ensure that the data is from the same measurement
        // (see pg. 17 of datasheet)
        let mut data: [u8; 4] = [0; 4];
        self.i2c
            .write_read(LTR303_BASE_ADDRESS, &[Register::ALS_DATA_CH1_0], &mut data)
            .map_err(Error::I2C)?;
        let ch1_raw = u16::from_le_bytes([data[0], data[1]]);
        let ch0_raw = u16::from_le_bytes([data[2], data[3]]);

        Ok(RawData { ch0_raw, ch1_raw })
    }
}

fn raw_to_lux(ch1_data: u16, ch0_data: u16, gain: Gain, itime: IntegrationTime) -> f32 {
    let ratio = ch1_data as f32 / (ch0_data as f32 + ch1_data as f32);
    let als_gain: f32 = gain.into();
    let int_time: f32 = itime.into();

    if ratio < 0.45 {
        ((1.7743 * f32::from(ch0_data)) + (1.1059 * f32::from(ch1_data))) / als_gain / int_time
    } else if (0.45..0.64).contains(&ratio) {
        ((4.2785 * f32::from(ch0_data)) - (1.9548 * f32::from(ch1_data))) / als_gain / int_time
    } else if (0.64..0.85).contains(&ratio) {
        ((0.5926 * f32::from(ch0_data)) - (0.1185 * f32::from(ch1_data))) / als_gain / int_time
    } else {
        0.0
    }
}

#[cfg(test)]
mod tests {
    // this code lives inside a `tests` module

    extern crate std;
    use crate::{DataStatus, DataValidity, Gain, IntStatus};

    use super::*;

    use embedded_hal_mock::eh1::i2c;
    const LTR303_ADDR: u8 = 0x29;

    #[test]
    fn manufacturer_info() {
        let expectations = [i2c::Transaction::write_read(
            LTR303_ADDR,
            std::vec![Register::MANUFAC_ID],
            std::vec![0x05],
        )];
        let mock = i2c::Mock::new(&expectations);

        let mut ltr303 = LTR303::init(mock);
        let mfc = ltr303.get_mfc_id().unwrap();
        assert_eq!(0x05, mfc);

        let mut mock = ltr303.destroy();
        mock.done(); // verify expectations
    }

    #[test]
    fn part_id() {
        let expectations = [i2c::Transaction::write_read(
            LTR303_ADDR,
            std::vec![Register::PART_ID],
            std::vec![0xA0],
        )];
        let mock = i2c::Mock::new(&expectations);

        let mut ltr303 = LTR303::init(mock);
        let part_id = ltr303.get_part_id().unwrap();
        assert_eq!(0xA0, part_id);

        let mut mock = ltr303.destroy();
        mock.done(); // verify expectations
    }

    #[test]
    fn sensor_status() {
        let expectations = [i2c::Transaction::write_read(
            LTR303_ADDR,
            std::vec![Register::ALS_STATUS],
            std::vec![0b11111010],
        )];
        let mock = i2c::Mock::new(&expectations);

        let mut ltr303 = LTR303::init(mock);
        let sensor_status = ltr303.get_status().unwrap();

        assert_eq!(sensor_status.data_status.value, DataStatus::Old);
        assert_eq!(sensor_status.data_valid.value, DataValidity::DataInvalid);
        assert_eq!(sensor_status.gain.value, Gain::Gain96x);
        assert_eq!(sensor_status.int_status.value, IntStatus::Active);

        assert_eq!(sensor_status.value(), 0b11111000);

        let mut mock = ltr303.destroy();
        mock.done(); // verify expectations
    }

    #[test]
    fn start_measurement() {
        let expectations = [
            i2c::Transaction::write(
                LTR303_ADDR,
                std::vec![Register::ALS_MEAS_RATE, 0b00010101], // 200ms integration time & 2000ms meas rate
            ),
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_THRES_LOW_0, 0xFF]),
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_THRES_LOW_1, 0xFF]),
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_THRES_UP_0, 0x00]),
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_THRES_UP_1, 0x00]),
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::INTERRUPT, 0b00000010]),
            i2c::Transaction::write(
                LTR303_ADDR,
                std::vec![Register::ALS_CONTR, 0b00000001], // Active mode, default otherwise
            ),
        ];

        let mock = i2c::Mock::new(&expectations);

        let config = LTR303Config {
            integration_time: crate::IntegrationTime::Ms200,
            measurement_rate: crate::MeasurementRate::Ms2000,
            ..Default::default()
        };

        let mut ltr303 = LTR303::init(mock);

        ltr303.start_measurement(&config).unwrap();

        let mut mock = ltr303.destroy();
        mock.done(); // verify expectations
    }

    // Do a complete measurement from start to finish and test that we get the proper data
    #[test]
    fn single_shot_measurement() {
        // Start a Gain4x single measurement with integration time 100ms and measurement rate 2000ms,
        // then after we got a result, put the sensor to sleep.
        let expectations = [
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_MEAS_RATE, 0b0001_1101]), // set times
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_THRES_LOW_0, 0xFF]), // set thresholds
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_THRES_LOW_1, 0xFF]), // set thresholds
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_THRES_UP_0, 0x00]), // set thresholds
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_THRES_UP_1, 0x00]), // set thresholds
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::INTERRUPT, 0b00000010]), // enable interrupts
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_CONTR, 0b0000_1001]), // wake-up sensor. start
            i2c::Transaction::write_read(
                LTR303_ADDR,
                std::vec![Register::ALS_STATUS],
                std::vec![0b1010_0000],
            ), // current status: still measuring
            i2c::Transaction::write_read(
                LTR303_ADDR,
                std::vec![Register::ALS_STATUS],
                std::vec![0b0010_0100],
            ), // current status: new data available
            i2c::Transaction::write_read(
                LTR303_ADDR,
                std::vec![Register::ALS_DATA_CH1_0],
                std::vec![0xAD, 0xDE, 0xEF, 0xBE],
            ), // Reading channel data
            i2c::Transaction::write(LTR303_ADDR, std::vec![Register::ALS_CONTR, 0b0000_0000]), // put sensor to sleep
        ];
        let mock = i2c::Mock::new(&expectations);

        // Created expected bus communication. Below is the expected developer workflow:
        let config = crate::LTR303Config::default()
            .with_integration_time(crate::IntegrationTime::Ms400)
            .with_measurement_rate(crate::MeasurementRate::Ms2000)
            .with_gain(crate::Gain::Gain4x);

        let mut ltr303 = LTR303::init(mock);
        ltr303.start_measurement(&config).unwrap();

        while ltr303.get_status().unwrap().data_status.value != DataStatus::New {}

        let lux_data = ltr303.get_lux_data().unwrap();
        ltr303.standby().unwrap();

        assert_eq!(lux_data.lux_raw.ch1_raw, 0xDEAD);
        assert_eq!(lux_data.lux_raw.ch0_raw, 0xBEEF);

        let mut mock = ltr303.destroy();
        mock.done(); // verify expectations
    }

    #[cfg(test)]
    mod unit_tests {
        use crate::{
            raw_to_lux, ControlRegister, Field, Gain, IntegrationTime, MeasRateRegister,
            MeasurementRate, Mode, ResetStatus,
        };

        #[test]
        fn calculate_lux_from_raw() {
            let ch0_data: u16 = 0x0000;
            let ch1_data: u16 = 0xFFFF;

            // First, test that CH1 >> CH0 returns 0 lux
            let ltr303_config = crate::LTR303Config::default();

            let lux = raw_to_lux(
                ch1_data,
                ch0_data,
                ltr303_config.gain,
                ltr303_config.integration_time,
            );

            assert_eq!(lux, 0.0);

            // Then a normal random value testing ratio >= 0.45 && ratio < 0.64
            let ch0_data: u16 = 0x1000;
            let ch1_data: u16 = 0x1000;
            let lux = raw_to_lux(
                ch1_data,
                ch0_data,
                ltr303_config.gain,
                ltr303_config.integration_time,
            );

            assert_eq!(lux, 9517.875);
        }

        #[test]
        fn test_registers() {
            // Test that the register API works as expected!
            let control_reg = ControlRegister::default()
                .with_mode(Mode::STANDBY)
                .with_gain(Gain::Gain8x);

            assert_eq!(control_reg.gain.value, Gain::Gain8x);
            assert_eq!(control_reg.value(), 0b0000_1100);

            let measrate_reg = MeasRateRegister::default()
                .with_integration_time(IntegrationTime::Ms200)
                .with_measurement_rate(MeasurementRate::Ms2000);

            assert_eq!(measrate_reg.integration_time.value, IntegrationTime::Ms200);
            assert_eq!(measrate_reg.value(), 0b0001_0101);
        }

        #[test]
        fn test_register_from_u8() {
            // Tests that we can properly transform a u8 value to a register with fields!
            let contr_reg_val: u8 = 0b0000_1011;
            let control_reg: ControlRegister = contr_reg_val.into();

            assert_eq!(control_reg.gain.value, Gain::Gain4x);
            assert_eq!(control_reg.sw_reset.value, ResetStatus::Resetting);
            assert_eq!(control_reg.mode.value, Mode::ACTIVE);
        }

        #[test]
        fn test_fields() {
            // Field one should be 0b00010110
            let field1 = Field {
                start_index: 1,
                width: 4,
                value: 0x0Bu8,
            };
            assert_eq!(field1.bits(), 0b0001_0110)
        }
    }
}