Adafruit_TSL2591.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /**************************************************************************/
  2. /*!
  3. @file Adafruit_TSL2591.cpp
  4. @author KT0WN (adafruit.com)
  5. This is a library for the Adafruit TSL2591 breakout board
  6. This library works with the Adafruit TSL2591 breakout
  7. ----> https://www.adafruit.com/products/1980
  8. Check out the links above for our tutorials and wiring diagrams
  9. These chips use I2C to communicate
  10. Adafruit invests time and resources providing this open source code,
  11. please support Adafruit and open-source hardware by purchasing
  12. products from Adafruit!
  13. @section LICENSE
  14. Software License Agreement (BSD License)
  15. Copyright (c) 2014 Adafruit Industries
  16. All rights reserved.
  17. Redistribution and use in source and binary forms, with or without
  18. modification, are permitted provided that the following conditions are met:
  19. 1. Redistributions of source code must retain the above copyright
  20. notice, this list of conditions and the following disclaimer.
  21. 2. Redistributions in binary form must reproduce the above copyright
  22. notice, this list of conditions and the following disclaimer in the
  23. documentation and/or other materials provided with the distribution.
  24. 3. Neither the name of the copyright holders nor the
  25. names of its contributors may be used to endorse or promote products
  26. derived from this software without specific prior written permission.
  27. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  28. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  29. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  30. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
  31. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  32. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  33. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  34. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  35. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  36. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  37. */
  38. /**************************************************************************/
  39. #include "Adafruit_TSL2591.h"
  40. #include <stdlib.h>
  41. /**************************************************************************/
  42. /*!
  43. @brief Instantiates a new Adafruit TSL2591 class
  44. @param sensorID An optional ID # so you can track this sensor, it will tag
  45. sensorEvents you create.
  46. */
  47. /**************************************************************************/
  48. Adafruit_TSL2591::Adafruit_TSL2591(int32_t sensorID) {
  49. _initialized = false;
  50. _integration = TSL2591_INTEGRATIONTIME_100MS;
  51. _gain = TSL2591_GAIN_MED;
  52. _sensorID = sensorID;
  53. // we cant do wire initialization till later, because we havent loaded Wire
  54. // yet
  55. }
  56. Adafruit_TSL2591::~Adafruit_TSL2591() {
  57. if (i2c_dev)
  58. delete i2c_dev;
  59. }
  60. /**************************************************************************/
  61. /*!
  62. @brief Setups the I2C interface and hardware, identifies if chip is found
  63. @param theWire a reference to TwoWire instance
  64. @param addr The I2C adress of the sensor (Default 0x29)
  65. @returns True if a TSL2591 is found, false on any failure
  66. */
  67. /**************************************************************************/
  68. boolean Adafruit_TSL2591::begin(TwoWire *theWire, uint8_t addr) {
  69. if (i2c_dev)
  70. delete i2c_dev;
  71. i2c_dev = new Adafruit_I2CDevice(addr, theWire);
  72. if (!i2c_dev->begin())
  73. return false;
  74. /*
  75. for (uint8_t i=0; i<0x20; i++)
  76. {
  77. uint8_t id = read8(0x12);
  78. Serial.print("$"); Serial.print(i, HEX);
  79. Serial.print(" = 0x"); Serial.println(read8(i), HEX);
  80. }
  81. */
  82. uint8_t id = read8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_DEVICE_ID);
  83. if (id != 0x50) {
  84. return false;
  85. }
  86. // Serial.println("Found Adafruit_TSL2591");
  87. _initialized = true;
  88. // Set default integration time and gain
  89. setTiming(_integration);
  90. setGain(_gain);
  91. // Note: by default, the device is in power down mode on bootup
  92. disable();
  93. return true;
  94. }
  95. /**************************************************************************/
  96. /*!
  97. @brief Setups the I2C interface and hardware, identifies if chip is found
  98. @param addr The I2C adress of the sensor (Default 0x29)
  99. @returns True if a TSL2591 is found, false on any failure
  100. */
  101. /**************************************************************************/
  102. boolean Adafruit_TSL2591::begin(uint8_t addr) { return begin(&Wire, addr); }
  103. /**************************************************************************/
  104. /*!
  105. @brief Enables the chip, so it's ready to take readings
  106. */
  107. /**************************************************************************/
  108. void Adafruit_TSL2591::enable(void) {
  109. if (!_initialized) {
  110. if (!begin()) {
  111. return;
  112. }
  113. }
  114. // Enable the device by setting the control bit to 0x01
  115. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE,
  116. TSL2591_ENABLE_POWERON | TSL2591_ENABLE_AEN | TSL2591_ENABLE_AIEN |
  117. TSL2591_ENABLE_NPIEN);
  118. }
  119. /**************************************************************************/
  120. /*!
  121. @brief Disables the chip, so it's in power down mode
  122. */
  123. /**************************************************************************/
  124. void Adafruit_TSL2591::disable(void) {
  125. if (!_initialized) {
  126. if (!begin()) {
  127. return;
  128. }
  129. }
  130. // Disable the device by setting the control bit to 0x00
  131. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE,
  132. TSL2591_ENABLE_POWEROFF);
  133. }
  134. /************************************************************************/
  135. /*!
  136. @brief Setter for sensor light gain
  137. @param gain {@link tsl2591Gain_t} gain value
  138. */
  139. /**************************************************************************/
  140. void Adafruit_TSL2591::setGain(tsl2591Gain_t gain) {
  141. if (!_initialized) {
  142. if (!begin()) {
  143. return;
  144. }
  145. }
  146. enable();
  147. _gain = gain;
  148. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL, _integration | _gain);
  149. disable();
  150. }
  151. /************************************************************************/
  152. /*!
  153. @brief Getter for sensor light gain
  154. @returns {@link tsl2591Gain_t} gain value
  155. */
  156. /**************************************************************************/
  157. tsl2591Gain_t Adafruit_TSL2591::getGain() { return _gain; }
  158. /************************************************************************/
  159. /*!
  160. @brief Setter for sensor integration time setting
  161. @param integration {@link tsl2591IntegrationTime_t} integration time setting
  162. */
  163. /**************************************************************************/
  164. void Adafruit_TSL2591::setTiming(tsl2591IntegrationTime_t integration) {
  165. if (!_initialized) {
  166. if (!begin()) {
  167. return;
  168. }
  169. }
  170. enable();
  171. _integration = integration;
  172. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL, _integration | _gain);
  173. disable();
  174. }
  175. /************************************************************************/
  176. /*!
  177. @brief Getter for sensor integration time setting
  178. @returns {@link tsl2591IntegrationTime_t} integration time
  179. */
  180. /**************************************************************************/
  181. tsl2591IntegrationTime_t Adafruit_TSL2591::getTiming() { return _integration; }
  182. /************************************************************************/
  183. /*!
  184. @brief Calculates the visible Lux based on the two light sensors
  185. @param ch0 Data from channel 0 (IR+Visible)
  186. @param ch1 Data from channel 1 (IR)
  187. @returns Lux, based on AMS coefficients (or < 0 if overflow)
  188. */
  189. /**************************************************************************/
  190. float Adafruit_TSL2591::calculateLux(uint16_t ch0, uint16_t ch1) {
  191. float atime, again;
  192. float cpl, lux;
  193. // Check for overflow conditions first
  194. if ((ch0 == 0xFFFF) | (ch1 == 0xFFFF)) {
  195. // Signal an overflow
  196. return -1;
  197. }
  198. // Note: This algorithm is based on preliminary coefficients
  199. // provided by AMS and may need to be updated in the future
  200. switch (_integration) {
  201. case TSL2591_INTEGRATIONTIME_100MS:
  202. atime = 100.0F;
  203. break;
  204. case TSL2591_INTEGRATIONTIME_200MS:
  205. atime = 200.0F;
  206. break;
  207. case TSL2591_INTEGRATIONTIME_300MS:
  208. atime = 300.0F;
  209. break;
  210. case TSL2591_INTEGRATIONTIME_400MS:
  211. atime = 400.0F;
  212. break;
  213. case TSL2591_INTEGRATIONTIME_500MS:
  214. atime = 500.0F;
  215. break;
  216. case TSL2591_INTEGRATIONTIME_600MS:
  217. atime = 600.0F;
  218. break;
  219. default: // 100ms
  220. atime = 100.0F;
  221. break;
  222. }
  223. switch (_gain) {
  224. case TSL2591_GAIN_LOW:
  225. again = 1.0F;
  226. break;
  227. case TSL2591_GAIN_MED:
  228. again = 25.0F;
  229. break;
  230. case TSL2591_GAIN_HIGH:
  231. again = 428.0F;
  232. break;
  233. case TSL2591_GAIN_MAX:
  234. again = 9876.0F;
  235. break;
  236. default:
  237. again = 1.0F;
  238. break;
  239. }
  240. // cpl = (ATIME * AGAIN) / DF
  241. cpl = (atime * again) / TSL2591_LUX_DF;
  242. // Original lux calculation (for reference sake)
  243. // float lux1 = ( (float)ch0 - (TSL2591_LUX_COEFB * (float)ch1) ) / cpl;
  244. // float lux2 = ( ( TSL2591_LUX_COEFC * (float)ch0 ) - ( TSL2591_LUX_COEFD *
  245. // (float)ch1 ) ) / cpl; lux = lux1 > lux2 ? lux1 : lux2;
  246. // Alternate lux calculation 1
  247. // See: https://github.com/adafruit/Adafruit_TSL2591_Library/issues/14
  248. lux = (((float)ch0 - (float)ch1)) * (1.0F - ((float)ch1 / (float)ch0)) / cpl;
  249. // Alternate lux calculation 2
  250. // lux = ( (float)ch0 - ( 1.7F * (float)ch1 ) ) / cpl;
  251. // Signal I2C had no errors
  252. return lux;
  253. }
  254. /************************************************************************/
  255. /*!
  256. @brief Reads the raw data from both light channels
  257. @returns 32-bit raw count where high word is IR, low word is IR+Visible
  258. */
  259. /**************************************************************************/
  260. uint32_t Adafruit_TSL2591::getFullLuminosity(void) {
  261. if (!_initialized) {
  262. if (!begin()) {
  263. return 0;
  264. }
  265. }
  266. // Enable the device
  267. enable();
  268. // Wait x ms for ADC to complete
  269. for (uint8_t d = 0; d <= _integration; d++) {
  270. delay(120);
  271. }
  272. // CHAN0 must be read before CHAN1
  273. // See: https://forums.adafruit.com/viewtopic.php?f=19&t=124176
  274. uint32_t x;
  275. uint16_t y;
  276. y = read16(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN0_LOW);
  277. x = read16(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN1_LOW);
  278. x <<= 16;
  279. x |= y;
  280. disable();
  281. return x;
  282. }
  283. /************************************************************************/
  284. /*!
  285. @brief Reads the raw data from the channel
  286. @param channel Can be 0 (IR+Visible, 1 (IR) or 2 (Visible only)
  287. @returns 16-bit raw count, or 0 if channel is invalid
  288. */
  289. /**************************************************************************/
  290. uint16_t Adafruit_TSL2591::getLuminosity(uint8_t channel) {
  291. uint32_t x = getFullLuminosity();
  292. if (channel == TSL2591_FULLSPECTRUM) {
  293. // Reads two byte value from channel 0 (visible + infrared)
  294. return (x & 0xFFFF);
  295. } else if (channel == TSL2591_INFRARED) {
  296. // Reads two byte value from channel 1 (infrared)
  297. return (x >> 16);
  298. } else if (channel == TSL2591_VISIBLE) {
  299. // Reads all and subtracts out just the visible!
  300. return ((x & 0xFFFF) - (x >> 16));
  301. }
  302. // unknown channel!
  303. return 0;
  304. }
  305. /************************************************************************/
  306. /*!
  307. @brief Set up the interrupt to go off when light level is outside the
  308. lower/upper range.
  309. @param lowerThreshold Raw light data reading level that is the lower value
  310. threshold for interrupt
  311. @param upperThreshold Raw light data reading level that is the higher value
  312. threshold for interrupt
  313. @param persist How many counts we must be outside range for interrupt to
  314. fire, default is any single value
  315. */
  316. /**************************************************************************/
  317. void Adafruit_TSL2591::registerInterrupt(
  318. uint16_t lowerThreshold, uint16_t upperThreshold,
  319. tsl2591Persist_t persist = TSL2591_PERSIST_ANY) {
  320. if (!_initialized) {
  321. if (!begin()) {
  322. return;
  323. }
  324. }
  325. enable();
  326. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_PERSIST_FILTER, persist);
  327. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_AILTL,
  328. lowerThreshold);
  329. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_AILTH,
  330. lowerThreshold >> 8);
  331. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_AIHTL,
  332. upperThreshold);
  333. write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_AIHTH,
  334. upperThreshold >> 8);
  335. disable();
  336. }
  337. /************************************************************************/
  338. /*!
  339. @brief Clear interrupt status
  340. */
  341. /**************************************************************************/
  342. void Adafruit_TSL2591::clearInterrupt() {
  343. if (!_initialized) {
  344. if (!begin()) {
  345. return;
  346. }
  347. }
  348. enable();
  349. write8(TSL2591_CLEAR_INT);
  350. disable();
  351. }
  352. /************************************************************************/
  353. /*!
  354. @brief Gets the most recent sensor event from the hardware status register.
  355. @return Sensor status as a byte. Bit 0 is ALS Valid. Bit 4 is ALS Interrupt.
  356. Bit 5 is No-persist Interrupt.
  357. */
  358. /**************************************************************************/
  359. uint8_t Adafruit_TSL2591::getStatus(void) {
  360. if (!_initialized) {
  361. if (!begin()) {
  362. return 0;
  363. }
  364. }
  365. // Enable the device
  366. enable();
  367. uint8_t x;
  368. x = read8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_DEVICE_STATUS);
  369. disable();
  370. return x;
  371. }
  372. /************************************************************************/
  373. /*!
  374. @brief Gets the most recent sensor event
  375. @param event Pointer to Adafruit_Sensor sensors_event_t object that will be
  376. filled with sensor data
  377. @return True on success, False on failure
  378. */
  379. /**************************************************************************/
  380. bool Adafruit_TSL2591::getEvent(sensors_event_t *event) {
  381. uint16_t ir, full;
  382. uint32_t lum = getFullLuminosity();
  383. /* Early silicon seems to have issues when there is a sudden jump in */
  384. /* light levels. :( To work around this for now sample the sensor 2x */
  385. lum = getFullLuminosity();
  386. ir = lum >> 16;
  387. full = lum & 0xFFFF;
  388. /* Clear the event */
  389. memset(event, 0, sizeof(sensors_event_t));
  390. event->version = sizeof(sensors_event_t);
  391. event->sensor_id = _sensorID;
  392. event->type = SENSOR_TYPE_LIGHT;
  393. event->timestamp = millis();
  394. /* Calculate the actual lux value */
  395. /* 0 = sensor overflow (too much light) */
  396. event->light = calculateLux(full, ir);
  397. return true;
  398. }
  399. /**************************************************************************/
  400. /*!
  401. @brief Gets the overall sensor_t data including the type, range and
  402. resulution
  403. @param sensor Pointer to Adafruit_Sensor sensor_t object that will be
  404. filled with sensor type data
  405. */
  406. /**************************************************************************/
  407. void Adafruit_TSL2591::getSensor(sensor_t *sensor) {
  408. /* Clear the sensor_t object */
  409. memset(sensor, 0, sizeof(sensor_t));
  410. /* Insert the sensor name in the fixed length char array */
  411. strncpy(sensor->name, "TSL2591", sizeof(sensor->name) - 1);
  412. sensor->name[sizeof(sensor->name) - 1] = 0;
  413. sensor->version = 1;
  414. sensor->sensor_id = _sensorID;
  415. sensor->type = SENSOR_TYPE_LIGHT;
  416. sensor->min_delay = 0;
  417. sensor->max_value = 88000.0;
  418. sensor->min_value = 0.0;
  419. sensor->resolution = 0.001;
  420. }
  421. /*******************************************************/
  422. uint8_t Adafruit_TSL2591::read8(uint8_t reg) {
  423. uint8_t buffer[1];
  424. buffer[0] = reg;
  425. i2c_dev->write_then_read(buffer, 1, buffer, 1);
  426. return buffer[0];
  427. }
  428. uint16_t Adafruit_TSL2591::read16(uint8_t reg) {
  429. uint8_t buffer[2];
  430. buffer[0] = reg;
  431. i2c_dev->write_then_read(buffer, 1, buffer, 2);
  432. return uint16_t(buffer[1]) << 8 | uint16_t(buffer[0]);
  433. }
  434. void Adafruit_TSL2591::write8(uint8_t reg, uint8_t value) {
  435. uint8_t buffer[2];
  436. buffer[0] = reg;
  437. buffer[1] = value;
  438. i2c_dev->write(buffer, 2);
  439. }
  440. void Adafruit_TSL2591::write8(uint8_t reg) {
  441. uint8_t buffer[1];
  442. buffer[0] = reg;
  443. i2c_dev->write(buffer, 1);
  444. }