This library gets information from TSL2550 ambient light sensor through SMBus / I²C.
TSL2550.cpp
- Committer:
- goeckeritz
- Date:
- 2011-03-30
- Revision:
- 0:7e6a051d1700
File content as of revision 0:7e6a051d1700:
/* * mbed library to use a TAOS TSL2550 Ambient Light Sensor * Copyright (c) 2011 Stefan Goeckeritz, * RheinAhrCampus Remagen, Suedallee 2, 53424 Remagen * * Released under the MIT License: http://mbed.org/license/mit */ #include "mbed.h" #include "TSL2550.h" #define TSL2550_ADDR 0x72 //hardwired slave address of TSL2550 #define xpow(x, y) ((long)1 << y) TSL2550::TSL2550 (PinName p_sda, PinName p_scl ) : i2c(p_sda, p_scl) { init(); } TSL2550::TSL2550 (I2C& p_i2c) : i2c(p_i2c) { init(); } unsigned short TSL2550::get_ch0() { return ch0; } unsigned short TSL2550::get_ch1() { return ch1; } double TSL2550::get_lux() { return lux; } void TSL2550::update () { unsigned short c0, c1, s0, s1; int adc0, adc1; double r; //read channel 0 and 1 ch0 = twi_read(TSL2550_ADDR, 0x43); wait(0.5); ch1 = twi_read(TSL2550_ADDR, 0x83); //now compute lux value, if data is valid if((ch0 & 0x80) && (ch1 & 0x80)) { c0 = (ch0 & ~0x80) >> 4 ; c1 = (ch1 & ~0x80) >> 4 ; s0 = ch0 & ~0xF0 ; s1 = ch1 & ~0xF0 ; //ADC Count Value adc0 = int(16.5 * xpow(2,c0)) + (s0 * xpow(2,c0)); adc1 = int(16.5 * xpow(2,c1)) + (s1 * xpow(2,c1)); r = (double(adc1) / double(adc0)); lux = double(adc0) * 0.46 * exp(-3.13 * r); //give debug information //printf("\n\nZW: c0=%i s0=%i c1=%i s1=%i \n", c0, s0, c1, s1); //printf("ZW: adc0=%i, adc1=%i\n", adc0, adc1); } else printf("TSL2550: ***data not valid ! ***\n"); } void TSL2550::init() { unsigned short i; i = twi_read(TSL2550_ADDR, 0x03); if( i == 0x03 ) printf("TSL2550: Init successful\n"); else printf("TSL2550: Init ***failed*** !\n"); } unsigned short TSL2550::twi_read (unsigned short id, unsigned short data) { unsigned short i; //supply COMMAND byte to slave i2c.start(); i2c.write(id); i2c.write(data); //demand ANSWER byte from slave i2c.start(); i2c.write(id | 1); i = i2c.read(0); i2c.stop(); return i; } void TSL2550::twi_write (unsigned short id, unsigned short data) { i2c.start(); i2c.write(id); i2c.write(data); i2c.stop(); }