Skip to main content

capsules_extra/
tsl2561.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! SyscallDriver for the Taos TSL2561 light sensor.
6//!
7//! <http://www.digikey.com/product-detail/en/ams-taos-usa-inc/TSL2561FN/TSL2561-FNCT-ND/3095298>
8//!
9//! > The TSL2560 and TSL2561 are light-to-digital converters that transform
10//! > light intensity to a digital signal output capable of direct I2C
11//! > interface. Each device combines one broadband photodiode (visible plus
12//! > infrared) and one infrared-responding photodiode on a single CMOS
13//! > integrated circuit capable of providing a near-photopic response over an
14//! > effective 20-bit dynamic range (16-bit resolution). Two integrating ADCs
15//! > convert the photodiode currents to a digital output that represents the
16//! > irradiance measured on each channel. This digital output can be input to a
17//! > microprocessor where illuminance (ambient light level) in lux is derived
18//! > using an empirical formula to approximate the human eye response.
19
20use core::cell::Cell;
21
22use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
23use kernel::hil::gpio;
24use kernel::hil::i2c;
25use kernel::syscall::{CommandReturn, SyscallDriver};
26use kernel::utilities::cells::{OptionalCell, TakeCell};
27use kernel::{ErrorCode, ProcessId};
28
29/// Syscall driver number.
30use capsules_core::driver;
31pub const DRIVER_NUM: usize = driver::NUM::Tsl2561 as usize;
32
33// Buffer to use for I2C messages
34pub const BUFFER_LENGTH: usize = 4;
35
36/// Command register defines
37const COMMAND_REG: u8 = 0x80;
38const WORD_PROTOCOL: u8 = 0x20;
39
40/// Control_Reg defines
41const POWER_ON: u8 = 0x03;
42const POWER_OFF: u8 = 0x00;
43
44/// Timing_Reg defines
45const INTEGRATE_TIME_101_MS: u8 = 0x01;
46const LOW_GAIN_MODE: u8 = 0x00;
47
48// Interrupt_Control_Reg defines
49const INTERRUPT_CONTROL_LEVEL: u8 = 0x10;
50const INTERRUPT_ON_ADC_DONE: u8 = 0x0;
51
52// ADC counts to Lux value conversion copied from TSL2561 manual
53// −−−−------------------------------
54// Value scaling factors
55// −−−−−−−−−−−−−−−-------------------
56const LUX_SCALE: u16 = 14; // scale by 2^14
57const RATIO_SCALE: u16 = 9; // scale ratio by 2^9
58
59// −−−−−−−−−−−−−−−−−−−−−−−-----------
60// Integration time scaling factors
61// −−−−−−−−−−−−−−−−−−−−−−−−−−−−------
62const CH_SCALE: u16 = 10; // scale channel values by 2^10
63#[allow(dead_code)]
64const CHSCALE_TINT0: u16 = 0x7517; // 322/11 * 2^CH_SCALE
65const CHSCALE_TINT1: u16 = 0x0fe7; // 322/81 * 2^CH_SCALE
66
67// −−−−−−−−−−−−−−−−−−−−−−−−−−−−------
68// T, FN, and CL Package coefficients
69// −−−−−−−−−−−−−−−−−−−−−−−−−−−−------
70// For Ch1/Ch0=0.00 to 0.50
71// Lux/Ch0=0.0304−0.062*((Ch1/Ch0)^1.4)
72// piecewise approximation
73// For Ch1/Ch0=0.00 to 0.125:
74// Lux/Ch0=0.0304−0.0272*(Ch1/Ch0)
75//
76// For Ch1/Ch0=0.125 to 0.250:
77// Lux/Ch0=0.0325−0.0440*(Ch1/Ch0)
78//
79// For Ch1/Ch0=0.250 to 0.375:
80// Lux/Ch0=0.0351−0.0544*(Ch1/Ch0)
81//
82// For Ch1/Ch0=0.375 to 0.50:
83// Lux/Ch0=0.0381−0.0624*(Ch1/Ch0)
84//
85// For Ch1/Ch0=0.50 to 0.61:
86// Lux/Ch0=0.0224−0.031*(Ch1/Ch0)
87//
88// For Ch1/Ch0=0.61 to 0.80:
89// Lux/Ch0=0.0128−0.0153*(Ch1/Ch0)
90//
91// For Ch1/Ch0=0.80 to 1.30:
92// Lux/Ch0=0.00146−0.00112*(Ch1/Ch0)
93//
94// For Ch1/Ch0>1.3:
95// Lux/Ch0=0
96// −−−−−−−−−−−−−−−−−−−−−−−−−−−−------
97const K1T: usize = 0x0040; // 0.125 * 2^RATIO_SCALE
98const B1T: usize = 0x01f2; // 0.0304 * 2^LUX_SCALE
99const M1T: usize = 0x01be; // 0.0272 * 2^LUX_SCALE
100const K2T: usize = 0x0080; // 0.250 * 2^RATIO_SCALE
101const B2T: usize = 0x0214; // 0.0325 * 2^LUX_SCALE
102const M2T: usize = 0x02d1; // 0.0440 * 2^LUX_SCALE
103const K3T: usize = 0x00c0; // 0.375 * 2^RATIO_SCALE
104const B3T: usize = 0x023f; // 0.0351 * 2^LUX_SCALE
105const M3T: usize = 0x037b; // 0.0544 * 2^LUX_SCALE
106const K4T: usize = 0x0100; // 0.50 * 2^RATIO_SCALE
107const B4T: usize = 0x0270; // 0.0381 * 2^LUX_SCALE
108const M4T: usize = 0x03fe; // 0.0624 * 2^LUX_SCALE
109const K5T: usize = 0x0138; // 0.61 * 2^RATIO_SCALE
110const B5T: usize = 0x016f; // 0.0224 * 2^LUX_SCALE
111const M5T: usize = 0x01fc; // 0.0310 * 2^LUX_SCALE
112const K6T: usize = 0x019a; // 0.80 * 2^RATIO_SCALE
113const B6T: usize = 0x00d2; // 0.0128 * 2^LUX_SCALE
114const M6T: usize = 0x00fb; // 0.0153 * 2^LUX_SCALE
115const K7T: usize = 0x029a; // 1.3 * 2^RATIO_SCALE
116const B7T: usize = 0x0018; // 0.00146 * 2^LUX_SCALE
117const M7T: usize = 0x0012; // 0.00112 * 2^LUX_SCALE
118const K8T: usize = 0x029a; // 1.3 * 2^RATIO_SCALE
119const B8T: usize = 0x0000; // 0.000 * 2^LUX_SCALE
120const M8T: usize = 0x0000; // 0.000 * 2^LUX_SCALE
121
122// −−−−−−−−−−−−−−−−−−−−−−−−−−−−------
123// CS package coefficients
124// −−−−−−−−−−−−−−−−−−−−−−−−−−−−------
125// For 0 <= Ch1/Ch0 <= 0.52
126// Lux/Ch0 = 0.0315−0.0593*((Ch1/Ch0)^1.4)
127// piecewise approximation
128// For 0 <= Ch1/Ch0 <= 0.13
129// Lux/Ch0 = 0.0315−0.0262*(Ch1/Ch0)
130// For 0.13 <= Ch1/Ch0 <= 0.26
131// Lux/Ch0 = 0.0337−0.0430*(Ch1/Ch0)
132// For 0.26 <= Ch1/Ch0 <= 0.39
133// Lux/Ch0 = 0.0363−0.0529*(Ch1/Ch0)
134// For 0.39 <= Ch1/Ch0 <= 0.52
135// Lux/Ch0 = 0.0392−0.0605*(Ch1/Ch0)
136// For 0.52 < Ch1/Ch0 <= 0.65
137// Lux/Ch0 = 0.0229−0.0291*(Ch1/Ch0)
138// For 0.65 < Ch1/Ch0 <= 0.80
139// Lux/Ch0 = 0.00157−0.00180*(Ch1/Ch0)
140// For 0.80 < Ch1/Ch0 <= 1.30
141// Lux/Ch0 = 0.00338−0.00260*(Ch1/Ch0)
142// For Ch1/Ch0 > 1.30
143// Lux = 0
144// −−−−−−−−−−−−−−−−−−−−−−−−−−−−------
145// const K1C: usize = 0x0043; // 0.130 * 2^RATIO_SCALE
146// const B1C: usize = 0x0204; // 0.0315 * 2^LUX_SCALE
147// const M1C: usize = 0x01ad; // 0.0262 * 2^LUX_SCALE
148// const K2C: usize = 0x0085; // 0.260 * 2^RATIO_SCALE
149// const B2C: usize = 0x0228; // 0.0337 * 2^LUX_SCALE
150// const M2C: usize = 0x02c1; // 0.0430 * 2^LUX_SCALE
151// const K3C: usize = 0x00c8; // 0.390 * 2^RATIO_SCALE
152// const B3C: usize = 0x0253; // 0.0363 * 2^LUX_SCALE
153// const M3C: usize = 0x0363; // 0.0529 * 2^LUX_SCALE
154// const K4C: usize = 0x010a; // 0.520 * 2^RATIO_SCALE
155// const B4C: usize = 0x0282; // 0.0392 * 2^LUX_SCALE
156// const M4C: usize = 0x03df; // 0.0605 * 2^LUX_SCALE
157// const K5C: usize = 0x014d; // 0.65 * 2^RATIO_SCALE
158// const B5C: usize = 0x0177; // 0.0229 * 2^LUX_SCALE
159// const M5C: usize = 0x01dd; // 0.0291 * 2^LUX_SCALE
160// const K6C: usize = 0x019a; // 0.80 * 2^RATIO_SCALE
161// const B6C: usize = 0x0101; // 0.0157 * 2^LUX_SCALE
162// const M6C: usize = 0x0127; // 0.0180 * 2^LUX_SCALE
163// const K7C: usize = 0x029a; // 1.3 * 2^RATIO_SCALE
164// const B7C: usize = 0x0037; // 0.00338 * 2^LUX_SCALE
165// const M7C: usize = 0x002b; // 0.00260 * 2^LUX_SCALE
166// const K8C: usize = 0x029a; // 1.3 * 2^RATIO_SCALE
167// const B8C: usize = 0x0000; // 0.000 * 2^LUX_SCALE
168// const M8C: usize = 0x0000; // 0.000 * 2^LUX_SCALE
169
170#[allow(dead_code)]
171enum Registers {
172    Control = 0x00,
173    Timing = 0x01,
174    ThresholdLowLow = 0x02,
175    ThresholdLowHigh = 0x03,
176    ThresholdHighLow = 0x04,
177    ThresholdHighHigh = 0x05,
178    Interrupt = 0x06,
179    Id = 0x0a,
180    Data0Low = 0x0c,
181    Data0High = 0x0d,
182    Data1Low = 0x0e,
183    Data1High = 0x0f,
184}
185
186#[derive(Clone, Copy, PartialEq)]
187enum State {
188    Idle,
189
190    /// Read the Id register.
191    SelectId,
192    ReadingId,
193
194    /// Process of taking a light measurement.
195    TakeMeasurementTurnOn,
196    TakeMeasurementConfigMeasurement,
197    TakeMeasurementReset1,
198    TakeMeasurementReset2,
199
200    /// Read the ADC registers.
201    ReadMeasurement1,
202    ReadMeasurement2,
203    ReadMeasurement3,
204    /// Calculate light and call the callback with the value.
205    GotMeasurement,
206
207    /// Disable I2C and release buffer
208    Done,
209}
210
211#[derive(Default)]
212pub struct App {}
213
214pub struct TSL2561<'a, I: i2c::I2CDevice<'a>> {
215    i2c: &'a I,
216    interrupt_pin: &'a dyn gpio::InterruptPin<'a>,
217    state: Cell<State>,
218    buffer: TakeCell<'static, [u8]>,
219    apps: Grant<App, UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
220    owning_process: OptionalCell<ProcessId>,
221}
222
223impl<'a, I: i2c::I2CDevice<'a>> TSL2561<'a, I> {
224    pub fn new(
225        i2c: &'a I,
226        interrupt_pin: &'a dyn gpio::InterruptPin<'a>,
227        buffer: &'static mut [u8],
228        apps: Grant<App, UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
229    ) -> Self {
230        // setup and return struct
231        Self {
232            i2c,
233            interrupt_pin,
234            state: Cell::new(State::Idle),
235            buffer: TakeCell::new(buffer),
236            apps,
237            owning_process: OptionalCell::empty(),
238        }
239    }
240
241    pub fn read_id(&self) {
242        self.buffer.take().map(|buffer| {
243            // turn on i2c to send commands
244            self.i2c.enable();
245
246            buffer[0] = Registers::Id as u8 | COMMAND_REG;
247            // buffer[0] = Registers::Id as u8;
248            // TODO verify errors
249            let _ = self.i2c.write(buffer, 1);
250            self.state.set(State::SelectId);
251        });
252    }
253
254    pub fn take_measurement(&self) {
255        // Need pull up on interrupt pin
256        self.interrupt_pin.make_input();
257        self.interrupt_pin
258            .enable_interrupts(gpio::InterruptEdge::FallingEdge);
259
260        self.buffer.take().map(|buf| {
261            // Turn on i2c to send commands
262            self.i2c.enable();
263
264            buf[0] = Registers::Control as u8 | COMMAND_REG;
265            buf[1] = POWER_ON;
266            // TODO verify errors
267            let _ = self.i2c.write(buf, 2);
268            self.state.set(State::TakeMeasurementTurnOn);
269        });
270    }
271
272    fn calculate_lux(&self, chan0: u16, chan1: u16) -> usize {
273        // First, scale the channel values depending on the gain and integration
274        // time. 16X, 402mS is nominal. Scale if integration time is NOT 402 msec.
275        // let mut ch_scale = CHSCALE_TINT0 as usize; // 13.7ms
276        let mut ch_scale = CHSCALE_TINT1 as usize; // 101ms
277        // let mut ch_scale: usize = 1 << CH_SCALE; // Default
278
279        // Scale if gain is NOT 16X
280        ch_scale <<= 4; // scale 1X to 16X
281
282        // scale the channel values
283        let channel0 = (chan0 as usize * ch_scale) >> CH_SCALE;
284        let channel1 = (chan1 as usize * ch_scale) >> CH_SCALE;
285
286        // Find the ratio of the channel values (Channel1/Channel0).
287        // Protect against divide by zero.
288        let ratio1 = (channel1 << (RATIO_SCALE + 1))
289            .checked_div(channel0)
290            .unwrap_or(0);
291
292        // round the ratio value
293        let ratio = (ratio1 + 1) >> 1;
294
295        // is ratio <= eachBreak ?
296        let mut b = 0;
297        let mut m = 0;
298        // T, FN, and CL package
299        if ratio <= K1T {
300            b = B1T;
301            m = M1T;
302        } else if ratio <= K2T {
303            b = B2T;
304            m = M2T;
305        } else if ratio <= K3T {
306            b = B3T;
307            m = M3T;
308        } else if ratio <= K4T {
309            b = B4T;
310            m = M4T;
311        } else if ratio <= K5T {
312            b = B5T;
313            m = M5T;
314        } else if ratio <= K6T {
315            b = B6T;
316            m = M6T;
317        } else if ratio <= K7T {
318            b = B7T;
319            m = M7T;
320        } else if ratio > K8T {
321            b = B8T;
322            m = M8T;
323        }
324        // CS package
325        // if ratio <= K1C {
326        //     b=B1C; m=M1C;
327        // } else if ratio <= K2C {
328        //     b=B2C; m=M2C;
329        // } else if ratio <= K3C {
330        //     b=B3C; m=M3C;
331        // } else if ratio <= K4C {
332        //     b=B4C; m=M4C;
333        // } else if ratio <= K5C {
334        //     b=B5C; m=M5C;
335        // } else if ratio <= K6C {
336        //     b=B6C; m=M6C;
337        // } else if ratio <= K7C {
338        //     b=B7C; m=M7C;
339        // } else if ratio > K8C {
340        //     b=B8C; m=M8C;
341        // }
342
343        // Calculate actual lux value
344        let mut val = ((channel0 * b) as isize) - ((channel1 * m) as isize);
345
346        // Do not allow negative lux value
347        if val < 0 {
348            val = 0;
349        }
350
351        // round lsb (2^(LUX_SCALE−1))
352        // val += (1 << (LUX_SCALE−1));
353        val += 1 << (LUX_SCALE - 1);
354
355        // strip off fractional portion and return lux
356        let lux = val >> LUX_SCALE;
357
358        lux as usize
359    }
360}
361
362impl<'a, I: i2c::I2CDevice<'a>> i2c::I2CClient for TSL2561<'a, I> {
363    fn command_complete(&self, buffer: &'static mut [u8], _status: Result<(), i2c::Error>) {
364        match self.state.get() {
365            State::SelectId => {
366                // TODO verify errors
367                let _ = self.i2c.read(buffer, 1);
368                self.state.set(State::ReadingId);
369            }
370            State::ReadingId => {
371                self.buffer.replace(buffer);
372                self.i2c.disable();
373                self.state.set(State::Idle);
374            }
375            State::TakeMeasurementTurnOn => {
376                buffer[0] = Registers::Timing as u8 | COMMAND_REG;
377                buffer[1] = INTEGRATE_TIME_101_MS | LOW_GAIN_MODE;
378                // TODO verify errors
379                let _ = self.i2c.write(buffer, 2);
380                self.state.set(State::TakeMeasurementConfigMeasurement);
381            }
382            State::TakeMeasurementConfigMeasurement => {
383                buffer[0] = Registers::Interrupt as u8 | COMMAND_REG;
384                buffer[1] = INTERRUPT_CONTROL_LEVEL | INTERRUPT_ON_ADC_DONE;
385                // TODO verify errors
386                let _ = self.i2c.write(buffer, 2);
387                self.state.set(State::TakeMeasurementReset1);
388            }
389            State::TakeMeasurementReset1 => {
390                buffer[0] = Registers::Control as u8 | COMMAND_REG;
391                buffer[1] = POWER_OFF;
392                // TODO verify errors
393                let _ = self.i2c.write(buffer, 2);
394                self.state.set(State::TakeMeasurementReset2);
395            }
396            State::TakeMeasurementReset2 => {
397                buffer[0] = Registers::Control as u8 | COMMAND_REG;
398                buffer[1] = POWER_ON;
399                // TODO verify errors
400                let _ = self.i2c.write(buffer, 2);
401                self.state.set(State::Done);
402            }
403            State::ReadMeasurement1 => {
404                // TODO verify errors
405                let _ = self.i2c.read(buffer, 2);
406                self.state.set(State::ReadMeasurement2);
407            }
408            State::ReadMeasurement2 => {
409                // Store the previous readings in the buffer where they
410                // won't get overwritten.
411                buffer[2] = buffer[0];
412                buffer[3] = buffer[1];
413                buffer[0] = Registers::Data0Low as u8 | COMMAND_REG | WORD_PROTOCOL;
414                // TODO verify errors
415                let _ = self.i2c.write(buffer, 2);
416                self.state.set(State::ReadMeasurement3);
417            }
418            State::ReadMeasurement3 => {
419                // TODO verify errors
420                let _ = self.i2c.read(buffer, 2);
421                self.state.set(State::GotMeasurement);
422            }
423            State::GotMeasurement => {
424                let chan0 = ((buffer[1] as u16) << 8) | (buffer[0] as u16);
425                let chan1 = ((buffer[3] as u16) << 8) | (buffer[2] as u16);
426
427                let lux = self.calculate_lux(chan0, chan1);
428
429                self.owning_process.map(|pid| {
430                    let _ = self.apps.enter(pid, |_, upcalls| {
431                        let _ = upcalls.schedule_upcall(0, (0, lux, 0));
432                    });
433                });
434
435                buffer[0] = Registers::Control as u8 | COMMAND_REG;
436                buffer[1] = POWER_OFF;
437                // TODO verify errors
438                let _ = self.i2c.write(buffer, 2);
439                self.interrupt_pin.disable_interrupts();
440                self.state.set(State::Done);
441            }
442            State::Done => {
443                self.buffer.replace(buffer);
444                self.i2c.disable();
445                self.state.set(State::Idle);
446            }
447            _ => {}
448        }
449    }
450}
451
452impl<'a, I: i2c::I2CDevice<'a>> gpio::Client for TSL2561<'a, I> {
453    fn fired(&self) {
454        self.buffer.take().map(|buffer| {
455            // turn on i2c to send commands
456            self.i2c.enable();
457
458            // Read the first of the ADC registers.
459            buffer[0] = Registers::Data1Low as u8 | COMMAND_REG | WORD_PROTOCOL;
460            // TODO verify errors
461            let _ = self.i2c.write(buffer, 1);
462            self.state.set(State::ReadMeasurement1);
463        });
464    }
465}
466
467impl<'a, I: i2c::I2CDevice<'a>> SyscallDriver for TSL2561<'a, I> {
468    fn command(
469        &self,
470        command_num: usize,
471        _: usize,
472        _: usize,
473        process_id: ProcessId,
474    ) -> CommandReturn {
475        if command_num == 0 {
476            // Handle this first as it should be returned
477            // unconditionally
478            return CommandReturn::success();
479        }
480        // Check if this non-virtualized driver is already in use by
481        // some (alive) process
482        let match_or_empty_or_nonexistant = self.owning_process.map_or(true, |current_process| {
483            self.apps
484                .enter(current_process, |_, _| current_process == process_id)
485                .unwrap_or(true)
486        });
487        if match_or_empty_or_nonexistant {
488            self.owning_process.set(process_id);
489        } else {
490            return CommandReturn::failure(ErrorCode::NOMEM);
491        }
492        match command_num {
493            // Take a measurement
494            1 => {
495                self.take_measurement();
496                CommandReturn::success()
497            }
498            // default
499            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
500        }
501    }
502
503    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
504        self.apps.enter(processid, |_, _| {})
505    }
506}