From cd4e9f7664490ed62cfcd427118a2e9598b9e5ca Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 11:33:53 +0000 Subject: [PATCH 01/44] Initial creation of TSL2561 library with latest I2C lib and the moded forum sourced TSL2561 Python code --- Adafruit_TSL2561/Adafruit_I2C.py | 161 ++++++++ Adafruit_TSL2561/Adafruit_TSL2561.py | 545 +++++++++++++++++++++++++++ 2 files changed, 706 insertions(+) create mode 100755 Adafruit_TSL2561/Adafruit_I2C.py create mode 100755 Adafruit_TSL2561/Adafruit_TSL2561.py diff --git a/Adafruit_TSL2561/Adafruit_I2C.py b/Adafruit_TSL2561/Adafruit_I2C.py new file mode 100755 index 00000000..2b24b67f --- /dev/null +++ b/Adafruit_TSL2561/Adafruit_I2C.py @@ -0,0 +1,161 @@ +#!/usr/bin/python +import re +import smbus + +# =========================================================================== +# Adafruit_I2C Class +# =========================================================================== + +class Adafruit_I2C(object): + + @staticmethod + def getPiRevision(): + "Gets the version number of the Raspberry Pi board" + # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History + try: + with open('/proc/cpuinfo', 'r') as infile: + for line in infile: + # Match a line of the form "Revision : 0002" while ignoring extra + # info in front of the revsion (like 1000 when the Pi was over-volted). + match = re.match('Revision\s+:\s+.*(\w{4})$', line) + if match and match.group(1) in ['0000', '0002', '0003']: + # Return revision 1 if revision ends with 0000, 0002 or 0003. + return 1 + elif match: + # Assume revision 2 if revision ends with any other 4 chars. + return 2 + # Couldn't find the revision, assume revision 0 like older code for compatibility. + return 0 + except: + return 0 + + @staticmethod + def getPiI2CBusNumber(): + # Gets the I2C bus number /dev/i2c# + return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 + + def __init__(self, address, busnum=-1, debug=False): + self.address = address + # By default, the correct I2C bus is auto-detected using /proc/cpuinfo + # Alternatively, you can hard-code the bus version below: + # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) + # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) + self.bus = smbus.SMBus(busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) + self.debug = debug + + def reverseByteOrder(self, data): + "Reverses the byte order of an int (16-bit) or long (32-bit) value" + # Courtesy Vishal Sapre + byteCount = len(hex(data)[2:].replace('L','')[::2]) + val = 0 + for i in range(byteCount): + val = (val << 8) | (data & 0xff) + data >>= 8 + return val + + def errMsg(self): + print "Error accessing 0x%02X: Check your I2C address" % self.address + return -1 + + def write8(self, reg, value): + "Writes an 8-bit value to the specified register/address" + try: + self.bus.write_byte_data(self.address, reg, value) + if self.debug: + print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg) + except IOError, err: + return self.errMsg() + + def write16(self, reg, value): + "Writes a 16-bit value to the specified register/address pair" + try: + self.bus.write_word_data(self.address, reg, value) + if self.debug: + print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % + (value, reg, reg+1)) + except IOError, err: + return self.errMsg() + + def writeRaw8(self, value): + "Writes an 8-bit value on the bus" + try: + self.bus.write_byte(self.address, value) + if self.debug: + print "I2C: Wrote 0x%02X" % value + except IOError, err: + return self.errMsg() + + def writeList(self, reg, list): + "Writes an array of bytes using I2C format" + try: + if self.debug: + print "I2C: Writing list to register 0x%02X:" % reg + print list + self.bus.write_i2c_block_data(self.address, reg, list) + except IOError, err: + return self.errMsg() + + def readList(self, reg, length): + "Read a list of bytes from the I2C device" + try: + results = self.bus.read_i2c_block_data(self.address, reg, length) + if self.debug: + print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % + (self.address, reg)) + print results + return results + except IOError, err: + return self.errMsg() + + def readU8(self, reg): + "Read an unsigned byte from the I2C device" + try: + result = self.bus.read_byte_data(self.address, reg) + if self.debug: + print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % + (self.address, result & 0xFF, reg)) + return result + except IOError, err: + return self.errMsg() + + def readS8(self, reg): + "Reads a signed byte from the I2C device" + try: + result = self.bus.read_byte_data(self.address, reg) + if result > 127: result -= 256 + if self.debug: + print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % + (self.address, result & 0xFF, reg)) + return result + except IOError, err: + return self.errMsg() + + def readU16(self, reg, little_endian=True): + "Reads an unsigned 16-bit value from the I2C device" + try: + result = self.bus.read_word_data(self.address,reg) + # Swap bytes if using big endian because read_word_data assumes little + # endian on ARM (little endian) systems. + if not little_endian: + result = ((result << 8) & 0xFF00) + (result >> 8) + if (self.debug): + print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) + return result + except IOError, err: + return self.errMsg() + + def readS16(self, reg, little_endian=True): + "Reads a signed 16-bit value from the I2C device" + try: + result = self.readU16(reg,little_endian) + if result > 32767: result -= 65536 + return result + except IOError, err: + return self.errMsg() + +if __name__ == '__main__': + try: + bus = Adafruit_I2C(address=0) + print "Default I2C bus is accessible" + except: + print "Error accessing default I2C bus" diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py new file mode 100755 index 00000000..2ad2b05f --- /dev/null +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -0,0 +1,545 @@ +#!/usr/bin/python + +# Python library for the TSL2561 digital luminosity (light) sensors. +# Version 0 + +# This library is heavily based on the Arduino library for the TSL2561 digital luminosity (light) sensors. +# It is basically a simple translation from C++ to Python. +# The thread on the Adafruit forum helped a lot to do this. +# Thanks to static, huelke, pandring, adafruit_support_rick, scortier, bryand, csalty, lenos and of course to Adafruit +# Source for the Arduino library: https://github.com/adafruit/TSL2561-Arduino-Library +# Adafruit form thread:http://forums.adafruit.com/viewtopic.php?f=8&t=34922&sid=8336d566f2f03c25882aaf34c8a15a92 + +import sys +import time +from Adafruit_I2C import Adafruit_I2C + +class Adafruit_TSL2651(Adafruit_I2C): + TSL2561_VISIBLE =2 # channel 0 - channel 1 + TSL2561_INFRARED =1 # channel 1 + TSL2561_FULLSPECTRUM =0 # channel 0 + + # I2C address options + TSL2561_ADDR_LOW =0x29 + TSL2561_ADDR_FLOAT =0x39 # Default address (pin left floating) + TSL2561_ADDR_HIGH =0x49 + + # Lux calculations differ slightly for CS package + TSL2561_PACKAGE_CS =0 + TSL2561_PACKAGE_T_FN_CL =1 + + TSL2561_COMMAND_BIT =0x80 # Must be 1 + TSL2561_CLEAR_BIT =0x40 # Clears any pending interrupt (write 1 to clear) + TSL2561_WORD_BIT =0x20 # 1 = read/write word (rather than byte) + TSL2561_BLOCK_BIT =0x10 # 1 = using block read/write + + TSL2561_CONTROL_POWERON =0x03 + TSL2561_CONTROL_POWEROFF =0x00 + + TSL2561_LUX_LUXSCALE =14 # Scale by 2^14 + TSL2561_LUX_RATIOSCALE =9 # Scale ratio by 2^9 + TSL2561_LUX_CHSCALE =10 # Scale channel values by 2^10 + TSL2561_LUX_CHSCALE_TINT0 =0x7517 # 322/11 * 2^TSL2561_LUX_CHSCALE + TSL2561_LUX_CHSCALE_TINT1 =0x0FE7 # 322/81 * 2^TSL2561_LUX_CHSCALE + + # T, FN and CL package values + TSL2561_LUX_K1T =0x0040 # 0.125 * 2^RATIO_SCALE + TSL2561_LUX_B1T =0x01f2 # 0.0304 * 2^LUX_SCALE + TSL2561_LUX_M1T =0x01be # 0.0272 * 2^LUX_SCALE + TSL2561_LUX_K2T =0x0080 # 0.250 * 2^RATIO_SCALE + TSL2561_LUX_B2T =0x0214 # 0.0325 * 2^LUX_SCALE + TSL2561_LUX_M2T =0x02d1 # 0.0440 * 2^LUX_SCALE + TSL2561_LUX_K3T =0x00c0 # 0.375 * 2^RATIO_SCALE + TSL2561_LUX_B3T =0x023f # 0.0351 * 2^LUX_SCALE + TSL2561_LUX_M3T =0x037b # 0.0544 * 2^LUX_SCALE + TSL2561_LUX_K4T =0x0100 # 0.50 * 2^RATIO_SCALE + TSL2561_LUX_B4T =0x0270 # 0.0381 * 2^LUX_SCALE + TSL2561_LUX_M4T =0x03fe # 0.0624 * 2^LUX_SCALE + TSL2561_LUX_K5T =0x0138 # 0.61 * 2^RATIO_SCALE + TSL2561_LUX_B5T =0x016f # 0.0224 * 2^LUX_SCALE + TSL2561_LUX_M5T =0x01fc # 0.0310 * 2^LUX_SCALE + TSL2561_LUX_K6T =0x019a # 0.80 * 2^RATIO_SCALE + TSL2561_LUX_B6T =0x00d2 # 0.0128 * 2^LUX_SCALE + TSL2561_LUX_M6T =0x00fb # 0.0153 * 2^LUX_SCALE + TSL2561_LUX_K7T =0x029a # 1.3 * 2^RATIO_SCALE + TSL2561_LUX_B7T =0x0018 # 0.00146 * 2^LUX_SCALE + TSL2561_LUX_M7T =0x0012 # 0.00112 * 2^LUX_SCALE + TSL2561_LUX_K8T =0x029a # 1.3 * 2^RATIO_SCALE + TSL2561_LUX_B8T =0x0000 # 0.000 * 2^LUX_SCALE + TSL2561_LUX_M8T =0x0000 # 0.000 * 2^LUX_SCALE + + # CS package values + TSL2561_LUX_K1C =0x0043 # 0.130 * 2^RATIO_SCALE + TSL2561_LUX_B1C =0x0204 # 0.0315 * 2^LUX_SCALE + TSL2561_LUX_M1C =0x01ad # 0.0262 * 2^LUX_SCALE + TSL2561_LUX_K2C =0x0085 # 0.260 * 2^RATIO_SCALE + TSL2561_LUX_B2C =0x0228 # 0.0337 * 2^LUX_SCALE + TSL2561_LUX_M2C =0x02c1 # 0.0430 * 2^LUX_SCALE + TSL2561_LUX_K3C =0x00c8 # 0.390 * 2^RATIO_SCALE + TSL2561_LUX_B3C =0x0253 # 0.0363 * 2^LUX_SCALE + TSL2561_LUX_M3C =0x0363 # 0.0529 * 2^LUX_SCALE + TSL2561_LUX_K4C =0x010a # 0.520 * 2^RATIO_SCALE + TSL2561_LUX_B4C =0x0282 # 0.0392 * 2^LUX_SCALE + TSL2561_LUX_M4C =0x03df # 0.0605 * 2^LUX_SCALE + TSL2561_LUX_K5C =0x014d # 0.65 * 2^RATIO_SCALE + TSL2561_LUX_B5C =0x0177 # 0.0229 * 2^LUX_SCALE + TSL2561_LUX_M5C =0x01dd # 0.0291 * 2^LUX_SCALE + TSL2561_LUX_K6C =0x019a # 0.80 * 2^RATIO_SCALE + TSL2561_LUX_B6C =0x0101 # 0.0157 * 2^LUX_SCALE + TSL2561_LUX_M6C =0x0127 # 0.0180 * 2^LUX_SCALE + TSL2561_LUX_K7C =0x029a # 1.3 * 2^RATIO_SCALE + TSL2561_LUX_B7C =0x0037 # 0.00338 * 2^LUX_SCALE + TSL2561_LUX_M7C =0x002b # 0.00260 * 2^LUX_SCALE + TSL2561_LUX_K8C =0x029a # 1.3 * 2^RATIO_SCALE + TSL2561_LUX_B8C =0x0000 # 0.000 * 2^LUX_SCALE + TSL2561_LUX_M8C =0x0000 # 0.000 * 2^LUX_SCALE + + # Auto-gain thresholds + TSL2561_AGC_THI_13MS =4850 # Max value at Ti 13ms = 5047 + TSL2561_AGC_TLO_13MS =100 + TSL2561_AGC_THI_101MS =36000 # Max value at Ti 101ms = 37177 + TSL2561_AGC_TLO_101MS =200 + TSL2561_AGC_THI_402MS =63000 # Max value at Ti 402ms = 65535 + TSL2561_AGC_TLO_402MS =500 + + # Clipping thresholds + TSL2561_CLIPPING_13MS =4900 + TSL2561_CLIPPING_101MS =37000 + TSL2561_CLIPPING_402MS =65000 + + TSL2561_REGISTER_CONTROL = 0x00 + TSL2561_REGISTER_TIMING = 0x01 + TSL2561_REGISTER_THRESHHOLDL_LOW = 0x02 + TSL2561_REGISTER_THRESHHOLDL_HIGH = 0x03 + TSL2561_REGISTER_THRESHHOLDH_LOW = 0x04 + TSL2561_REGISTER_THRESHHOLDH_HIGH = 0x05 + TSL2561_REGISTER_INTERRUPT = 0x06 + TSL2561_REGISTER_CRC = 0x08 + TSL2561_REGISTER_ID = 0x0A + TSL2561_REGISTER_CHAN0_LOW = 0x0C + TSL2561_REGISTER_CHAN0_HIGH = 0x0D + TSL2561_REGISTER_CHAN1_LOW = 0x0E + TSL2561_REGISTER_CHAN1_HIGH = 0x0F + + TSL2561_INTEGRATIONTIME_13MS = 0x00 # 13.7ms + TSL2561_INTEGRATIONTIME_101MS = 0x01 # 101ms + TSL2561_INTEGRATIONTIME_402MS = 0x02 # 402ms + + TSL2561_GAIN_1X = 0x00 # No gain + TSL2561_GAIN_16X = 0x10 # 16x gain + + + + +#**************************************************************************/ +# Writes a register and an 8 bit value over I2C +#**************************************************************************/ + def write8 (self, reg, value): + if (self._debug == True): print "write8" + self._i2c.write8(reg, value) + if (self._debug == True): print "write8_end" + +#**************************************************************************/ +# Reads an 8 bit value over I2C +#**************************************************************************/ + def read8(self, reg): + if (self._debug == True): print "read8" + return self._i2c.readS8(reg) + if (self._debug == True): print "read8_end" + +#**************************************************************************/ +# Reads a 16 bit values over I2C +#**************************************************************************/ + def read16(self, reg): + if (self._debug == True): print "read16" + return self._i2c.readS16(reg) + if (self._debug == True): print "read16_end" + +#**************************************************************************/ +# Enables the device +#**************************************************************************/ + def enable(self): + if (self._debug == True): print "enable" + # Enable the device by setting the control bit to 0x03 */ + self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWERON) + if (self._debug == True): print "enable_end" + +#**************************************************************************/ +# Disables the device (putting it in lower power sleep mode) +#**************************************************************************/ + def disable(self): + if (self._debug == True): print "disable" + # Turn the device off to save power */ + self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWEROFF) + if (self._debug == True): print "disable_end" + +#**************************************************************************/ +# Private function to read luminosity on both channels +#**************************************************************************/ + def getData (self): + if (self._debug == True): print "getData" + # Enable the device by setting the control bit to 0x03 */ + self.enable(); + + # Wait x ms for ADC to complete */ + if self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS: + time.sleep(0.014) + elif self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS: + time.sleep(0.102) + else: + time.sleep(0.403) + + + # Reads a two byte value from channel 0 (visible + infrared) */ + self._broadband = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN0_LOW); + + # Reads a two byte value from channel 1 (infrared) */ + self._ir = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN1_LOW); + + # Turn the device off to save power */ + self.disable(); + if (self._debug == True): print "getData_end" + +#**************************************************************************/ +# Constructor +#**************************************************************************/ + def __init__(self, addr=0x39, debug=False): + self._debug = debug + if (self._debug == True): print "__init__" + self._addr = addr + self._tsl2561Initialised = False + self._tsl2561AutoGain = False + self._tsl2561IntegrationTime = self.TSL2561_INTEGRATIONTIME_13MS + self._tsl2561Gain = self.TSL2561_GAIN_1X + self._i2c = Adafruit_I2C(self._addr) + self._luminosity = 0 + self._broadband = 0 + self._ir = 0 + if (self._debug == True): print "__init___end" + +#**************************************************************************/ +# Initializes I2C and configures the sensor (call this function before +# doing anything else) +#**************************************************************************/ + def begin(self): + if (self._debug == True): print "begin" + # Make sure we're actually connected */ + x = self.read8(self.TSL2561_REGISTER_ID); + if not(x & 0x0A): + return False + self._tsl2561Initialised = True + + # Set default integration time and gain */ + self.setIntegrationTime(self._tsl2561IntegrationTime) + self.setGain(self._tsl2561Gain) + + # Note: by default, the device is in power down mode on bootup */ + self.disable() + if (self._debug == True): print "begin_end" + + return True + +#**************************************************************************/ +# Enables or disables the auto-gain settings when reading +# data from the sensor +#**************************************************************************/ + def enableAutoGain(self, enable): + if (self._debug == True): print "enableAutoGain" + self._tsl2561AutoGain = enable if True else False + if (enable == True): + self._tsl2561AutoGain = enable + else: + self._tsl2561AutoGain = False + if (self._debug == True): print "enableAutoGain_end" + +#**************************************************************************/ +# Sets the integration time for the TSL2561 +#**************************************************************************/ + def setIntegrationTime(self, time): + if (self._debug == True): print "setIntegrationTime" + if (not self._tsl2561Initialised): + self.begin() + + # Enable the device by setting the control bit to 0x03 */ + self.enable(); + + # Update the timing register */ + self.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_TIMING, time | self._tsl2561Gain) + + # Update value placeholders */ + self._tsl2561IntegrationTime = time + + # Turn the device off to save power */ + self.disable() + if (self._debug == True): print "setIntegrationTime_end" + +#**************************************************************************/ +# Adjusts the gain on the TSL2561 (adjusts the sensitivity to light) +#**************************************************************************/ + def setGain(self, gain): + if (self._debug == True): print "setGain" + if (not self._tsl2561Initialised): + begin() + + # Enable the device by setting the control bit to 0x03 */ + self.enable() + + # Update the timing register */ + self.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_TIMING, self._tsl2561IntegrationTime | gain) + + # Update value placeholders */ + self._tsl2561Gain = gain + + # Turn the device off to save power */ + self.disable() + if (self._debug == True): print "setGain_end" + +#**************************************************************************/ +# Gets the broadband (mixed lighting) and IR only values from +# the TSL2561, adjusting gain if auto-gain is enabled +#**************************************************************************/ + def getLuminosity (self): + if (self._debug == True): print "getLuminosity" + valid = False + + if (not self._tsl2561Initialised): + self.begin() + + # If Auto gain disabled get a single reading and continue */ + if(not self._tsl2561AutoGain): + self.getData() + return + + # Read data until we find a valid range */ + _agcCheck = False + while (not valid): + _it = self._tsl2561IntegrationTime; + + # Get the hi/low threshold for the current integration time */ + if _it==self.TSL2561_INTEGRATIONTIME_13MS: + _hi = self.TSL2561_AGC_THI_13MS + _lo = self.TSL2561_AGC_TLO_13MS + elif _it==self.TSL2561_INTEGRATIONTIME_101MS: + _hi = self.TSL2561_AGC_THI_101MS + _lo = self.TSL2561_AGC_TLO_101MS + else: + _hi = self.TSL2561_AGC_THI_402MS + _lo = self.TSL2561_AGC_TLO_402MS + + self.getData() + + # Run an auto-gain check if we haven't already done so ... */ + if (not _agcCheck): + if ((self._broadband < _lo) and (self._tsl2561Gain == self.TSL2561_GAIN_1X)): + # Increase the gain and try again */ + self.setGain(self.TSL2561_GAIN_16X) + # Drop the previous conversion results */ + self.getData() + # Set a flag to indicate we've adjusted the gain */ + _agcCheck = True + elif ((self._broadband > _hi) and (self._tsl2561Gain == self.TSL2561_GAIN_16X)): + # Drop gain to 1x and try again */ + self.setGain(self.TSL2561_GAIN_1X) + # Drop the previous conversion results */ + self.getData() + # Set a flag to indicate we've adjusted the gain */ + _agcCheck = True + else: + # Nothing to look at here, keep moving .... + # Reading is either valid, or we're already at the chips limits */ + valid = True + else: + # If we've already adjusted the gain once, just return the new results. + # This avoids endless loops where a value is at one extreme pre-gain, + # and the the other extreme post-gain */ + valid = True + if (self._debug == True): print "getLuminosity_end" + +#**************************************************************************/ +# Converts the raw sensor values to the standard SI lux equivalent. +# Returns 0 if the sensor is saturated and the values are unreliable. +#**************************************************************************/ + def calculateLux(self): + if (self._debug == True): print "calculateLux" + self.getLuminosity() + # Make sure the sensor isn't saturated! */ + if (self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS): + clipThreshold = self.TSL2561_CLIPPING_13MS + elif (self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS): + clipThreshold = self.TSL2561_CLIPPING_101MS + else: + clipThreshold = self.TSL2561_CLIPPING_402MS + + # Return 0 lux if the sensor is saturated */ + if ((self._broadband > clipThreshold) or (self._ir > clipThreshold)): + return 0 + + # Get the correct scale depending on the intergration time */ + if (self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_13MS): + chScale = self.TSL2561_LUX_CHSCALE_TINT0 + elif (self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_101MS): + chScale = self.TSL2561_LUX_CHSCALE_TINT1 + else: + chScale = (1 << self.TSL2561_LUX_CHSCALE) + + # Scale for gain (1x or 16x) */ + if (not self._tsl2561Gain): + chScale = chScale << 4 + + # Scale the channel values */ + channel0 = (self._broadband * chScale) >> self.TSL2561_LUX_CHSCALE + channel1 = (self._ir * chScale) >> self.TSL2561_LUX_CHSCALE + + # Find the ratio of the channel values (Channel1/Channel0) */ + ratio1 = 0; + if (channel0 != 0): + ratio1 = (channel1 << (self.TSL2561_LUX_RATIOSCALE+1)) / channel0 + + # round the ratio value */ + ratio = (ratio1 + 1) >> 1 + + if (self.TSL2561_PACKAGE_CS == 1): + if ((ratio >= 0) and (ratio <= self.TSL2561_LUX_K1C)): + b=self.TSL2561_LUX_B1C + m=self.TSL2561_LUX_M1C + elif (ratio <= self.TSL2561_LUX_K2C): + b=self.TSL2561_LUX_B2C + m=self.TSL2561_LUX_M2C + elif (ratio <= self.TSL2561_LUX_K3C): + b=self.TSL2561_LUX_B3C + m=self.TSL2561_LUX_M3C + elif (ratio <= self.TSL2561_LUX_K4C): + b=self.TSL2561_LUX_B4C + m=self.TSL2561_LUX_M4C + elif (ratio <= self.TSL2561_LUX_K5C): + b=self.TSL2561_LUX_B5C + m=self.TSL2561_LUX_M5C + elif (ratio <= self.TSL2561_LUX_K6C): + b=self.TSL2561_LUX_B6C + m=self.TSL2561_LUX_M6C + elif (ratio <= self.TSL2561_LUX_K7C): + b=self.TSL2561_LUX_B7C + m=self.TSL2561_LUX_M7C + elif (ratio > self.TSL2561_LUX_K8C): + b=self.TSL2561_LUX_B8C + m=self.TSL2561_LUX_M8C + elif (self.TSL2561_PACKAGE_T_FN_CL == 1): + if ((ratio >= 0) and (ratio <= self.TSL2561_LUX_K1T)): + b=self.TSL2561_LUX_B1T + m=self.TSL2561_LUX_M1T + elif (ratio <= self.TSL2561_LUX_K2T): + b=self.TSL2561_LUX_B2T + m=self.TSL2561_LUX_M2T + elif (ratio <= self.TSL2561_LUX_K3T): + b=self.TSL2561_LUX_B3T + m=self.TSL2561_LUX_M3T + elif (ratio <= self.TSL2561_LUX_K4T): + b=self.TSL2561_LUX_B4T + m=self.TSL2561_LUX_M4T + elif (ratio <= self.TSL2561_LUX_K5T): + b=self.TSL2561_LUX_B5T + m=self.TSL2561_LUX_M5T + elif (ratio <= self.TSL2561_LUX_K6T): + b=self.TSL2561_LUX_B6T + m=self.TSL2561_LUX_M6T + elif (ratio <= self.TSL2561_LUX_K7T): + b=self.TSL2561_LUX_B7T + m=self.TSL2561_LUX_M7T + elif (ratio > self.TSL2561_LUX_K8T): + b=self.TSL2561_LUX_B8T + m=self.TSL2561_LUX_M8T + #endif + + temp = ((channel0 * b) - (channel1 * m)) + + # Do not allow negative lux value */ + if (temp < 0): + temp = 0 + + # Round lsb (2^(LUX_SCALE-1)) */ + temp += (1 << (self.TSL2561_LUX_LUXSCALE-1)) + + # Strip off fractional portion */ + lux = temp >> self.TSL2561_LUX_LUXSCALE; + + # Signal I2C had no errors */ + if (self._debug == True): print "calculateLux_end" + return lux + +#**************************************************************************/ +# Calculates an averaged Lux value over default 30 samples +#**************************************************************************/ + def calculateAvgLux(self, testavg=int(30)): + # Set initial vars + count = 0 + luxavgtotal = 0 + # Create a cumulative total of values for 'testavg' tests + while True: + capture = self.calculateLux() + luxavgtotal = capture + luxavgtotal + count += 1 + # Once we reach the number of required tests, work out the average + if ( count >= testavg ): + luxavg = round(luxavgtotal / testavg) + return (luxavg) + +''' +#**************************************************************************/ +# Gets the most recent sensor event +#**************************************************************************/ +void Adafruit_TSL2561::getEvent(sensors_event_t *event) +{ + uint16_t broadband, ir; + + # Clear the event */ + memset(event, 0, sizeof(sensors_event_t)); + + event->version = sizeof(sensors_event_t); + event->sensor_id = _tsl2561SensorID; + event->type = SENSOR_TYPE_LIGHT; + event->timestamp = 0; + + # Calculate the actual lux value */ + getLuminosity(&broadband, &ir); + event->light = calculateLux(broadband, ir); +} + +#**************************************************************************/ +# Gets the sensor_t data +#**************************************************************************/ +void Adafruit_TSL2561::getSensor(sensor_t *sensor) +{ + # Clear the sensor_t object */ + memset(sensor, 0, sizeof(sensor_t)); + + # Insert the sensor name in the fixed length char array */ + strncpy (sensor->name, "TSL2561", sizeof(sensor->name) - 1); + sensor->name[sizeof(sensor->name)- 1] = 0; + sensor->version = 1; + sensor->sensor_id = _tsl2561SensorID; + sensor->type = SENSOR_TYPE_LIGHT; + sensor->min_delay = 0; + sensor->max_value = 17000.0; /* Based on trial and error ... confirm! */ + sensor->min_value = 0.0; + sensor->resolution = 1.0; +} +''' + +if __name__ == "__main__": + LightSensor = Adafruit_TSL2651() + LightSensor.enableAutoGain(True) + #while True: + # print LightSensor.calculateLux(), " Lux" + # See if "loop" has been passed as an arg. + try: + arg = sys.argv[1] + if ( arg == "loop" ): + while True: + try: + print (int(LightSensor.calculateAvgLux())) + except KeyboardInterrupt: + quit() + else: + print ("Invalid arg(s):", sys.argv) + except IndexError: + print (int(LightSensor.calculateAvgLux())) From faf21e5db479c7ce03a997a73f9b17719a02c217 Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 14:49:54 +0000 Subject: [PATCH 02/44] Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code --- Adafruit_TSL2561/Adafruit_TSL2561.py | 64 ++++++++-------------------- 1 file changed, 18 insertions(+), 46 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 2ad2b05f..b9ff2d8d 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -8,7 +8,17 @@ # The thread on the Adafruit forum helped a lot to do this. # Thanks to static, huelke, pandring, adafruit_support_rick, scortier, bryand, csalty, lenos and of course to Adafruit # Source for the Arduino library: https://github.com/adafruit/TSL2561-Arduino-Library -# Adafruit form thread:http://forums.adafruit.com/viewtopic.php?f=8&t=34922&sid=8336d566f2f03c25882aaf34c8a15a92 +# Adafruit forum thread:http://forums.adafruit.com/viewtopic.php?f=8&t=34922&sid=8336d566f2f03c25882aaf34c8a15a92 +# +# Original code posted here http://forums.adafruit.com/viewtopic.php?f=8&t=34922&start=75#p222877 +# +# Changes by Iain Colledge +# +# Removed commented out C++ code +# Added calculateAvgLux +# Changed main method to use calculateAvgLux and looping support added. +# Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code +# import sys import time @@ -124,6 +134,10 @@ class Adafruit_TSL2651(Adafruit_I2C): TSL2561_INTEGRATIONTIME_13MS = 0x00 # 13.7ms TSL2561_INTEGRATIONTIME_101MS = 0x01 # 101ms TSL2561_INTEGRATIONTIME_402MS = 0x02 # 402ms + + TSL2561_DELAY_INTTIME_13MS = 0.015 + TSL2561_DELAY_INTTIME_101MS = 0.120 + TSL2561_DELAY_INTTIME_402MS = 0.450 TSL2561_GAIN_1X = 0x00 # No gain TSL2561_GAIN_16X = 0x10 # 16x gain @@ -183,11 +197,11 @@ def getData (self): # Wait x ms for ADC to complete */ if self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS: - time.sleep(0.014) + time.sleep(TSL2561_DELAY_INTTIME_13MS) elif self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS: - time.sleep(0.102) + time.sleep(TSL2561_DELAY_INTTIME_101MS) else: - time.sleep(0.403) + time.sleep(TSL2561_DELAY_INTTIME_402MS) # Reads a two byte value from channel 0 (visible + infrared) */ @@ -483,48 +497,6 @@ def calculateAvgLux(self, testavg=int(30)): luxavg = round(luxavgtotal / testavg) return (luxavg) -''' -#**************************************************************************/ -# Gets the most recent sensor event -#**************************************************************************/ -void Adafruit_TSL2561::getEvent(sensors_event_t *event) -{ - uint16_t broadband, ir; - - # Clear the event */ - memset(event, 0, sizeof(sensors_event_t)); - - event->version = sizeof(sensors_event_t); - event->sensor_id = _tsl2561SensorID; - event->type = SENSOR_TYPE_LIGHT; - event->timestamp = 0; - - # Calculate the actual lux value */ - getLuminosity(&broadband, &ir); - event->light = calculateLux(broadband, ir); -} - -#**************************************************************************/ -# Gets the sensor_t data -#**************************************************************************/ -void Adafruit_TSL2561::getSensor(sensor_t *sensor) -{ - # Clear the sensor_t object */ - memset(sensor, 0, sizeof(sensor_t)); - - # Insert the sensor name in the fixed length char array */ - strncpy (sensor->name, "TSL2561", sizeof(sensor->name) - 1); - sensor->name[sizeof(sensor->name)- 1] = 0; - sensor->version = 1; - sensor->sensor_id = _tsl2561SensorID; - sensor->type = SENSOR_TYPE_LIGHT; - sensor->min_delay = 0; - sensor->max_value = 17000.0; /* Based on trial and error ... confirm! */ - sensor->min_value = 0.0; - sensor->resolution = 1.0; -} -''' - if __name__ == "__main__": LightSensor = Adafruit_TSL2651() LightSensor.enableAutoGain(True) From fb87a883122425f90429fc4b96d0975b89281c0b Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 14:54:04 +0000 Subject: [PATCH 03/44] Added self. to references to delay --- Adafruit_TSL2561/Adafruit_TSL2561.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index b9ff2d8d..f31a2255 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -197,11 +197,11 @@ def getData (self): # Wait x ms for ADC to complete */ if self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS: - time.sleep(TSL2561_DELAY_INTTIME_13MS) + time.sleep(self.TSL2561_DELAY_INTTIME_13MS) elif self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS: - time.sleep(TSL2561_DELAY_INTTIME_101MS) + time.sleep(self.TSL2561_DELAY_INTTIME_101MS) else: - time.sleep(TSL2561_DELAY_INTTIME_402MS) + time.sleep(self.TSL2561_DELAY_INTTIME_402MS) # Reads a two byte value from channel 0 (visible + infrared) */ From e27e9585474c21ab8463b39c90347bf54f021052 Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 15:09:29 +0000 Subject: [PATCH 04/44] Turn off autogain which defaults to 1 x gain --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index f31a2255..00afb13c 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -499,7 +499,7 @@ def calculateAvgLux(self, testavg=int(30)): if __name__ == "__main__": LightSensor = Adafruit_TSL2651() - LightSensor.enableAutoGain(True) +# LightSensor.enableAutoGain(True) #while True: # print LightSensor.calculateLux(), " Lux" # See if "loop" has been passed as an arg. From 88ae72a1afb6feb58abd9c7d833ade7c06df7d7d Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:04:39 +0000 Subject: [PATCH 05/44] Set to 16x gain --- Adafruit_TSL2561/Adafruit_TSL2561.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 00afb13c..268f4ed6 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -500,8 +500,8 @@ def calculateAvgLux(self, testavg=int(30)): if __name__ == "__main__": LightSensor = Adafruit_TSL2651() # LightSensor.enableAutoGain(True) - #while True: - # print LightSensor.calculateLux(), " Lux" + self.setGain(self.TSL2561_GAIN_16X) + # See if "loop" has been passed as an arg. try: arg = sys.argv[1] From 5e4dba34b72933f8e092c2885dd2cb6ce3aa17d1 Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:07:14 +0000 Subject: [PATCH 06/44] Typo --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 268f4ed6..f00498d5 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -500,7 +500,7 @@ def calculateAvgLux(self, testavg=int(30)): if __name__ == "__main__": LightSensor = Adafruit_TSL2651() # LightSensor.enableAutoGain(True) - self.setGain(self.TSL2561_GAIN_16X) + LightSensor.setGain(self.TSL2561_GAIN_16X) # See if "loop" has been passed as an arg. try: From b6bae177269b34b5d2c3118497950d090bcc0b8c Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:07:44 +0000 Subject: [PATCH 07/44] Typo --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index f00498d5..51622720 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -500,7 +500,7 @@ def calculateAvgLux(self, testavg=int(30)): if __name__ == "__main__": LightSensor = Adafruit_TSL2651() # LightSensor.enableAutoGain(True) - LightSensor.setGain(self.TSL2561_GAIN_16X) + LightSensor.setGain(LightSensor.TSL2561_GAIN_16X) # See if "loop" has been passed as an arg. try: From e09920d6988569b3742a951b10eb913c2366a09c Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:11:01 +0000 Subject: [PATCH 08/44] Set gain in calc average --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 51622720..b221cd9d 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -484,6 +484,7 @@ def calculateLux(self): # Calculates an averaged Lux value over default 30 samples #**************************************************************************/ def calculateAvgLux(self, testavg=int(30)): + self.setGain(self.TSL2561_GAIN_16X) # Set initial vars count = 0 luxavgtotal = 0 @@ -500,7 +501,6 @@ def calculateAvgLux(self, testavg=int(30)): if __name__ == "__main__": LightSensor = Adafruit_TSL2651() # LightSensor.enableAutoGain(True) - LightSensor.setGain(LightSensor.TSL2561_GAIN_16X) # See if "loop" has been passed as an arg. try: From ca6095ceefdd01ab49b085a244d49cfd7a5e3c3a Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:17:36 +0000 Subject: [PATCH 09/44] Fixed non reference to self for begin in setGain --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index b221cd9d..ea6d5990 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -293,7 +293,7 @@ def setIntegrationTime(self, time): def setGain(self, gain): if (self._debug == True): print "setGain" if (not self._tsl2561Initialised): - begin() + self.begin() # Enable the device by setting the control bit to 0x03 */ self.enable() From b6a4f091b029924a210827243edded059ba7a405 Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:22:39 +0000 Subject: [PATCH 10/44] Added a set gain at the start of an everageing to see if it ramps up and down ok. --- Adafruit_TSL2561/Adafruit_TSL2561.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index ea6d5990..d9bac436 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -484,7 +484,7 @@ def calculateLux(self): # Calculates an averaged Lux value over default 30 samples #**************************************************************************/ def calculateAvgLux(self, testavg=int(30)): - self.setGain(self.TSL2561_GAIN_16X) + self.setGain(self.TSL2561_GAIN_1X) # Set initial vars count = 0 luxavgtotal = 0 @@ -500,7 +500,7 @@ def calculateAvgLux(self, testavg=int(30)): if __name__ == "__main__": LightSensor = Adafruit_TSL2651() -# LightSensor.enableAutoGain(True) + LightSensor.enableAutoGain(True) # See if "loop" has been passed as an arg. try: From b687c38e306146bf515017b5713fbb4f41d951a8 Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:39:20 +0000 Subject: [PATCH 11/44] Moved the set gain to 1X at the beginning of every sample when using autogain as hack for fixing 16X to 1X not working. --- Adafruit_TSL2561/Adafruit_TSL2561.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index d9bac436..48608536 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -313,6 +313,12 @@ def setGain(self, gain): # the TSL2561, adjusting gain if auto-gain is enabled #**************************************************************************/ def getLuminosity (self): + # This is a hack to ensure that when looping with autogain the gain can go up and down as without + # setting the gain to 1X before every reading it doesn't seem able to go from 16X + # back to 1X again. Going from 1X to 16X works fine. - IC + if (self._tsl2561AutoGain): + self.setGain(self.TSL2561_GAIN_1X) + if (self._debug == True): print "getLuminosity" valid = False @@ -484,7 +490,6 @@ def calculateLux(self): # Calculates an averaged Lux value over default 30 samples #**************************************************************************/ def calculateAvgLux(self, testavg=int(30)): - self.setGain(self.TSL2561_GAIN_1X) # Set initial vars count = 0 luxavgtotal = 0 From 781a421d1557158f7ec8ecfd32a7e144b294e5fd Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:48:03 +0000 Subject: [PATCH 12/44] Set constant for number of samples for averaging --- Adafruit_TSL2561/Adafruit_TSL2561.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 48608536..7812ca93 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -18,6 +18,7 @@ # Added calculateAvgLux # Changed main method to use calculateAvgLux and looping support added. # Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code +# Added have so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work # import sys @@ -141,6 +142,8 @@ class Adafruit_TSL2651(Adafruit_I2C): TSL2561_GAIN_1X = 0x00 # No gain TSL2561_GAIN_16X = 0x10 # 16x gain + + TSL2561_NO_OF_AVG_SAMPLES = 25 # How many samples to make an average reading @@ -489,7 +492,7 @@ def calculateLux(self): #**************************************************************************/ # Calculates an averaged Lux value over default 30 samples #**************************************************************************/ - def calculateAvgLux(self, testavg=int(30)): + def calculateAvgLux(self, testavg=self.TSL2561_NO_OF_AVG_SAMPLES): # Set initial vars count = 0 luxavgtotal = 0 From ceb3b982a80f08f4110e811dc285935375ad8114 Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:50:55 +0000 Subject: [PATCH 13/44] Reference error --- Adafruit_TSL2561/Adafruit_TSL2561.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 7812ca93..051c384d 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -490,9 +490,9 @@ def calculateLux(self): return lux #**************************************************************************/ -# Calculates an averaged Lux value over default 30 samples +# Calculates an averaged Lux value over default 25 samples #**************************************************************************/ - def calculateAvgLux(self, testavg=self.TSL2561_NO_OF_AVG_SAMPLES): + def calculateAvgLux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): # Set initial vars count = 0 luxavgtotal = 0 From 335b433bfeecd23bf18f8a5d4ec879de41f75d3d Mon Sep 17 00:00:00 2001 From: iain Date: Sat, 28 Nov 2015 16:57:21 +0000 Subject: [PATCH 14/44] Typo fix --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 051c384d..ae04c69d 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -18,7 +18,7 @@ # Added calculateAvgLux # Changed main method to use calculateAvgLux and looping support added. # Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code -# Added have so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work +# Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work # import sys From 4df076b6df6de34efa908a6f4febf37daca0983e Mon Sep 17 00:00:00 2001 From: iain Date: Fri, 4 Dec 2015 15:21:46 +0000 Subject: [PATCH 15/44] Updated comments section --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index ae04c69d..df2df372 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -16,7 +16,7 @@ # # Removed commented out C++ code # Added calculateAvgLux -# Changed main method to use calculateAvgLux and looping support added. +# Changed main method to use calculateAvgLux and loop argument support added. # Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code # Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work # From 4fc5d72807f8921c4ac303bc6fbca35d7e43ccbb Mon Sep 17 00:00:00 2001 From: iain Date: Fri, 4 Dec 2015 15:26:25 +0000 Subject: [PATCH 16/44] Added checked against lux meter details --- Adafruit_TSL2561/Adafruit_TSL2561.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index df2df372..8d5b4cab 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -20,6 +20,9 @@ # Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code # Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work # +# This was checked against a £10 lux meter from Amazon and was withing 10% up and down the range, the meter +# had a stated accuracy of 5% but then again, £10 meter. +# import sys import time From 51cdf34a81a226c2080af765ada2052b3a9dcb70 Mon Sep 17 00:00:00 2001 From: iain Date: Fri, 4 Dec 2015 15:29:51 +0000 Subject: [PATCH 17/44] removed pound symbol from comments --- Adafruit_TSL2561/Adafruit_TSL2561.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 8d5b4cab..08a679b6 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -20,8 +20,8 @@ # Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code # Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work # -# This was checked against a £10 lux meter from Amazon and was withing 10% up and down the range, the meter -# had a stated accuracy of 5% but then again, £10 meter. +# This was checked against a 10 UKP lux meter from Amazon and was withing 10% up and down the range, the meter +# had a stated accuracy of 5% but then again, 10 UKP meter. # import sys From 4559bb585094975bab6322b4b058b147a59f7281 Mon Sep 17 00:00:00 2001 From: iain Date: Tue, 15 Dec 2015 15:08:51 +0000 Subject: [PATCH 18/44] Added example and fixed class name --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- Adafruit_TSL2561/Adafruit_TSL2561_example.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 Adafruit_TSL2561/Adafruit_TSL2561_example.py diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 08a679b6..7db93445 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -28,7 +28,7 @@ import time from Adafruit_I2C import Adafruit_I2C -class Adafruit_TSL2651(Adafruit_I2C): +class Adafruit_TSL2561(Adafruit_I2C): TSL2561_VISIBLE =2 # channel 0 - channel 1 TSL2561_INFRARED =1 # channel 1 TSL2561_FULLSPECTRUM =0 # channel 0 diff --git a/Adafruit_TSL2561/Adafruit_TSL2561_example.py b/Adafruit_TSL2561/Adafruit_TSL2561_example.py new file mode 100644 index 00000000..0ef804da --- /dev/null +++ b/Adafruit_TSL2561/Adafruit_TSL2561_example.py @@ -0,0 +1,15 @@ +#!/usr/bin/python + +from Adafruit_TSL2561 import Adafruit_TSL2561 + +# Initialise the sensor +LightSensor = Adafruit_TSL2561.Adafruit_TSL2651() + +# Enable auto gain switching between 1x and 16x +# Default is False +LightSensor.enableAutoGain(True) + +# Get the calculated lux value, this is a spot reading so if you're under light +# lux = Adafruit_TSL2561.calculateLux() + + From 3f3979f209f9ce461985e61842f543cf56eb6b99 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 15:18:38 +0000 Subject: [PATCH 19/44] Fixed main reference to tsl2561 class --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 7db93445..4f2544fe 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -510,7 +510,7 @@ def calculateAvgLux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): return (luxavg) if __name__ == "__main__": - LightSensor = Adafruit_TSL2651() + LightSensor = Adafruit_TSL2561() LightSensor.enableAutoGain(True) # See if "loop" has been passed as an arg. From 50ce4fde5f12dd2db41ab7759995e52f31cf82af Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 16:10:06 +0000 Subject: [PATCH 20/44] Changed read8 and read16 to use unsigned I2C methods and removed autogain hack --- .idea/dictionaries/iainc.xml | 15 ++++++++++++++ Adafruit_TSL2561/Adafruit_TSL2561.py | 29 ++++++++++++++++++---------- 2 files changed, 34 insertions(+), 10 deletions(-) create mode 100644 .idea/dictionaries/iainc.xml diff --git a/.idea/dictionaries/iainc.xml b/.idea/dictionaries/iainc.xml new file mode 100644 index 00000000..941769dd --- /dev/null +++ b/.idea/dictionaries/iainc.xml @@ -0,0 +1,15 @@ + + + + adafruit + arduino + bryand + colledge + csalty + huelke + lenos + pandring + scortier + + + \ No newline at end of file diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 4f2544fe..774c6080 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -14,15 +14,24 @@ # # Changes by Iain Colledge # -# Removed commented out C++ code -# Added calculateAvgLux -# Changed main method to use calculateAvgLux and loop argument support added. -# Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code -# Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work + # # This was checked against a 10 UKP lux meter from Amazon and was withing 10% up and down the range, the meter # had a stated accuracy of 5% but then again, 10 UKP meter. # +# Changelog: +# +# 1.1 - Fixes from https://forums.adafruit.com/viewtopic.php?f=8&t=34922&p=430795#p430782 - Iain Colledge +# Bug #1: The class name has the middle two digits transposed - Adafruit_TSL2651 should be Adafruit_TSL2561 +# Bug #2: The read8 and read16 methods (functions) call the I2C readS8 and readS16 methods respectively. +# They should call the readU8 and readU16 (i.e. unsigned) methods. +# 1.0 - Initial release - Iain Colledge +# Removed commented out C++ code +# Added calculateAvgLux +# Changed main method to use calculateAvgLux and loop argument support added. +# Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code +# Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work +# import sys import time @@ -164,7 +173,7 @@ def write8 (self, reg, value): #**************************************************************************/ def read8(self, reg): if (self._debug == True): print "read8" - return self._i2c.readS8(reg) + return self._i2c.readU8(reg) if (self._debug == True): print "read8_end" #**************************************************************************/ @@ -172,7 +181,7 @@ def read8(self, reg): #**************************************************************************/ def read16(self, reg): if (self._debug == True): print "read16" - return self._i2c.readS16(reg) + return self._i2c.readU16(reg) if (self._debug == True): print "read16_end" #**************************************************************************/ @@ -322,8 +331,8 @@ def getLuminosity (self): # This is a hack to ensure that when looping with autogain the gain can go up and down as without # setting the gain to 1X before every reading it doesn't seem able to go from 16X # back to 1X again. Going from 1X to 16X works fine. - IC - if (self._tsl2561AutoGain): - self.setGain(self.TSL2561_GAIN_1X) +# if (self._tsl2561AutoGain): +# self.setGain(self.TSL2561_GAIN_1X) if (self._debug == True): print "getLuminosity" valid = False @@ -409,7 +418,7 @@ def calculateLux(self): chScale = (1 << self.TSL2561_LUX_CHSCALE) # Scale for gain (1x or 16x) */ - if (not self._tsl2561Gain): + if (not self._tsl2561Gain): chScale = chScale << 4 # Scale the channel values */ From e2f82b100f1ddf116088e03a22c712360219ecd8 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 16:16:01 +0000 Subject: [PATCH 21/44] Removed Pycharm dictionary from commit --- Adafruit_TSL2561/Adafruit_TSL2561.py | 29 ++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 4f2544fe..774c6080 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -14,15 +14,24 @@ # # Changes by Iain Colledge # -# Removed commented out C++ code -# Added calculateAvgLux -# Changed main method to use calculateAvgLux and loop argument support added. -# Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code -# Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work + # # This was checked against a 10 UKP lux meter from Amazon and was withing 10% up and down the range, the meter # had a stated accuracy of 5% but then again, 10 UKP meter. # +# Changelog: +# +# 1.1 - Fixes from https://forums.adafruit.com/viewtopic.php?f=8&t=34922&p=430795#p430782 - Iain Colledge +# Bug #1: The class name has the middle two digits transposed - Adafruit_TSL2651 should be Adafruit_TSL2561 +# Bug #2: The read8 and read16 methods (functions) call the I2C readS8 and readS16 methods respectively. +# They should call the readU8 and readU16 (i.e. unsigned) methods. +# 1.0 - Initial release - Iain Colledge +# Removed commented out C++ code +# Added calculateAvgLux +# Changed main method to use calculateAvgLux and loop argument support added. +# Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code +# Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work +# import sys import time @@ -164,7 +173,7 @@ def write8 (self, reg, value): #**************************************************************************/ def read8(self, reg): if (self._debug == True): print "read8" - return self._i2c.readS8(reg) + return self._i2c.readU8(reg) if (self._debug == True): print "read8_end" #**************************************************************************/ @@ -172,7 +181,7 @@ def read8(self, reg): #**************************************************************************/ def read16(self, reg): if (self._debug == True): print "read16" - return self._i2c.readS16(reg) + return self._i2c.readU16(reg) if (self._debug == True): print "read16_end" #**************************************************************************/ @@ -322,8 +331,8 @@ def getLuminosity (self): # This is a hack to ensure that when looping with autogain the gain can go up and down as without # setting the gain to 1X before every reading it doesn't seem able to go from 16X # back to 1X again. Going from 1X to 16X works fine. - IC - if (self._tsl2561AutoGain): - self.setGain(self.TSL2561_GAIN_1X) +# if (self._tsl2561AutoGain): +# self.setGain(self.TSL2561_GAIN_1X) if (self._debug == True): print "getLuminosity" valid = False @@ -409,7 +418,7 @@ def calculateLux(self): chScale = (1 << self.TSL2561_LUX_CHSCALE) # Scale for gain (1x or 16x) */ - if (not self._tsl2561Gain): + if (not self._tsl2561Gain): chScale = chScale << 4 # Scale the channel values */ From 00331b762a69b24f2bb4f09bf3cdff40e8f1a34f Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 16:26:19 +0000 Subject: [PATCH 22/44] Removed Pycharm dictionary from commit --- .idea/dictionaries/iainc.xml | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 .idea/dictionaries/iainc.xml diff --git a/.idea/dictionaries/iainc.xml b/.idea/dictionaries/iainc.xml deleted file mode 100644 index 941769dd..00000000 --- a/.idea/dictionaries/iainc.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - adafruit - arduino - bryand - colledge - csalty - huelke - lenos - pandring - scortier - - - \ No newline at end of file From 947c96a377a5aa00a2e1e0a74a67a3d5531dd0a6 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 17:11:28 +0000 Subject: [PATCH 23/44] Added autogain hack back in --- Adafruit_TSL2561/Adafruit_TSL2561.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 774c6080..22e2e673 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -232,7 +232,7 @@ def getData (self): #**************************************************************************/ # Constructor #**************************************************************************/ - def __init__(self, addr=0x39, debug=False): + def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): self._debug = debug if (self._debug == True): print "__init__" self._addr = addr @@ -331,8 +331,8 @@ def getLuminosity (self): # This is a hack to ensure that when looping with autogain the gain can go up and down as without # setting the gain to 1X before every reading it doesn't seem able to go from 16X # back to 1X again. Going from 1X to 16X works fine. - IC -# if (self._tsl2561AutoGain): -# self.setGain(self.TSL2561_GAIN_1X) + if (self._tsl2561AutoGain): + self.setGain(self.TSL2561_GAIN_1X) if (self._debug == True): print "getLuminosity" valid = False From 1a61196c41c373b8f3a2be989440d3e5a602c657 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 17:27:02 +0000 Subject: [PATCH 24/44] Remove trailing / on comments and added space after = on constant definitions at start of class --- Adafruit_TSL2561/Adafruit_TSL2561.py | 208 +++++++++++++-------------- 1 file changed, 104 insertions(+), 104 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 22e2e673..ec8ca54f 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -38,97 +38,97 @@ from Adafruit_I2C import Adafruit_I2C class Adafruit_TSL2561(Adafruit_I2C): - TSL2561_VISIBLE =2 # channel 0 - channel 1 - TSL2561_INFRARED =1 # channel 1 - TSL2561_FULLSPECTRUM =0 # channel 0 + TSL2561_VISIBLE = 2 # channel 0 - channel 1 + TSL2561_INFRARED = 1 # channel 1 + TSL2561_FULLSPECTRUM = 0 # channel 0 # I2C address options - TSL2561_ADDR_LOW =0x29 - TSL2561_ADDR_FLOAT =0x39 # Default address (pin left floating) - TSL2561_ADDR_HIGH =0x49 + TSL2561_ADDR_LOW = 0x29 + TSL2561_ADDR_FLOAT = 0x39 # Default address (pin left floating) + TSL2561_ADDR_HIGH = 0x49 # Lux calculations differ slightly for CS package - TSL2561_PACKAGE_CS =0 - TSL2561_PACKAGE_T_FN_CL =1 + TSL2561_PACKAGE_CS = 0 + TSL2561_PACKAGE_T_FN_CL = 1 - TSL2561_COMMAND_BIT =0x80 # Must be 1 - TSL2561_CLEAR_BIT =0x40 # Clears any pending interrupt (write 1 to clear) - TSL2561_WORD_BIT =0x20 # 1 = read/write word (rather than byte) - TSL2561_BLOCK_BIT =0x10 # 1 = using block read/write + TSL2561_COMMAND_BIT = 0x80 # Must be 1 + TSL2561_CLEAR_BIT = 0x40 # Clears any pending interrupt (write 1 to clear) + TSL2561_WORD_BIT = 0x20 # 1 = read/write word (rather than byte) + TSL2561_BLOCK_BIT = 0x10 # 1 = using block read/write - TSL2561_CONTROL_POWERON =0x03 - TSL2561_CONTROL_POWEROFF =0x00 + TSL2561_CONTROL_POWERON = 0x03 + TSL2561_CONTROL_POWEROFF = 0x00 - TSL2561_LUX_LUXSCALE =14 # Scale by 2^14 - TSL2561_LUX_RATIOSCALE =9 # Scale ratio by 2^9 - TSL2561_LUX_CHSCALE =10 # Scale channel values by 2^10 - TSL2561_LUX_CHSCALE_TINT0 =0x7517 # 322/11 * 2^TSL2561_LUX_CHSCALE - TSL2561_LUX_CHSCALE_TINT1 =0x0FE7 # 322/81 * 2^TSL2561_LUX_CHSCALE + TSL2561_LUX_LUXSCALE = 14 # Scale by 2^14 + TSL2561_LUX_RATIOSCALE = 9 # Scale ratio by 2^9 + TSL2561_LUX_CHSCALE = 10 # Scale channel values by 2^10 + TSL2561_LUX_CHSCALE_TINT0 = 0x7517 # 322/11 * 2^TSL2561_LUX_CHSCALE + TSL2561_LUX_CHSCALE_TINT1 = 0x0FE7 # 322/81 * 2^TSL2561_LUX_CHSCALE # T, FN and CL package values - TSL2561_LUX_K1T =0x0040 # 0.125 * 2^RATIO_SCALE - TSL2561_LUX_B1T =0x01f2 # 0.0304 * 2^LUX_SCALE - TSL2561_LUX_M1T =0x01be # 0.0272 * 2^LUX_SCALE - TSL2561_LUX_K2T =0x0080 # 0.250 * 2^RATIO_SCALE - TSL2561_LUX_B2T =0x0214 # 0.0325 * 2^LUX_SCALE - TSL2561_LUX_M2T =0x02d1 # 0.0440 * 2^LUX_SCALE - TSL2561_LUX_K3T =0x00c0 # 0.375 * 2^RATIO_SCALE - TSL2561_LUX_B3T =0x023f # 0.0351 * 2^LUX_SCALE - TSL2561_LUX_M3T =0x037b # 0.0544 * 2^LUX_SCALE - TSL2561_LUX_K4T =0x0100 # 0.50 * 2^RATIO_SCALE - TSL2561_LUX_B4T =0x0270 # 0.0381 * 2^LUX_SCALE - TSL2561_LUX_M4T =0x03fe # 0.0624 * 2^LUX_SCALE - TSL2561_LUX_K5T =0x0138 # 0.61 * 2^RATIO_SCALE - TSL2561_LUX_B5T =0x016f # 0.0224 * 2^LUX_SCALE - TSL2561_LUX_M5T =0x01fc # 0.0310 * 2^LUX_SCALE - TSL2561_LUX_K6T =0x019a # 0.80 * 2^RATIO_SCALE - TSL2561_LUX_B6T =0x00d2 # 0.0128 * 2^LUX_SCALE - TSL2561_LUX_M6T =0x00fb # 0.0153 * 2^LUX_SCALE - TSL2561_LUX_K7T =0x029a # 1.3 * 2^RATIO_SCALE - TSL2561_LUX_B7T =0x0018 # 0.00146 * 2^LUX_SCALE - TSL2561_LUX_M7T =0x0012 # 0.00112 * 2^LUX_SCALE - TSL2561_LUX_K8T =0x029a # 1.3 * 2^RATIO_SCALE - TSL2561_LUX_B8T =0x0000 # 0.000 * 2^LUX_SCALE - TSL2561_LUX_M8T =0x0000 # 0.000 * 2^LUX_SCALE + TSL2561_LUX_K1T = 0x0040 # 0.125 * 2^RATIO_SCALE + TSL2561_LUX_B1T = 0x01f2 # 0.0304 * 2^LUX_SCALE + TSL2561_LUX_M1T = 0x01be # 0.0272 * 2^LUX_SCALE + TSL2561_LUX_K2T = 0x0080 # 0.250 * 2^RATIO_SCALE + TSL2561_LUX_B2T = 0x0214 # 0.0325 * 2^LUX_SCALE + TSL2561_LUX_M2T = 0x02d1 # 0.0440 * 2^LUX_SCALE + TSL2561_LUX_K3T = 0x00c0 # 0.375 * 2^RATIO_SCALE + TSL2561_LUX_B3T = 0x023f # 0.0351 * 2^LUX_SCALE + TSL2561_LUX_M3T = 0x037b # 0.0544 * 2^LUX_SCALE + TSL2561_LUX_K4T = 0x0100 # 0.50 * 2^RATIO_SCALE + TSL2561_LUX_B4T = 0x0270 # 0.0381 * 2^LUX_SCALE + TSL2561_LUX_M4T = 0x03fe # 0.0624 * 2^LUX_SCALE + TSL2561_LUX_K5T = 0x0138 # 0.61 * 2^RATIO_SCALE + TSL2561_LUX_B5T = 0x016f # 0.0224 * 2^LUX_SCALE + TSL2561_LUX_M5T = 0x01fc # 0.0310 * 2^LUX_SCALE + TSL2561_LUX_K6T = 0x019a # 0.80 * 2^RATIO_SCALE + TSL2561_LUX_B6T = 0x00d2 # 0.0128 * 2^LUX_SCALE + TSL2561_LUX_M6T = 0x00fb # 0.0153 * 2^LUX_SCALE + TSL2561_LUX_K7T = 0x029a # 1.3 * 2^RATIO_SCALE + TSL2561_LUX_B7T = 0x0018 # 0.00146 * 2^LUX_SCALE + TSL2561_LUX_M7T = 0x0012 # 0.00112 * 2^LUX_SCALE + TSL2561_LUX_K8T = 0x029a # 1.3 * 2^RATIO_SCALE + TSL2561_LUX_B8T = 0x0000 # 0.000 * 2^LUX_SCALE + TSL2561_LUX_M8T = 0x0000 # 0.000 * 2^LUX_SCALE # CS package values - TSL2561_LUX_K1C =0x0043 # 0.130 * 2^RATIO_SCALE - TSL2561_LUX_B1C =0x0204 # 0.0315 * 2^LUX_SCALE - TSL2561_LUX_M1C =0x01ad # 0.0262 * 2^LUX_SCALE - TSL2561_LUX_K2C =0x0085 # 0.260 * 2^RATIO_SCALE - TSL2561_LUX_B2C =0x0228 # 0.0337 * 2^LUX_SCALE - TSL2561_LUX_M2C =0x02c1 # 0.0430 * 2^LUX_SCALE - TSL2561_LUX_K3C =0x00c8 # 0.390 * 2^RATIO_SCALE - TSL2561_LUX_B3C =0x0253 # 0.0363 * 2^LUX_SCALE - TSL2561_LUX_M3C =0x0363 # 0.0529 * 2^LUX_SCALE - TSL2561_LUX_K4C =0x010a # 0.520 * 2^RATIO_SCALE - TSL2561_LUX_B4C =0x0282 # 0.0392 * 2^LUX_SCALE - TSL2561_LUX_M4C =0x03df # 0.0605 * 2^LUX_SCALE - TSL2561_LUX_K5C =0x014d # 0.65 * 2^RATIO_SCALE - TSL2561_LUX_B5C =0x0177 # 0.0229 * 2^LUX_SCALE - TSL2561_LUX_M5C =0x01dd # 0.0291 * 2^LUX_SCALE - TSL2561_LUX_K6C =0x019a # 0.80 * 2^RATIO_SCALE - TSL2561_LUX_B6C =0x0101 # 0.0157 * 2^LUX_SCALE - TSL2561_LUX_M6C =0x0127 # 0.0180 * 2^LUX_SCALE - TSL2561_LUX_K7C =0x029a # 1.3 * 2^RATIO_SCALE - TSL2561_LUX_B7C =0x0037 # 0.00338 * 2^LUX_SCALE - TSL2561_LUX_M7C =0x002b # 0.00260 * 2^LUX_SCALE - TSL2561_LUX_K8C =0x029a # 1.3 * 2^RATIO_SCALE - TSL2561_LUX_B8C =0x0000 # 0.000 * 2^LUX_SCALE - TSL2561_LUX_M8C =0x0000 # 0.000 * 2^LUX_SCALE + TSL2561_LUX_K1C = 0x0043 # 0.130 * 2^RATIO_SCALE + TSL2561_LUX_B1C = 0x0204 # 0.0315 * 2^LUX_SCALE + TSL2561_LUX_M1C = 0x01ad # 0.0262 * 2^LUX_SCALE + TSL2561_LUX_K2C = 0x0085 # 0.260 * 2^RATIO_SCALE + TSL2561_LUX_B2C = 0x0228 # 0.0337 * 2^LUX_SCALE + TSL2561_LUX_M2C = 0x02c1 # 0.0430 * 2^LUX_SCALE + TSL2561_LUX_K3C = 0x00c8 # 0.390 * 2^RATIO_SCALE + TSL2561_LUX_B3C = 0x0253 # 0.0363 * 2^LUX_SCALE + TSL2561_LUX_M3C = 0x0363 # 0.0529 * 2^LUX_SCALE + TSL2561_LUX_K4C = 0x010a # 0.520 * 2^RATIO_SCALE + TSL2561_LUX_B4C = 0x0282 # 0.0392 * 2^LUX_SCALE + TSL2561_LUX_M4C = 0x03df # 0.0605 * 2^LUX_SCALE + TSL2561_LUX_K5C = 0x014d # 0.65 * 2^RATIO_SCALE + TSL2561_LUX_B5C = 0x0177 # 0.0229 * 2^LUX_SCALE + TSL2561_LUX_M5C = 0x01dd # 0.0291 * 2^LUX_SCALE + TSL2561_LUX_K6C = 0x019a # 0.80 * 2^RATIO_SCALE + TSL2561_LUX_B6C = 0x0101 # 0.0157 * 2^LUX_SCALE + TSL2561_LUX_M6C = 0x0127 # 0.0180 * 2^LUX_SCALE + TSL2561_LUX_K7C = 0x029a # 1.3 * 2^RATIO_SCALE + TSL2561_LUX_B7C = 0x0037 # 0.00338 * 2^LUX_SCALE + TSL2561_LUX_M7C = 0x002b # 0.00260 * 2^LUX_SCALE + TSL2561_LUX_K8C = 0x029a # 1.3 * 2^RATIO_SCALE + TSL2561_LUX_B8C = 0x0000 # 0.000 * 2^LUX_SCALE + TSL2561_LUX_M8C = 0x0000 # 0.000 * 2^LUX_SCALE # Auto-gain thresholds - TSL2561_AGC_THI_13MS =4850 # Max value at Ti 13ms = 5047 - TSL2561_AGC_TLO_13MS =100 - TSL2561_AGC_THI_101MS =36000 # Max value at Ti 101ms = 37177 - TSL2561_AGC_TLO_101MS =200 - TSL2561_AGC_THI_402MS =63000 # Max value at Ti 402ms = 65535 - TSL2561_AGC_TLO_402MS =500 + TSL2561_AGC_THI_13MS = 4850 # Max value at Ti 13ms = 5047 + TSL2561_AGC_TLO_13MS = 100 + TSL2561_AGC_THI_101MS = 36000 # Max value at Ti 101ms = 37177 + TSL2561_AGC_TLO_101MS = 200 + TSL2561_AGC_THI_402MS = 63000 # Max value at Ti 402ms = 65535 + TSL2561_AGC_TLO_402MS = 500 # Clipping thresholds - TSL2561_CLIPPING_13MS =4900 - TSL2561_CLIPPING_101MS =37000 - TSL2561_CLIPPING_402MS =65000 + TSL2561_CLIPPING_13MS = 4900 + TSL2561_CLIPPING_101MS = 37000 + TSL2561_CLIPPING_402MS = 65000 TSL2561_REGISTER_CONTROL = 0x00 TSL2561_REGISTER_TIMING = 0x01 @@ -160,51 +160,51 @@ class Adafruit_TSL2561(Adafruit_I2C): -#**************************************************************************/ +#************************************************************************** # Writes a register and an 8 bit value over I2C -#**************************************************************************/ +#************************************************************************** def write8 (self, reg, value): if (self._debug == True): print "write8" self._i2c.write8(reg, value) if (self._debug == True): print "write8_end" -#**************************************************************************/ +#************************************************************************** # Reads an 8 bit value over I2C -#**************************************************************************/ +#************************************************************************** def read8(self, reg): if (self._debug == True): print "read8" return self._i2c.readU8(reg) if (self._debug == True): print "read8_end" -#**************************************************************************/ +#************************************************************************** # Reads a 16 bit values over I2C -#**************************************************************************/ +#************************************************************************** def read16(self, reg): if (self._debug == True): print "read16" return self._i2c.readU16(reg) if (self._debug == True): print "read16_end" -#**************************************************************************/ +#************************************************************************** # Enables the device -#**************************************************************************/ +#************************************************************************** def enable(self): if (self._debug == True): print "enable" # Enable the device by setting the control bit to 0x03 */ self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWERON) if (self._debug == True): print "enable_end" -#**************************************************************************/ +#************************************************************************** # Disables the device (putting it in lower power sleep mode) -#**************************************************************************/ +#************************************************************************** def disable(self): if (self._debug == True): print "disable" # Turn the device off to save power */ self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWEROFF) if (self._debug == True): print "disable_end" -#**************************************************************************/ +#************************************************************************** # Private function to read luminosity on both channels -#**************************************************************************/ +#************************************************************************** def getData (self): if (self._debug == True): print "getData" # Enable the device by setting the control bit to 0x03 */ @@ -229,9 +229,9 @@ def getData (self): self.disable(); if (self._debug == True): print "getData_end" -#**************************************************************************/ +#************************************************************************** # Constructor -#**************************************************************************/ +#************************************************************************** def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): self._debug = debug if (self._debug == True): print "__init__" @@ -246,10 +246,10 @@ def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): self._ir = 0 if (self._debug == True): print "__init___end" -#**************************************************************************/ +#************************************************************************** # Initializes I2C and configures the sensor (call this function before # doing anything else) -#**************************************************************************/ +#************************************************************************** def begin(self): if (self._debug == True): print "begin" # Make sure we're actually connected */ @@ -268,10 +268,10 @@ def begin(self): return True -#**************************************************************************/ +#************************************************************************** # Enables or disables the auto-gain settings when reading # data from the sensor -#**************************************************************************/ +#************************************************************************** def enableAutoGain(self, enable): if (self._debug == True): print "enableAutoGain" self._tsl2561AutoGain = enable if True else False @@ -281,9 +281,9 @@ def enableAutoGain(self, enable): self._tsl2561AutoGain = False if (self._debug == True): print "enableAutoGain_end" -#**************************************************************************/ +#************************************************************************** # Sets the integration time for the TSL2561 -#**************************************************************************/ +#************************************************************************** def setIntegrationTime(self, time): if (self._debug == True): print "setIntegrationTime" if (not self._tsl2561Initialised): @@ -302,9 +302,9 @@ def setIntegrationTime(self, time): self.disable() if (self._debug == True): print "setIntegrationTime_end" -#**************************************************************************/ +#************************************************************************** # Adjusts the gain on the TSL2561 (adjusts the sensitivity to light) -#**************************************************************************/ +#************************************************************************** def setGain(self, gain): if (self._debug == True): print "setGain" if (not self._tsl2561Initialised): @@ -323,10 +323,10 @@ def setGain(self, gain): self.disable() if (self._debug == True): print "setGain_end" -#**************************************************************************/ +#************************************************************************** # Gets the broadband (mixed lighting) and IR only values from # the TSL2561, adjusting gain if auto-gain is enabled -#**************************************************************************/ +#************************************************************************** def getLuminosity (self): # This is a hack to ensure that when looping with autogain the gain can go up and down as without # setting the gain to 1X before every reading it doesn't seem able to go from 16X @@ -390,10 +390,10 @@ def getLuminosity (self): valid = True if (self._debug == True): print "getLuminosity_end" -#**************************************************************************/ +#************************************************************************** # Converts the raw sensor values to the standard SI lux equivalent. # Returns 0 if the sensor is saturated and the values are unreliable. -#**************************************************************************/ +#************************************************************************** def calculateLux(self): if (self._debug == True): print "calculateLux" self.getLuminosity() @@ -501,9 +501,9 @@ def calculateLux(self): if (self._debug == True): print "calculateLux_end" return lux -#**************************************************************************/ +#************************************************************************** # Calculates an averaged Lux value over default 25 samples -#**************************************************************************/ +#************************************************************************** def calculateAvgLux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): # Set initial vars count = 0 From 7149f7b0b25c6779e3caa74292ed755178733888 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 18:19:26 +0000 Subject: [PATCH 25/44] Removed redundant non functioning statement from enableAutoGain --- Adafruit_TSL2561/Adafruit_TSL2561.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index ec8ca54f..559c2550 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -274,7 +274,6 @@ def begin(self): #************************************************************************** def enableAutoGain(self, enable): if (self._debug == True): print "enableAutoGain" - self._tsl2561AutoGain = enable if True else False if (enable == True): self._tsl2561AutoGain = enable else: From 3a4090b1cb69933a050acc89bbc2c5188f0a12b5 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 19:31:43 +0000 Subject: [PATCH 26/44] Converted comments to Docstrings --- Adafruit_TSL2561/Adafruit_TSL2561.py | 195 +++++++++++++++------------ 1 file changed, 110 insertions(+), 85 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 559c2550..c5136406 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -1,37 +1,34 @@ #!/usr/bin/python -# Python library for the TSL2561 digital luminosity (light) sensors. -# Version 0 - -# This library is heavily based on the Arduino library for the TSL2561 digital luminosity (light) sensors. -# It is basically a simple translation from C++ to Python. -# The thread on the Adafruit forum helped a lot to do this. -# Thanks to static, huelke, pandring, adafruit_support_rick, scortier, bryand, csalty, lenos and of course to Adafruit -# Source for the Arduino library: https://github.com/adafruit/TSL2561-Arduino-Library -# Adafruit forum thread:http://forums.adafruit.com/viewtopic.php?f=8&t=34922&sid=8336d566f2f03c25882aaf34c8a15a92 -# -# Original code posted here http://forums.adafruit.com/viewtopic.php?f=8&t=34922&start=75#p222877 -# -# Changes by Iain Colledge -# - -# -# This was checked against a 10 UKP lux meter from Amazon and was withing 10% up and down the range, the meter -# had a stated accuracy of 5% but then again, 10 UKP meter. -# -# Changelog: -# -# 1.1 - Fixes from https://forums.adafruit.com/viewtopic.php?f=8&t=34922&p=430795#p430782 - Iain Colledge -# Bug #1: The class name has the middle two digits transposed - Adafruit_TSL2651 should be Adafruit_TSL2561 -# Bug #2: The read8 and read16 methods (functions) call the I2C readS8 and readS16 methods respectively. -# They should call the readU8 and readU16 (i.e. unsigned) methods. -# 1.0 - Initial release - Iain Colledge -# Removed commented out C++ code -# Added calculateAvgLux -# Changed main method to use calculateAvgLux and loop argument support added. -# Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code -# Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work -# +""" +Python library for the TSL2561 digital luminosity (light) sensors. + +This library is heavily based on the Arduino library for the TSL2561 digital luminosity (light) sensors. +It is basically a simple translation from C++ to Python. +The thread on the Adafruit forum helped a lot to do this. +Thanks to static, huelke, pandring, adafruit_support_rick, scortier, bryand, csalty, lenos and of course to Adafruit +Source for the Arduino library: https://github.com/adafruit/TSL2561-Arduino-Library +Adafruit forum thread:http://forums.adafruit.com/viewtopic.php?f=8&t=34922&sid=8336d566f2f03c25882aaf34c8a15a92 + +Original code posted here http://forums.adafruit.com/viewtopic.php?f=8&t=34922&start=75#p222877 + +This was checked against a 10 UKP lux meter from Amazon and was withing 10% up and down the range, the meter +had a stated accuracy of 5% but then again, 10 UKP meter. + +Changelog: + +1.1 - Fixes from https://forums.adafruit.com/viewtopic.php?f=8&t=34922&p=430795#p430782 - Iain Colledge + Bug #1: The class name has the middle two digits transposed - Adafruit_TSL2651 should be Adafruit_TSL2561 + Bug #2: The read8 and read16 methods (functions) call the I2C readS8 and readS16 methods respectively. + They should call the readU8 and readU16 (i.e. unsigned) methods. + Minor fixes and changes + 1.0 - Initial release - Iain Colledge + Removed commented out C++ code + Added calculateAvgLux + Changed main method to use calculateAvgLux and loop argument support added. + Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code + Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work +""" import sys import time @@ -157,57 +154,64 @@ class Adafruit_TSL2561(Adafruit_I2C): TSL2561_NO_OF_AVG_SAMPLES = 25 # How many samples to make an average reading - - - -#************************************************************************** -# Writes a register and an 8 bit value over I2C -#************************************************************************** def write8 (self, reg, value): + """ + Writes a register and an 8 bit value over I2C + + :param reg: Register / Address to write value to + :param value: Byte to write to Address + """ if (self._debug == True): print "write8" self._i2c.write8(reg, value) if (self._debug == True): print "write8_end" -#************************************************************************** -# Reads an 8 bit value over I2C -#************************************************************************** def read8(self, reg): + """ + Reads an 8 bit value over I2C + + :param reg: Register / Address to read value from + :return: Unsigned byte + """ if (self._debug == True): print "read8" return self._i2c.readU8(reg) if (self._debug == True): print "read8_end" -#************************************************************************** -# Reads a 16 bit values over I2C -#************************************************************************** def read16(self, reg): + """ + Reads a 16 bit values over I2C + + :param reg: Register / Address to read value from + :return: Unsigned word + """ if (self._debug == True): print "read16" return self._i2c.readU16(reg) if (self._debug == True): print "read16_end" -#************************************************************************** -# Enables the device -#************************************************************************** def enable(self): + """ + Enables the device + """ if (self._debug == True): print "enable" # Enable the device by setting the control bit to 0x03 */ self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWERON) if (self._debug == True): print "enable_end" -#************************************************************************** -# Disables the device (putting it in lower power sleep mode) -#************************************************************************** def disable(self): + """ + Disables the device (putting it in lower power sleep mode) + """ if (self._debug == True): print "disable" # Turn the device off to save power */ self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWEROFF) if (self._debug == True): print "disable_end" -#************************************************************************** -# Private function to read luminosity on both channels -#************************************************************************** def getData (self): + """ + Private function to read luminosity on both channels + """ if (self._debug == True): print "getData" - # Enable the device by setting the control bit to 0x03 */ + + #Enables the device by setting the control bit to 0x03 self.enable(); # Wait x ms for ADC to complete */ @@ -229,10 +233,13 @@ def getData (self): self.disable(); if (self._debug == True): print "getData_end" -#************************************************************************** -# Constructor -#************************************************************************** def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): + """ + Constructor + + :param addr: I2C address of TSL2561, defaults to 0x39 + :param debug: Turn on debugging, defaults to False + """ self._debug = debug if (self._debug == True): print "__init__" self._addr = addr @@ -246,11 +253,15 @@ def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): self._ir = 0 if (self._debug == True): print "__init___end" -#************************************************************************** -# Initializes I2C and configures the sensor (call this function before -# doing anything else) -#************************************************************************** def begin(self): + """ + Initializes I2C and configures the sensor (call this function before + doing anything else) + + Note: by default, the device is in power down mode on bootup + + :return: True if connected to a TSL2561 + """ if (self._debug == True): print "begin" # Make sure we're actually connected */ x = self.read8(self.TSL2561_REGISTER_ID); @@ -268,11 +279,13 @@ def begin(self): return True -#************************************************************************** -# Enables or disables the auto-gain settings when reading -# data from the sensor -#************************************************************************** def enableAutoGain(self, enable): + """ + Enables or disables the auto-gain settings when reading + data from the sensor + + :param enable: True to enable + """ if (self._debug == True): print "enableAutoGain" if (enable == True): self._tsl2561AutoGain = enable @@ -280,13 +293,16 @@ def enableAutoGain(self, enable): self._tsl2561AutoGain = False if (self._debug == True): print "enableAutoGain_end" -#************************************************************************** -# Sets the integration time for the TSL2561 -#************************************************************************** def setIntegrationTime(self, time): + """ + Sets the integration time for the TSL2561 + + :param time: + :return: + """ if (self._debug == True): print "setIntegrationTime" if (not self._tsl2561Initialised): - self.begin() + self.begin # Enable the device by setting the control bit to 0x03 */ self.enable(); @@ -301,13 +317,15 @@ def setIntegrationTime(self, time): self.disable() if (self._debug == True): print "setIntegrationTime_end" -#************************************************************************** -# Adjusts the gain on the TSL2561 (adjusts the sensitivity to light) -#************************************************************************** def setGain(self, gain): + """ + Adjusts the gain on the TSL2561 (adjusts the sensitivity to light) + + :param gain: + """ if (self._debug == True): print "setGain" if (not self._tsl2561Initialised): - self.begin() + self.begin # Enable the device by setting the control bit to 0x03 */ self.enable() @@ -322,11 +340,12 @@ def setGain(self, gain): self.disable() if (self._debug == True): print "setGain_end" -#************************************************************************** -# Gets the broadband (mixed lighting) and IR only values from -# the TSL2561, adjusting gain if auto-gain is enabled -#************************************************************************** def getLuminosity (self): + """ + Gets the broadband (mixed lighting) and IR only values from + the TSL2561, adjusting gain if auto-gain is enabled + + """ # This is a hack to ensure that when looping with autogain the gain can go up and down as without # setting the gain to 1X before every reading it doesn't seem able to go from 16X # back to 1X again. Going from 1X to 16X works fine. - IC @@ -337,7 +356,7 @@ def getLuminosity (self): valid = False if (not self._tsl2561Initialised): - self.begin() + self.begin # If Auto gain disabled get a single reading and continue */ if(not self._tsl2561AutoGain): @@ -389,11 +408,13 @@ def getLuminosity (self): valid = True if (self._debug == True): print "getLuminosity_end" -#************************************************************************** -# Converts the raw sensor values to the standard SI lux equivalent. -# Returns 0 if the sensor is saturated and the values are unreliable. -#************************************************************************** def calculateLux(self): + """ + Converts the raw sensor values to the standard SI lux equivalent. + Returns 0 if the sensor is saturated and the values are unreliable. + + :return: lux value, unsigned 16bit word (0 - 65535) + """ if (self._debug == True): print "calculateLux" self.getLuminosity() # Make sure the sensor isn't saturated! */ @@ -405,6 +426,7 @@ def calculateLux(self): clipThreshold = self.TSL2561_CLIPPING_402MS # Return 0 lux if the sensor is saturated */ + # TODO: Throw an exception rather than return 0 if ((self._broadband > clipThreshold) or (self._ir > clipThreshold)): return 0 @@ -500,10 +522,13 @@ def calculateLux(self): if (self._debug == True): print "calculateLux_end" return lux -#************************************************************************** -# Calculates an averaged Lux value over default 25 samples -#************************************************************************** def calculateAvgLux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): + """ + Calculates an averaged Lux value, useful for flickering lights and for smoothing values due to noise + + :param testavg: Number of samples to take in a reading, defaults to 25 + :return: lux value, unsigned 16bit word (0 - 65535) + """ # Set initial vars count = 0 luxavgtotal = 0 From bb0be79631228ab6712415076f7221bb043a1278 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 20:31:16 +0000 Subject: [PATCH 27/44] PEP 8 convention changes --- Adafruit_TSL2561/Adafruit_TSL2561.py | 136 +++++++++---------- Adafruit_TSL2561/Adafruit_TSL2561_example.py | 6 +- 2 files changed, 71 insertions(+), 71 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index c5136406..02cfc649 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -24,8 +24,8 @@ Minor fixes and changes 1.0 - Initial release - Iain Colledge Removed commented out C++ code - Added calculateAvgLux - Changed main method to use calculateAvgLux and loop argument support added. + Added calculate_avg_lux + Changed main method to use calculate_avg_lux and loop argument support added. Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work """ @@ -34,7 +34,8 @@ import time from Adafruit_I2C import Adafruit_I2C -class Adafruit_TSL2561(Adafruit_I2C): + +class AdafruitTSL2561(Adafruit_I2C): TSL2561_VISIBLE = 2 # channel 0 - channel 1 TSL2561_INFRARED = 1 # channel 1 TSL2561_FULLSPECTRUM = 0 # channel 0 @@ -87,7 +88,7 @@ class Adafruit_TSL2561(Adafruit_I2C): TSL2561_LUX_K8T = 0x029a # 1.3 * 2^RATIO_SCALE TSL2561_LUX_B8T = 0x0000 # 0.000 * 2^LUX_SCALE TSL2561_LUX_M8T = 0x0000 # 0.000 * 2^LUX_SCALE - + # CS package values TSL2561_LUX_K1C = 0x0043 # 0.130 * 2^RATIO_SCALE TSL2561_LUX_B1C = 0x0204 # 0.0315 * 2^LUX_SCALE @@ -140,7 +141,7 @@ class Adafruit_TSL2561(Adafruit_I2C): TSL2561_REGISTER_CHAN0_HIGH = 0x0D TSL2561_REGISTER_CHAN1_LOW = 0x0E TSL2561_REGISTER_CHAN1_HIGH = 0x0F - + TSL2561_INTEGRATIONTIME_13MS = 0x00 # 13.7ms TSL2561_INTEGRATIONTIME_101MS = 0x01 # 101ms TSL2561_INTEGRATIONTIME_402MS = 0x02 # 402ms @@ -148,13 +149,13 @@ class Adafruit_TSL2561(Adafruit_I2C): TSL2561_DELAY_INTTIME_13MS = 0.015 TSL2561_DELAY_INTTIME_101MS = 0.120 TSL2561_DELAY_INTTIME_402MS = 0.450 - + TSL2561_GAIN_1X = 0x00 # No gain TSL2561_GAIN_16X = 0x10 # 16x gain TSL2561_NO_OF_AVG_SAMPLES = 25 # How many samples to make an average reading - - def write8 (self, reg, value): + + def write8(self, reg, value): """ Writes a register and an 8 bit value over I2C @@ -205,32 +206,31 @@ def disable(self): self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWEROFF) if (self._debug == True): print "disable_end" - def getData (self): + def get_data(self): """ Private function to read luminosity on both channels """ - if (self._debug == True): print "getData" + if (self._debug == True): print "get_data" - #Enables the device by setting the control bit to 0x03 - self.enable(); + # Enables the device by setting the control bit to 0x03 + self.enable() # Wait x ms for ADC to complete */ if self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS: time.sleep(self.TSL2561_DELAY_INTTIME_13MS) elif self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS: - time.sleep(self.TSL2561_DELAY_INTTIME_101MS) + time.sleep(self.TSL2561_DELAY_INTTIME_101MS) else: - time.sleep(self.TSL2561_DELAY_INTTIME_402MS) - + time.sleep(self.TSL2561_DELAY_INTTIME_402MS) # Reads a two byte value from channel 0 (visible + infrared) */ - self._broadband = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN0_LOW); + self._broadband = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN0_LOW) # Reads a two byte value from channel 1 (infrared) */ - self._ir = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN1_LOW); + self._ir = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN1_LOW) # Turn the device off to save power */ - self.disable(); + self.disable() if (self._debug == True): print "getData_end" def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): @@ -264,48 +264,48 @@ def begin(self): """ if (self._debug == True): print "begin" # Make sure we're actually connected */ - x = self.read8(self.TSL2561_REGISTER_ID); + x = self.read8(self.TSL2561_REGISTER_ID) if not(x & 0x0A): return False self._tsl2561Initialised = True # Set default integration time and gain */ - self.setIntegrationTime(self._tsl2561IntegrationTime) - self.setGain(self._tsl2561Gain) + self.set_integration_time(self._tsl2561IntegrationTime) + self.set_gain(self._tsl2561Gain) # Note: by default, the device is in power down mode on bootup */ self.disable() if (self._debug == True): print "begin_end" return True - - def enableAutoGain(self, enable): + + def enable_auto_gain(self, enable): """ Enables or disables the auto-gain settings when reading data from the sensor :param enable: True to enable """ - if (self._debug == True): print "enableAutoGain" + if (self._debug == True): print "enable_auto_gain" if (enable == True): self._tsl2561AutoGain = enable else: self._tsl2561AutoGain = False if (self._debug == True): print "enableAutoGain_end" - def setIntegrationTime(self, time): + def set_integration_time(self, time): """ Sets the integration time for the TSL2561 :param time: :return: """ - if (self._debug == True): print "setIntegrationTime" + if (self._debug == True): print "set_integration_time" if (not self._tsl2561Initialised): self.begin # Enable the device by setting the control bit to 0x03 */ - self.enable(); + self.enable() # Update the timing register */ self.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_TIMING, time | self._tsl2561Gain) @@ -316,14 +316,14 @@ def setIntegrationTime(self, time): # Turn the device off to save power */ self.disable() if (self._debug == True): print "setIntegrationTime_end" - - def setGain(self, gain): + + def set_gain(self, gain): """ Adjusts the gain on the TSL2561 (adjusts the sensitivity to light) :param gain: """ - if (self._debug == True): print "setGain" + if (self._debug == True): print "set_gain" if (not self._tsl2561Initialised): self.begin @@ -340,7 +340,7 @@ def setGain(self, gain): self.disable() if (self._debug == True): print "setGain_end" - def getLuminosity (self): + def get_luminosity(self): """ Gets the broadband (mixed lighting) and IR only values from the TSL2561, adjusting gain if auto-gain is enabled @@ -350,23 +350,23 @@ def getLuminosity (self): # setting the gain to 1X before every reading it doesn't seem able to go from 16X # back to 1X again. Going from 1X to 16X works fine. - IC if (self._tsl2561AutoGain): - self.setGain(self.TSL2561_GAIN_1X) + self.set_gain(self.TSL2561_GAIN_1X) - if (self._debug == True): print "getLuminosity" + if (self._debug == True): print "get_luminosity" valid = False if (not self._tsl2561Initialised): - self.begin + self.begin # If Auto gain disabled get a single reading and continue */ if(not self._tsl2561AutoGain): - self.getData() + self.get_data() return # Read data until we find a valid range */ _agcCheck = False while (not valid): - _it = self._tsl2561IntegrationTime; + _it = self._tsl2561IntegrationTime # Get the hi/low threshold for the current integration time */ if _it==self.TSL2561_INTEGRATIONTIME_13MS: @@ -379,22 +379,22 @@ def getLuminosity (self): _hi = self.TSL2561_AGC_THI_402MS _lo = self.TSL2561_AGC_TLO_402MS - self.getData() + self.get_data() # Run an auto-gain check if we haven't already done so ... */ if (not _agcCheck): if ((self._broadband < _lo) and (self._tsl2561Gain == self.TSL2561_GAIN_1X)): # Increase the gain and try again */ - self.setGain(self.TSL2561_GAIN_16X) + self.set_gain(self.TSL2561_GAIN_16X) # Drop the previous conversion results */ - self.getData() + self.get_data() # Set a flag to indicate we've adjusted the gain */ _agcCheck = True elif ((self._broadband > _hi) and (self._tsl2561Gain == self.TSL2561_GAIN_16X)): # Drop gain to 1x and try again */ - self.setGain(self.TSL2561_GAIN_1X) + self.set_gain(self.TSL2561_GAIN_1X) # Drop the previous conversion results */ - self.getData() + self.get_data() # Set a flag to indicate we've adjusted the gain */ _agcCheck = True else: @@ -407,49 +407,49 @@ def getLuminosity (self): # and the the other extreme post-gain */ valid = True if (self._debug == True): print "getLuminosity_end" - - def calculateLux(self): + + def calculate_lux(self): """ Converts the raw sensor values to the standard SI lux equivalent. Returns 0 if the sensor is saturated and the values are unreliable. :return: lux value, unsigned 16bit word (0 - 65535) """ - if (self._debug == True): print "calculateLux" - self.getLuminosity() + if (self._debug == True): print "calculate_lux" + self.get_luminosity() # Make sure the sensor isn't saturated! */ if (self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS): - clipThreshold = self.TSL2561_CLIPPING_13MS + clip_threshold = self.TSL2561_CLIPPING_13MS elif (self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS): - clipThreshold = self.TSL2561_CLIPPING_101MS + clip_threshold = self.TSL2561_CLIPPING_101MS else: - clipThreshold = self.TSL2561_CLIPPING_402MS + clip_threshold = self.TSL2561_CLIPPING_402MS # Return 0 lux if the sensor is saturated */ # TODO: Throw an exception rather than return 0 - if ((self._broadband > clipThreshold) or (self._ir > clipThreshold)): + if ((self._broadband > clip_threshold) or (self._ir > clip_threshold)): return 0 # Get the correct scale depending on the intergration time */ if (self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_13MS): - chScale = self.TSL2561_LUX_CHSCALE_TINT0 + ch_scale = self.TSL2561_LUX_CHSCALE_TINT0 elif (self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_101MS): - chScale = self.TSL2561_LUX_CHSCALE_TINT1 + ch_scale = self.TSL2561_LUX_CHSCALE_TINT1 else: - chScale = (1 << self.TSL2561_LUX_CHSCALE) + ch_scale = (1 << self.TSL2561_LUX_CHSCALE) # Scale for gain (1x or 16x) */ if (not self._tsl2561Gain): - chScale = chScale << 4 + ch_scale = ch_scale << 4 # Scale the channel values */ - channel0 = (self._broadband * chScale) >> self.TSL2561_LUX_CHSCALE - channel1 = (self._ir * chScale) >> self.TSL2561_LUX_CHSCALE + channel0 = (self._broadband * ch_scale) >> self.TSL2561_LUX_CHSCALE + channel1 = (self._ir * ch_scale) >> self.TSL2561_LUX_CHSCALE # Find the ratio of the channel values (Channel1/Channel0) */ - ratio1 = 0; + ratio1 = 0 if (channel0 != 0): - ratio1 = (channel1 << (self.TSL2561_LUX_RATIOSCALE+1)) / channel0 + ratio1 = (channel1 << (self.TSL2561_LUX_RATIOSCALE + 1)) / channel0 # round the ratio value */ ratio = (ratio1 + 1) >> 1 @@ -504,25 +504,25 @@ def calculateLux(self): elif (ratio > self.TSL2561_LUX_K8T): b=self.TSL2561_LUX_B8T m=self.TSL2561_LUX_M8T - #endif + # endif temp = ((channel0 * b) - (channel1 * m)) # Do not allow negative lux value */ - if (temp < 0): + if (temp < 0): temp = 0 # Round lsb (2^(LUX_SCALE-1)) */ - temp += (1 << (self.TSL2561_LUX_LUXSCALE-1)) + temp += (1 << (self.TSL2561_LUX_LUXSCALE - 1)) # Strip off fractional portion */ - lux = temp >> self.TSL2561_LUX_LUXSCALE; + lux = temp >> self.TSL2561_LUX_LUXSCALE # Signal I2C had no errors */ if (self._debug == True): print "calculateLux_end" return lux - def calculateAvgLux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): + def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): """ Calculates an averaged Lux value, useful for flickering lights and for smoothing values due to noise @@ -534,28 +534,28 @@ def calculateAvgLux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): luxavgtotal = 0 # Create a cumulative total of values for 'testavg' tests while True: - capture = self.calculateLux() + capture = self.calculate_lux() luxavgtotal = capture + luxavgtotal count += 1 # Once we reach the number of required tests, work out the average - if ( count >= testavg ): + if (count >= testavg): luxavg = round(luxavgtotal / testavg) return (luxavg) if __name__ == "__main__": LightSensor = Adafruit_TSL2561() - LightSensor.enableAutoGain(True) + LightSensor.enable_auto_gain(True) # See if "loop" has been passed as an arg. try: arg = sys.argv[1] - if ( arg == "loop" ): + if (arg == "loop"): while True: try: - print (int(LightSensor.calculateAvgLux())) + print (int(LightSensor.calculate_avg_lux())) except KeyboardInterrupt: quit() else: print ("Invalid arg(s):", sys.argv) except IndexError: - print (int(LightSensor.calculateAvgLux())) + print (int(LightSensor.calculate_avg_lux())) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561_example.py b/Adafruit_TSL2561/Adafruit_TSL2561_example.py index 0ef804da..93049cb5 100644 --- a/Adafruit_TSL2561/Adafruit_TSL2561_example.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561_example.py @@ -3,13 +3,13 @@ from Adafruit_TSL2561 import Adafruit_TSL2561 # Initialise the sensor -LightSensor = Adafruit_TSL2561.Adafruit_TSL2651() +LightSensor = Adafruit_TSL2561.AdafruitTSL2651() # Enable auto gain switching between 1x and 16x # Default is False -LightSensor.enableAutoGain(True) +LightSensor.enable_auto_gain(True) # Get the calculated lux value, this is a spot reading so if you're under light -# lux = Adafruit_TSL2561.calculateLux() +# lux = Adafruit_TSL2561.calculate_lux() From 6306a0a6de8f925a6f4e7188a2a5219bd98737e2 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 20:38:14 +0000 Subject: [PATCH 28/44] Fixed changed class reference --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 02cfc649..f3921148 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -543,7 +543,7 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): return (luxavg) if __name__ == "__main__": - LightSensor = Adafruit_TSL2561() + LightSensor = AdafruitTSL2561() LightSensor.enable_auto_gain(True) # See if "loop" has been passed as an arg. From 63c507b9646ab7fe750f012109063caf4cdea2e0 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 20:48:38 +0000 Subject: [PATCH 29/44] Removed redundant parentheses --- Adafruit_TSL2561/Adafruit_TSL2561.py | 130 +++++++++++++-------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index f3921148..2be032e7 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -162,9 +162,9 @@ def write8(self, reg, value): :param reg: Register / Address to write value to :param value: Byte to write to Address """ - if (self._debug == True): print "write8" + if self._debug == True: print "write8" self._i2c.write8(reg, value) - if (self._debug == True): print "write8_end" + if self._debug == True: print "write8_end" def read8(self, reg): """ @@ -173,9 +173,9 @@ def read8(self, reg): :param reg: Register / Address to read value from :return: Unsigned byte """ - if (self._debug == True): print "read8" + if self._debug == True: print "read8" return self._i2c.readU8(reg) - if (self._debug == True): print "read8_end" + if self._debug == True: print "read8_end" def read16(self, reg): """ @@ -184,33 +184,33 @@ def read16(self, reg): :param reg: Register / Address to read value from :return: Unsigned word """ - if (self._debug == True): print "read16" + if self._debug == True: print "read16" return self._i2c.readU16(reg) - if (self._debug == True): print "read16_end" + if self._debug == True: print "read16_end" def enable(self): """ Enables the device """ - if (self._debug == True): print "enable" + if self._debug == True: print "enable" # Enable the device by setting the control bit to 0x03 */ self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWERON) - if (self._debug == True): print "enable_end" + if self._debug == True: print "enable_end" def disable(self): """ Disables the device (putting it in lower power sleep mode) """ - if (self._debug == True): print "disable" + if self._debug == True: print "disable" # Turn the device off to save power */ self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWEROFF) - if (self._debug == True): print "disable_end" + if self._debug == True: print "disable_end" def get_data(self): """ Private function to read luminosity on both channels """ - if (self._debug == True): print "get_data" + if self._debug == True: print "get_data" # Enables the device by setting the control bit to 0x03 self.enable() @@ -231,7 +231,7 @@ def get_data(self): # Turn the device off to save power */ self.disable() - if (self._debug == True): print "getData_end" + if self._debug == True: print "getData_end" def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): """ @@ -241,7 +241,7 @@ def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): :param debug: Turn on debugging, defaults to False """ self._debug = debug - if (self._debug == True): print "__init__" + if self._debug == True: print "__init__" self._addr = addr self._tsl2561Initialised = False self._tsl2561AutoGain = False @@ -251,7 +251,7 @@ def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): self._luminosity = 0 self._broadband = 0 self._ir = 0 - if (self._debug == True): print "__init___end" + if self._debug == True: print "__init___end" def begin(self): """ @@ -262,7 +262,7 @@ def begin(self): :return: True if connected to a TSL2561 """ - if (self._debug == True): print "begin" + if self._debug == True: print "begin" # Make sure we're actually connected */ x = self.read8(self.TSL2561_REGISTER_ID) if not(x & 0x0A): @@ -275,7 +275,7 @@ def begin(self): # Note: by default, the device is in power down mode on bootup */ self.disable() - if (self._debug == True): print "begin_end" + if self._debug == True: print "begin_end" return True @@ -286,12 +286,12 @@ def enable_auto_gain(self, enable): :param enable: True to enable """ - if (self._debug == True): print "enable_auto_gain" - if (enable == True): + if self._debug == True: print "enable_auto_gain" + if enable == True: self._tsl2561AutoGain = enable else: self._tsl2561AutoGain = False - if (self._debug == True): print "enableAutoGain_end" + if self._debug == True: print "enableAutoGain_end" def set_integration_time(self, time): """ @@ -300,8 +300,8 @@ def set_integration_time(self, time): :param time: :return: """ - if (self._debug == True): print "set_integration_time" - if (not self._tsl2561Initialised): + if self._debug == True: print "set_integration_time" + if not self._tsl2561Initialised: self.begin # Enable the device by setting the control bit to 0x03 */ @@ -315,7 +315,7 @@ def set_integration_time(self, time): # Turn the device off to save power */ self.disable() - if (self._debug == True): print "setIntegrationTime_end" + if self._debug == True: print "setIntegrationTime_end" def set_gain(self, gain): """ @@ -323,8 +323,8 @@ def set_gain(self, gain): :param gain: """ - if (self._debug == True): print "set_gain" - if (not self._tsl2561Initialised): + if self._debug == True: print "set_gain" + if not self._tsl2561Initialised: self.begin # Enable the device by setting the control bit to 0x03 */ @@ -338,7 +338,7 @@ def set_gain(self, gain): # Turn the device off to save power */ self.disable() - if (self._debug == True): print "setGain_end" + if self._debug == True: print "setGain_end" def get_luminosity(self): """ @@ -349,23 +349,23 @@ def get_luminosity(self): # This is a hack to ensure that when looping with autogain the gain can go up and down as without # setting the gain to 1X before every reading it doesn't seem able to go from 16X # back to 1X again. Going from 1X to 16X works fine. - IC - if (self._tsl2561AutoGain): + if self._tsl2561AutoGain: self.set_gain(self.TSL2561_GAIN_1X) - if (self._debug == True): print "get_luminosity" + if self._debug == True: print "get_luminosity" valid = False - if (not self._tsl2561Initialised): + if not self._tsl2561Initialised: self.begin # If Auto gain disabled get a single reading and continue */ - if(not self._tsl2561AutoGain): + if not self._tsl2561AutoGain: self.get_data() return # Read data until we find a valid range */ _agcCheck = False - while (not valid): + while not valid: _it = self._tsl2561IntegrationTime # Get the hi/low threshold for the current integration time */ @@ -382,15 +382,15 @@ def get_luminosity(self): self.get_data() # Run an auto-gain check if we haven't already done so ... */ - if (not _agcCheck): - if ((self._broadband < _lo) and (self._tsl2561Gain == self.TSL2561_GAIN_1X)): + if not _agcCheck: + if (self._broadband < _lo) and (self._tsl2561Gain == self.TSL2561_GAIN_1X): # Increase the gain and try again */ self.set_gain(self.TSL2561_GAIN_16X) # Drop the previous conversion results */ self.get_data() # Set a flag to indicate we've adjusted the gain */ _agcCheck = True - elif ((self._broadband > _hi) and (self._tsl2561Gain == self.TSL2561_GAIN_16X)): + elif (self._broadband > _hi) and (self._tsl2561Gain == self.TSL2561_GAIN_16X): # Drop gain to 1x and try again */ self.set_gain(self.TSL2561_GAIN_1X) # Drop the previous conversion results */ @@ -406,7 +406,7 @@ def get_luminosity(self): # This avoids endless loops where a value is at one extreme pre-gain, # and the the other extreme post-gain */ valid = True - if (self._debug == True): print "getLuminosity_end" + if self._debug == True: print "getLuminosity_end" def calculate_lux(self): """ @@ -415,31 +415,31 @@ def calculate_lux(self): :return: lux value, unsigned 16bit word (0 - 65535) """ - if (self._debug == True): print "calculate_lux" + if self._debug == True: print "calculate_lux" self.get_luminosity() # Make sure the sensor isn't saturated! */ - if (self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS): + if self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS: clip_threshold = self.TSL2561_CLIPPING_13MS - elif (self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS): + elif self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS: clip_threshold = self.TSL2561_CLIPPING_101MS else: clip_threshold = self.TSL2561_CLIPPING_402MS # Return 0 lux if the sensor is saturated */ # TODO: Throw an exception rather than return 0 - if ((self._broadband > clip_threshold) or (self._ir > clip_threshold)): + if (self._broadband > clip_threshold) or (self._ir > clip_threshold): return 0 # Get the correct scale depending on the intergration time */ - if (self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_13MS): + if self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_13MS: ch_scale = self.TSL2561_LUX_CHSCALE_TINT0 - elif (self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_101MS): + elif self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_101MS: ch_scale = self.TSL2561_LUX_CHSCALE_TINT1 else: ch_scale = (1 << self.TSL2561_LUX_CHSCALE) # Scale for gain (1x or 16x) */ - if (not self._tsl2561Gain): + if not self._tsl2561Gain: ch_scale = ch_scale << 4 # Scale the channel values */ @@ -448,60 +448,60 @@ def calculate_lux(self): # Find the ratio of the channel values (Channel1/Channel0) */ ratio1 = 0 - if (channel0 != 0): + if channel0 != 0: ratio1 = (channel1 << (self.TSL2561_LUX_RATIOSCALE + 1)) / channel0 # round the ratio value */ ratio = (ratio1 + 1) >> 1 - if (self.TSL2561_PACKAGE_CS == 1): - if ((ratio >= 0) and (ratio <= self.TSL2561_LUX_K1C)): + if self.TSL2561_PACKAGE_CS == 1: + if (ratio >= 0) and (ratio <= self.TSL2561_LUX_K1C): b=self.TSL2561_LUX_B1C m=self.TSL2561_LUX_M1C - elif (ratio <= self.TSL2561_LUX_K2C): + elif ratio <= self.TSL2561_LUX_K2C: b=self.TSL2561_LUX_B2C m=self.TSL2561_LUX_M2C - elif (ratio <= self.TSL2561_LUX_K3C): + elif ratio <= self.TSL2561_LUX_K3C: b=self.TSL2561_LUX_B3C m=self.TSL2561_LUX_M3C - elif (ratio <= self.TSL2561_LUX_K4C): + elif ratio <= self.TSL2561_LUX_K4C: b=self.TSL2561_LUX_B4C m=self.TSL2561_LUX_M4C - elif (ratio <= self.TSL2561_LUX_K5C): + elif ratio <= self.TSL2561_LUX_K5C: b=self.TSL2561_LUX_B5C m=self.TSL2561_LUX_M5C - elif (ratio <= self.TSL2561_LUX_K6C): + elif ratio <= self.TSL2561_LUX_K6C: b=self.TSL2561_LUX_B6C m=self.TSL2561_LUX_M6C - elif (ratio <= self.TSL2561_LUX_K7C): + elif ratio <= self.TSL2561_LUX_K7C: b=self.TSL2561_LUX_B7C m=self.TSL2561_LUX_M7C - elif (ratio > self.TSL2561_LUX_K8C): + elif ratio > self.TSL2561_LUX_K8C: b=self.TSL2561_LUX_B8C m=self.TSL2561_LUX_M8C - elif (self.TSL2561_PACKAGE_T_FN_CL == 1): - if ((ratio >= 0) and (ratio <= self.TSL2561_LUX_K1T)): + elif self.TSL2561_PACKAGE_T_FN_CL == 1: + if (ratio >= 0) and (ratio <= self.TSL2561_LUX_K1T): b=self.TSL2561_LUX_B1T m=self.TSL2561_LUX_M1T - elif (ratio <= self.TSL2561_LUX_K2T): + elif ratio <= self.TSL2561_LUX_K2T: b=self.TSL2561_LUX_B2T m=self.TSL2561_LUX_M2T - elif (ratio <= self.TSL2561_LUX_K3T): + elif ratio <= self.TSL2561_LUX_K3T: b=self.TSL2561_LUX_B3T m=self.TSL2561_LUX_M3T - elif (ratio <= self.TSL2561_LUX_K4T): + elif ratio <= self.TSL2561_LUX_K4T: b=self.TSL2561_LUX_B4T m=self.TSL2561_LUX_M4T - elif (ratio <= self.TSL2561_LUX_K5T): + elif ratio <= self.TSL2561_LUX_K5T: b=self.TSL2561_LUX_B5T m=self.TSL2561_LUX_M5T - elif (ratio <= self.TSL2561_LUX_K6T): + elif ratio <= self.TSL2561_LUX_K6T: b=self.TSL2561_LUX_B6T m=self.TSL2561_LUX_M6T - elif (ratio <= self.TSL2561_LUX_K7T): + elif ratio <= self.TSL2561_LUX_K7T: b=self.TSL2561_LUX_B7T m=self.TSL2561_LUX_M7T - elif (ratio > self.TSL2561_LUX_K8T): + elif ratio > self.TSL2561_LUX_K8T: b=self.TSL2561_LUX_B8T m=self.TSL2561_LUX_M8T # endif @@ -509,7 +509,7 @@ def calculate_lux(self): temp = ((channel0 * b) - (channel1 * m)) # Do not allow negative lux value */ - if (temp < 0): + if temp < 0: temp = 0 # Round lsb (2^(LUX_SCALE-1)) */ @@ -519,7 +519,7 @@ def calculate_lux(self): lux = temp >> self.TSL2561_LUX_LUXSCALE # Signal I2C had no errors */ - if (self._debug == True): print "calculateLux_end" + if self._debug == True: print "calculateLux_end" return lux def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): @@ -538,9 +538,9 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): luxavgtotal = capture + luxavgtotal count += 1 # Once we reach the number of required tests, work out the average - if (count >= testavg): + if count >= testavg: luxavg = round(luxavgtotal / testavg) - return (luxavg) + return luxavg if __name__ == "__main__": LightSensor = AdafruitTSL2561() @@ -549,7 +549,7 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): # See if "loop" has been passed as an arg. try: arg = sys.argv[1] - if (arg == "loop"): + if arg == "loop": while True: try: print (int(LightSensor.calculate_avg_lux())) From e24ff6554491d955e57cd819beaa2b9b0dac61fc Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 21:06:44 +0000 Subject: [PATCH 30/44] More Pycharm Inspection driven changes --- Adafruit_TSL2561/Adafruit_TSL2561.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 2be032e7..2c4b6233 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -293,25 +293,25 @@ def enable_auto_gain(self, enable): self._tsl2561AutoGain = False if self._debug == True: print "enableAutoGain_end" - def set_integration_time(self, time): + def set_integration_time(self, integration_time): """ - Sets the integration time for the TSL2561 + Sets the integration integration_time for the TSL2561 - :param time: + :param integration_time: :return: """ if self._debug == True: print "set_integration_time" if not self._tsl2561Initialised: - self.begin + self.begin() # Enable the device by setting the control bit to 0x03 */ self.enable() # Update the timing register */ - self.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_TIMING, time | self._tsl2561Gain) + self.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_TIMING, integration_time | self._tsl2561Gain) # Update value placeholders */ - self._tsl2561IntegrationTime = time + self._tsl2561IntegrationTime = integration_time # Turn the device off to save power */ self.disable() @@ -325,7 +325,7 @@ def set_gain(self, gain): """ if self._debug == True: print "set_gain" if not self._tsl2561Initialised: - self.begin + self.begin() # Enable the device by setting the control bit to 0x03 */ self.enable() @@ -356,7 +356,7 @@ def get_luminosity(self): valid = False if not self._tsl2561Initialised: - self.begin + self.begin() # If Auto gain disabled get a single reading and continue */ if not self._tsl2561AutoGain: @@ -506,6 +506,7 @@ def calculate_lux(self): m=self.TSL2561_LUX_M8T # endif + # noinspection PyUnboundLocalVariable,PyUnboundLocalVariable temp = ((channel0 * b) - (channel1 * m)) # Do not allow negative lux value */ From 2ac74694845f7a7497243b553e12a914250664ea Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 21:25:11 +0000 Subject: [PATCH 31/44] Changed printing to use logger, shortened if enable == True to match convention --- Adafruit_TSL2561/Adafruit_TSL2561.py | 57 +++++++++++++++------------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 2c4b6233..df01d4fb 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -32,6 +32,7 @@ import sys import time +import logging from Adafruit_I2C import Adafruit_I2C @@ -162,9 +163,9 @@ def write8(self, reg, value): :param reg: Register / Address to write value to :param value: Byte to write to Address """ - if self._debug == True: print "write8" + logging.debug('write8') self._i2c.write8(reg, value) - if self._debug == True: print "write8_end" + logging.debug('write8_end') def read8(self, reg): """ @@ -173,9 +174,9 @@ def read8(self, reg): :param reg: Register / Address to read value from :return: Unsigned byte """ - if self._debug == True: print "read8" + logging.debug('read8') return self._i2c.readU8(reg) - if self._debug == True: print "read8_end" + logging.debug('read8_end') def read16(self, reg): """ @@ -184,33 +185,33 @@ def read16(self, reg): :param reg: Register / Address to read value from :return: Unsigned word """ - if self._debug == True: print "read16" + logging.debug('read16') return self._i2c.readU16(reg) - if self._debug == True: print "read16_end" + logging.debug('read16_end') def enable(self): """ Enables the device """ - if self._debug == True: print "enable" + logging.debug('enable') # Enable the device by setting the control bit to 0x03 */ self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWERON) - if self._debug == True: print "enable_end" + logging.debug('enable_end') def disable(self): """ Disables the device (putting it in lower power sleep mode) """ - if self._debug == True: print "disable" + logging.debug('disable') # Turn the device off to save power */ self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWEROFF) - if self._debug == True: print "disable_end" + logging.debug('disable_end') def get_data(self): """ Private function to read luminosity on both channels """ - if self._debug == True: print "get_data" + logging.debug('get_data') # Enables the device by setting the control bit to 0x03 self.enable() @@ -231,7 +232,7 @@ def get_data(self): # Turn the device off to save power */ self.disable() - if self._debug == True: print "getData_end" + logging.debug('getData_end"') def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): """ @@ -241,7 +242,7 @@ def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): :param debug: Turn on debugging, defaults to False """ self._debug = debug - if self._debug == True: print "__init__" + logging.debug('__init__"') self._addr = addr self._tsl2561Initialised = False self._tsl2561AutoGain = False @@ -251,7 +252,7 @@ def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): self._luminosity = 0 self._broadband = 0 self._ir = 0 - if self._debug == True: print "__init___end" + logging.debug('__init___end') def begin(self): """ @@ -262,7 +263,7 @@ def begin(self): :return: True if connected to a TSL2561 """ - if self._debug == True: print "begin" + logging.debug('begin') # Make sure we're actually connected */ x = self.read8(self.TSL2561_REGISTER_ID) if not(x & 0x0A): @@ -275,7 +276,7 @@ def begin(self): # Note: by default, the device is in power down mode on bootup */ self.disable() - if self._debug == True: print "begin_end" + logging.debug('begin_end') return True @@ -286,12 +287,12 @@ def enable_auto_gain(self, enable): :param enable: True to enable """ - if self._debug == True: print "enable_auto_gain" - if enable == True: + logging.debug('enable_auto_gain') + if enable: self._tsl2561AutoGain = enable else: self._tsl2561AutoGain = False - if self._debug == True: print "enableAutoGain_end" + logging.debug('enableAutoGain_end') def set_integration_time(self, integration_time): """ @@ -300,7 +301,7 @@ def set_integration_time(self, integration_time): :param integration_time: :return: """ - if self._debug == True: print "set_integration_time" + logging.debug('set_integration_time') if not self._tsl2561Initialised: self.begin() @@ -315,7 +316,7 @@ def set_integration_time(self, integration_time): # Turn the device off to save power */ self.disable() - if self._debug == True: print "setIntegrationTime_end" + logging.debug('setIntegrationTime_end') def set_gain(self, gain): """ @@ -323,7 +324,7 @@ def set_gain(self, gain): :param gain: """ - if self._debug == True: print "set_gain" + logging.debug('set_gain') if not self._tsl2561Initialised: self.begin() @@ -338,7 +339,7 @@ def set_gain(self, gain): # Turn the device off to save power */ self.disable() - if self._debug == True: print "setGain_end" + logging.debug('setGain_end') def get_luminosity(self): """ @@ -352,7 +353,7 @@ def get_luminosity(self): if self._tsl2561AutoGain: self.set_gain(self.TSL2561_GAIN_1X) - if self._debug == True: print "get_luminosity" + logging.debug('get_luminosity') valid = False if not self._tsl2561Initialised: @@ -406,7 +407,7 @@ def get_luminosity(self): # This avoids endless loops where a value is at one extreme pre-gain, # and the the other extreme post-gain */ valid = True - if self._debug == True: print "getLuminosity_end" + logging.debug('getLuminosity_end') def calculate_lux(self): """ @@ -415,7 +416,7 @@ def calculate_lux(self): :return: lux value, unsigned 16bit word (0 - 65535) """ - if self._debug == True: print "calculate_lux" + logging.debug('calculate_lux') self.get_luminosity() # Make sure the sensor isn't saturated! */ if self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS: @@ -520,7 +521,7 @@ def calculate_lux(self): lux = temp >> self.TSL2561_LUX_LUXSCALE # Signal I2C had no errors */ - if self._debug == True: print "calculateLux_end" + logging.debug('calculateLux_end') return lux def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): @@ -547,6 +548,8 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): LightSensor = AdafruitTSL2561() LightSensor.enable_auto_gain(True) + logging.basicConfig(level=logging.DEBUG) + # See if "loop" has been passed as an arg. try: arg = sys.argv[1] From 9515601db55f54117bcdd7ed270063ddaf234a56 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 21:38:32 +0000 Subject: [PATCH 32/44] last of the Pycharm inspection changes --- Adafruit_TSL2561/Adafruit_TSL2561.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index df01d4fb..f01bdc9f 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -176,7 +176,6 @@ def read8(self, reg): """ logging.debug('read8') return self._i2c.readU8(reg) - logging.debug('read8_end') def read16(self, reg): """ @@ -187,7 +186,6 @@ def read16(self, reg): """ logging.debug('read16') return self._i2c.readU16(reg) - logging.debug('read16_end') def enable(self): """ @@ -225,6 +223,7 @@ def get_data(self): time.sleep(self.TSL2561_DELAY_INTTIME_402MS) # Reads a two byte value from channel 0 (visible + infrared) */ + # noinspection PyPep8 self._broadband = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN0_LOW) # Reads a two byte value from channel 1 (infrared) */ @@ -234,7 +233,7 @@ def get_data(self): self.disable() logging.debug('getData_end"') - def __init__(self, addr=TSL2561_ADDR_FLOAT, debug=False): + def __init__(self, address, addr=TSL2561_ADDR_FLOAT, debug=False): """ Constructor @@ -441,7 +440,7 @@ def calculate_lux(self): # Scale for gain (1x or 16x) */ if not self._tsl2561Gain: - ch_scale = ch_scale << 4 + ch_scale <<= 4 # Scale the channel values */ channel0 = (self._broadband * ch_scale) >> self.TSL2561_LUX_CHSCALE @@ -537,7 +536,7 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): # Create a cumulative total of values for 'testavg' tests while True: capture = self.calculate_lux() - luxavgtotal = capture + luxavgtotal + luxavgtotal += capture count += 1 # Once we reach the number of required tests, work out the average if count >= testavg: From 81b3f1c9ddfef7d6701ef8492a132e1e11e81761 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 21:45:31 +0000 Subject: [PATCH 33/44] Fixed broken __init__ params --- Adafruit_TSL2561/Adafruit_TSL2561.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index f01bdc9f..b309558a 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -233,21 +233,21 @@ def get_data(self): self.disable() logging.debug('getData_end"') - def __init__(self, address, addr=TSL2561_ADDR_FLOAT, debug=False): + def __init__(self, address=TSL2561_ADDR_FLOAT, debug=False): """ Constructor - :param addr: I2C address of TSL2561, defaults to 0x39 + :param address: I2C address of TSL2561, defaults to 0x39 :param debug: Turn on debugging, defaults to False """ self._debug = debug logging.debug('__init__"') - self._addr = addr + self._address = address self._tsl2561Initialised = False self._tsl2561AutoGain = False self._tsl2561IntegrationTime = self.TSL2561_INTEGRATIONTIME_13MS self._tsl2561Gain = self.TSL2561_GAIN_1X - self._i2c = Adafruit_I2C(self._addr) + self._i2c = Adafruit_I2C(self._address) self._luminosity = 0 self._broadband = 0 self._ir = 0 From e8d0bce070174a7ee1936f39e22081faa2d8a8a9 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 21:50:48 +0000 Subject: [PATCH 34/44] Appropriate SonarQube inspection changes --- Adafruit_TSL2561/Adafruit_TSL2561.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index b309558a..35be4717 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -233,6 +233,7 @@ def get_data(self): self.disable() logging.debug('getData_end"') + # noinspection PyMissingConstructor def __init__(self, address=TSL2561_ADDR_FLOAT, debug=False): """ Constructor @@ -364,7 +365,7 @@ def get_luminosity(self): return # Read data until we find a valid range */ - _agcCheck = False + agc_check = False while not valid: _it = self._tsl2561IntegrationTime @@ -382,21 +383,21 @@ def get_luminosity(self): self.get_data() # Run an auto-gain check if we haven't already done so ... */ - if not _agcCheck: + if not agc_check: if (self._broadband < _lo) and (self._tsl2561Gain == self.TSL2561_GAIN_1X): # Increase the gain and try again */ self.set_gain(self.TSL2561_GAIN_16X) # Drop the previous conversion results */ self.get_data() # Set a flag to indicate we've adjusted the gain */ - _agcCheck = True + agc_check = True elif (self._broadband > _hi) and (self._tsl2561Gain == self.TSL2561_GAIN_16X): # Drop gain to 1x and try again */ self.set_gain(self.TSL2561_GAIN_1X) # Drop the previous conversion results */ self.get_data() # Set a flag to indicate we've adjusted the gain */ - _agcCheck = True + agc_check = True else: # Nothing to look at here, keep moving .... # Reading is either valid, or we're already at the chips limits */ @@ -436,7 +437,7 @@ def calculate_lux(self): elif self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_101MS: ch_scale = self.TSL2561_LUX_CHSCALE_TINT1 else: - ch_scale = (1 << self.TSL2561_LUX_CHSCALE) + ch_scale = 1 << self.TSL2561_LUX_CHSCALE # Scale for gain (1x or 16x) */ if not self._tsl2561Gain: @@ -507,14 +508,14 @@ def calculate_lux(self): # endif # noinspection PyUnboundLocalVariable,PyUnboundLocalVariable - temp = ((channel0 * b) - (channel1 * m)) + temp = (channel0 * b) - (channel1 * m) # Do not allow negative lux value */ if temp < 0: temp = 0 # Round lsb (2^(LUX_SCALE-1)) */ - temp += (1 << (self.TSL2561_LUX_LUXSCALE - 1)) + temp += 1 << (self.TSL2561_LUX_LUXSCALE - 1) # Strip off fractional portion */ lux = temp >> self.TSL2561_LUX_LUXSCALE From 5bcb72c73c62e4b25701d5b3e6982030400698c1 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 22:05:40 +0000 Subject: [PATCH 35/44] Log to stdout --- Adafruit_TSL2561/Adafruit_TSL2561.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 35be4717..6f1dd953 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -21,8 +21,8 @@ Bug #1: The class name has the middle two digits transposed - Adafruit_TSL2651 should be Adafruit_TSL2561 Bug #2: The read8 and read16 methods (functions) call the I2C readS8 and readS16 methods respectively. They should call the readU8 and readU16 (i.e. unsigned) methods. - Minor fixes and changes - 1.0 - Initial release - Iain Colledge + Minor fixes and changes due to Pycharm and SonarQube recommendations, it looks like Python more than C++ now +1.0 - Initial release - Iain Colledge Removed commented out C++ code Added calculate_avg_lux Changed main method to use calculate_avg_lux and loop argument support added. @@ -548,7 +548,7 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): LightSensor = AdafruitTSL2561() LightSensor.enable_auto_gain(True) - logging.basicConfig(level=logging.DEBUG) + logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) # See if "loop" has been passed as an arg. try: From 32a479b89c51c14837434625298fc19c9ed8b0d5 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 22:18:32 +0000 Subject: [PATCH 36/44] Example code --- Adafruit_TSL2561/Adafruit_TSL2561_example.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561_example.py b/Adafruit_TSL2561/Adafruit_TSL2561_example.py index 93049cb5..fd1027f5 100644 --- a/Adafruit_TSL2561/Adafruit_TSL2561_example.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561_example.py @@ -1,15 +1,17 @@ #!/usr/bin/python -from Adafruit_TSL2561 import Adafruit_TSL2561 +from Adafruit_TSL2561 import AdafruitTSL2561 # Initialise the sensor -LightSensor = Adafruit_TSL2561.AdafruitTSL2651() +LightSensor = AdafruitTSL2561() # Enable auto gain switching between 1x and 16x # Default is False LightSensor.enable_auto_gain(True) # Get the calculated lux value, this is a spot reading so if you're under light -# lux = Adafruit_TSL2561.calculate_lux() +lux = LightSensor.calculate_lux() + +print ('Lux value is %d',lux) From 2ee06816fd6c14fb4d2a1bde472d09d0c21063c2 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 22:27:53 +0000 Subject: [PATCH 37/44] Logging order fixed --- Adafruit_TSL2561/Adafruit_TSL2561.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 6f1dd953..b6fa7b2e 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -30,9 +30,12 @@ Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work """ +import logging +# Logging needs to be set before any other library is imported +logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) + import sys import time -import logging from Adafruit_I2C import Adafruit_I2C @@ -548,8 +551,6 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): LightSensor = AdafruitTSL2561() LightSensor.enable_auto_gain(True) - logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) - # See if "loop" has been passed as an arg. try: arg = sys.argv[1] From 3080cac3d31fff5249f09697af53eac14af36407 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 22:34:39 +0000 Subject: [PATCH 38/44] Logging after imports --- Adafruit_TSL2561/Adafruit_TSL2561.py | 7 ++++--- Adafruit_TSL2561/Adafruit_TSL2561_example.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index b6fa7b2e..3f60878b 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -31,13 +31,14 @@ """ import logging -# Logging needs to be set before any other library is imported -logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) - import sys import time from Adafruit_I2C import Adafruit_I2C +# Logging needs to be set at top +logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) + + class AdafruitTSL2561(Adafruit_I2C): TSL2561_VISIBLE = 2 # channel 0 - channel 1 diff --git a/Adafruit_TSL2561/Adafruit_TSL2561_example.py b/Adafruit_TSL2561/Adafruit_TSL2561_example.py index fd1027f5..5e203300 100644 --- a/Adafruit_TSL2561/Adafruit_TSL2561_example.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561_example.py @@ -12,6 +12,6 @@ # Get the calculated lux value, this is a spot reading so if you're under light lux = LightSensor.calculate_lux() -print ('Lux value is %d',lux) +print('Lux value is %d',lux) From f89b06bd6da7a8eb426151ec94449d6a588aeafa Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Tue, 15 Dec 2015 22:37:53 +0000 Subject: [PATCH 39/44] Comment out logging statement so level is default --- Adafruit_TSL2561/Adafruit_TSL2561.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 3f60878b..1eb56334 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -36,7 +36,7 @@ from Adafruit_I2C import Adafruit_I2C # Logging needs to be set at top -logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) +#logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) From fe63020a8a5f476cc6739f1c7344f466ae7cc037 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Wed, 16 Dec 2015 10:12:11 +0000 Subject: [PATCH 40/44] Throws an OverflowError when sensor is saturated, put in handling blocks in example and main method in TSL2561 module --- Adafruit_TSL2561/Adafruit_TSL2561.py | 23 ++++++++++++-------- Adafruit_TSL2561/Adafruit_TSL2561_example.py | 11 +++++----- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 1eb56334..06d7bd51 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -22,6 +22,7 @@ Bug #2: The read8 and read16 methods (functions) call the I2C readS8 and readS16 methods respectively. They should call the readU8 and readU16 (i.e. unsigned) methods. Minor fixes and changes due to Pycharm and SonarQube recommendations, it looks like Python more than C++ now + Added Exception thrown on sensor saturation 1.0 - Initial release - Iain Colledge Removed commented out C++ code Added calculate_avg_lux @@ -35,11 +36,11 @@ import time from Adafruit_I2C import Adafruit_I2C -# Logging needs to be set at top -#logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) - +# Logging needs to be set at top after imports +# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) +# TODO: Not sure why this is inheriting the Adafruit I2C class, might need some refactoring class AdafruitTSL2561(Adafruit_I2C): TSL2561_VISIBLE = 2 # channel 0 - channel 1 TSL2561_INFRARED = 1 # channel 1 @@ -354,6 +355,8 @@ def get_luminosity(self): # This is a hack to ensure that when looping with autogain the gain can go up and down as without # setting the gain to 1X before every reading it doesn't seem able to go from 16X # back to 1X again. Going from 1X to 16X works fine. - IC + # TODO: Grok the algorithm and fix it + if self._tsl2561AutoGain: self.set_gain(self.TSL2561_GAIN_1X) @@ -419,6 +422,8 @@ def calculate_lux(self): Returns 0 if the sensor is saturated and the values are unreliable. :return: lux value, unsigned 16bit word (0 - 65535) + :raises: OverflowError when TSL2561 sensor is saturated + """ logging.debug('calculate_lux') self.get_luminosity() @@ -430,10 +435,8 @@ def calculate_lux(self): else: clip_threshold = self.TSL2561_CLIPPING_402MS - # Return 0 lux if the sensor is saturated */ - # TODO: Throw an exception rather than return 0 if (self._broadband > clip_threshold) or (self._ir > clip_threshold): - return 0 + raise OverflowError('TSL2561 Sensor Saturated') # Get the correct scale depending on the intergration time */ if self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_13MS: @@ -558,10 +561,12 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): if arg == "loop": while True: try: - print (int(LightSensor.calculate_avg_lux())) + print(int(LightSensor.calculate_avg_lux())) + except OverflowError as e: + print(e) except KeyboardInterrupt: quit() else: - print ("Invalid arg(s):", sys.argv) + print("Invalid arg(s):", sys.argv) except IndexError: - print (int(LightSensor.calculate_avg_lux())) + print(int(LightSensor.calculate_avg_lux())) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561_example.py b/Adafruit_TSL2561/Adafruit_TSL2561_example.py index 5e203300..ad2873e6 100644 --- a/Adafruit_TSL2561/Adafruit_TSL2561_example.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561_example.py @@ -10,8 +10,9 @@ LightSensor.enable_auto_gain(True) # Get the calculated lux value, this is a spot reading so if you're under light -lux = LightSensor.calculate_lux() - -print('Lux value is %d',lux) - - +try: + lux = LightSensor.calculate_lux() +except OverflowError as e: + print(e) +else: + print('Lux value is %d', lux) From ddd6412a677f4a55227762d8d8e44dd24a33dd46 Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Wed, 16 Dec 2015 10:24:03 +0000 Subject: [PATCH 41/44] Added from __future__ import print_function so print is a function, not a statement in code --- Adafruit_TSL2561/Adafruit_TSL2561.py | 1 + Adafruit_TSL2561/Adafruit_TSL2561_example.py | 1 + 2 files changed, 2 insertions(+) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index 06d7bd51..bb9a3b21 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -31,6 +31,7 @@ Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work """ +from __future__ import print_function import logging import sys import time diff --git a/Adafruit_TSL2561/Adafruit_TSL2561_example.py b/Adafruit_TSL2561/Adafruit_TSL2561_example.py index ad2873e6..1c6ced20 100644 --- a/Adafruit_TSL2561/Adafruit_TSL2561_example.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561_example.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function from Adafruit_TSL2561 import AdafruitTSL2561 # Initialise the sensor From ce16513f6673eadd82f29c951fa7ff373c9fbcfd Mon Sep 17 00:00:00 2001 From: Iain Colledge Date: Wed, 16 Dec 2015 10:44:36 +0000 Subject: [PATCH 42/44] Tidy up print formatting in example and added TODO for bug in main code with regards saturation detection --- Adafruit_TSL2561/Adafruit_TSL2561.py | 3 ++- Adafruit_TSL2561/Adafruit_TSL2561_example.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index bb9a3b21..d438aa8e 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -436,6 +436,7 @@ def calculate_lux(self): else: clip_threshold = self.TSL2561_CLIPPING_402MS + # TODO: Fix that exception not raised when hits saturation but returns a Lux of around 780 if (self._broadband > clip_threshold) or (self._ir > clip_threshold): raise OverflowError('TSL2561 Sensor Saturated') @@ -568,6 +569,6 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): except KeyboardInterrupt: quit() else: - print("Invalid arg(s):", sys.argv) + print("Invalid arg(s):", sys.argv[1]) except IndexError: print(int(LightSensor.calculate_avg_lux())) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561_example.py b/Adafruit_TSL2561/Adafruit_TSL2561_example.py index 1c6ced20..bca57e92 100644 --- a/Adafruit_TSL2561/Adafruit_TSL2561_example.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561_example.py @@ -16,4 +16,4 @@ except OverflowError as e: print(e) else: - print('Lux value is %d', lux) + print("Lux value is ", lux) From 8b9a141251f588d13233a40af832bf782736ffef Mon Sep 17 00:00:00 2001 From: Chris Satterlee Date: Fri, 18 Dec 2015 11:44:09 -0800 Subject: [PATCH 43/44] Additional cleanup - Changed Adafruit_I2C.py from a copy to a symbolic link - Added underscore back into class name - Removed unnecessary inheritance from Adafruit_I2C - Removed vestigial trailing */ from comments - Removed (now unnecessary) autogain hack - Fold (most) long lines to comply with col 80 limit - Added BSD license header comment --- Adafruit_TSL2561/Adafruit_I2C.py | 162 +------------------ Adafruit_TSL2561/Adafruit_TSL2561.py | 222 +++++++++++++++++---------- 2 files changed, 141 insertions(+), 243 deletions(-) mode change 100755 => 120000 Adafruit_TSL2561/Adafruit_I2C.py diff --git a/Adafruit_TSL2561/Adafruit_I2C.py b/Adafruit_TSL2561/Adafruit_I2C.py deleted file mode 100755 index 2b24b67f..00000000 --- a/Adafruit_TSL2561/Adafruit_I2C.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/python -import re -import smbus - -# =========================================================================== -# Adafruit_I2C Class -# =========================================================================== - -class Adafruit_I2C(object): - - @staticmethod - def getPiRevision(): - "Gets the version number of the Raspberry Pi board" - # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History - try: - with open('/proc/cpuinfo', 'r') as infile: - for line in infile: - # Match a line of the form "Revision : 0002" while ignoring extra - # info in front of the revsion (like 1000 when the Pi was over-volted). - match = re.match('Revision\s+:\s+.*(\w{4})$', line) - if match and match.group(1) in ['0000', '0002', '0003']: - # Return revision 1 if revision ends with 0000, 0002 or 0003. - return 1 - elif match: - # Assume revision 2 if revision ends with any other 4 chars. - return 2 - # Couldn't find the revision, assume revision 0 like older code for compatibility. - return 0 - except: - return 0 - - @staticmethod - def getPiI2CBusNumber(): - # Gets the I2C bus number /dev/i2c# - return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 - - def __init__(self, address, busnum=-1, debug=False): - self.address = address - # By default, the correct I2C bus is auto-detected using /proc/cpuinfo - # Alternatively, you can hard-code the bus version below: - # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) - # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) - self.bus = smbus.SMBus(busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) - self.debug = debug - - def reverseByteOrder(self, data): - "Reverses the byte order of an int (16-bit) or long (32-bit) value" - # Courtesy Vishal Sapre - byteCount = len(hex(data)[2:].replace('L','')[::2]) - val = 0 - for i in range(byteCount): - val = (val << 8) | (data & 0xff) - data >>= 8 - return val - - def errMsg(self): - print "Error accessing 0x%02X: Check your I2C address" % self.address - return -1 - - def write8(self, reg, value): - "Writes an 8-bit value to the specified register/address" - try: - self.bus.write_byte_data(self.address, reg, value) - if self.debug: - print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg) - except IOError, err: - return self.errMsg() - - def write16(self, reg, value): - "Writes a 16-bit value to the specified register/address pair" - try: - self.bus.write_word_data(self.address, reg, value) - if self.debug: - print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % - (value, reg, reg+1)) - except IOError, err: - return self.errMsg() - - def writeRaw8(self, value): - "Writes an 8-bit value on the bus" - try: - self.bus.write_byte(self.address, value) - if self.debug: - print "I2C: Wrote 0x%02X" % value - except IOError, err: - return self.errMsg() - - def writeList(self, reg, list): - "Writes an array of bytes using I2C format" - try: - if self.debug: - print "I2C: Writing list to register 0x%02X:" % reg - print list - self.bus.write_i2c_block_data(self.address, reg, list) - except IOError, err: - return self.errMsg() - - def readList(self, reg, length): - "Read a list of bytes from the I2C device" - try: - results = self.bus.read_i2c_block_data(self.address, reg, length) - if self.debug: - print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % - (self.address, reg)) - print results - return results - except IOError, err: - return self.errMsg() - - def readU8(self, reg): - "Read an unsigned byte from the I2C device" - try: - result = self.bus.read_byte_data(self.address, reg) - if self.debug: - print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % - (self.address, result & 0xFF, reg)) - return result - except IOError, err: - return self.errMsg() - - def readS8(self, reg): - "Reads a signed byte from the I2C device" - try: - result = self.bus.read_byte_data(self.address, reg) - if result > 127: result -= 256 - if self.debug: - print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % - (self.address, result & 0xFF, reg)) - return result - except IOError, err: - return self.errMsg() - - def readU16(self, reg, little_endian=True): - "Reads an unsigned 16-bit value from the I2C device" - try: - result = self.bus.read_word_data(self.address,reg) - # Swap bytes if using big endian because read_word_data assumes little - # endian on ARM (little endian) systems. - if not little_endian: - result = ((result << 8) & 0xFF00) + (result >> 8) - if (self.debug): - print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) - return result - except IOError, err: - return self.errMsg() - - def readS16(self, reg, little_endian=True): - "Reads a signed 16-bit value from the I2C device" - try: - result = self.readU16(reg,little_endian) - if result > 32767: result -= 65536 - return result - except IOError, err: - return self.errMsg() - -if __name__ == '__main__': - try: - bus = Adafruit_I2C(address=0) - print "Default I2C bus is accessible" - except: - print "Error accessing default I2C bus" diff --git a/Adafruit_TSL2561/Adafruit_I2C.py b/Adafruit_TSL2561/Adafruit_I2C.py new file mode 120000 index 00000000..77f06164 --- /dev/null +++ b/Adafruit_TSL2561/Adafruit_I2C.py @@ -0,0 +1 @@ +../Adafruit_I2C/Adafruit_I2C.py \ No newline at end of file diff --git a/Adafruit_TSL2561/Adafruit_TSL2561.py b/Adafruit_TSL2561/Adafruit_TSL2561.py index d438aa8e..1a69b4a4 100755 --- a/Adafruit_TSL2561/Adafruit_TSL2561.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561.py @@ -1,34 +1,81 @@ #!/usr/bin/python - +# +# Copyright (c) 2015 Iain Colledge for Adafruit Industries +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. """ Python library for the TSL2561 digital luminosity (light) sensors. -This library is heavily based on the Arduino library for the TSL2561 digital luminosity (light) sensors. -It is basically a simple translation from C++ to Python. -The thread on the Adafruit forum helped a lot to do this. -Thanks to static, huelke, pandring, adafruit_support_rick, scortier, bryand, csalty, lenos and of course to Adafruit -Source for the Arduino library: https://github.com/adafruit/TSL2561-Arduino-Library -Adafruit forum thread:http://forums.adafruit.com/viewtopic.php?f=8&t=34922&sid=8336d566f2f03c25882aaf34c8a15a92 +This library is heavily based on the Arduino library for the TSL2561 digital +luminosity (light) sensors. It is basically a simple translation from C++ to +Python. + +The thread on the Adafruit forum helped a lot to do this. Thanks to static, +huelke, pandring, adafruit_support_rick, scortier, bryand, csalty, lenos and +of course to Adafruit + +Source for the Arduino library: +https://github.com/adafruit/TSL2561-Arduino-Library -Original code posted here http://forums.adafruit.com/viewtopic.php?f=8&t=34922&start=75#p222877 +Adafruit forum thread: +http://forums.adafruit.com/viewtopic.php?f=8&t=34922&sid=8336d566f2f03c25882aaf34c8a15a92 -This was checked against a 10 UKP lux meter from Amazon and was withing 10% up and down the range, the meter -had a stated accuracy of 5% but then again, 10 UKP meter. +Original code posted here: +http://forums.adafruit.com/viewtopic.php?f=8&t=34922&start=75#p222877 + +This was checked against a 10 UKP lux meter from Amazon and was withing 10% up +and down the range, the meter had a stated accuracy of 5% but then again, 10 +UKP meter. Changelog: -1.1 - Fixes from https://forums.adafruit.com/viewtopic.php?f=8&t=34922&p=430795#p430782 - Iain Colledge - Bug #1: The class name has the middle two digits transposed - Adafruit_TSL2651 should be Adafruit_TSL2561 - Bug #2: The read8 and read16 methods (functions) call the I2C readS8 and readS16 methods respectively. - They should call the readU8 and readU16 (i.e. unsigned) methods. - Minor fixes and changes due to Pycharm and SonarQube recommendations, it looks like Python more than C++ now +1.2 - Additional clean-up - Chris Satterlee + Added underscore back into class name + Removed unnecessary inheritance from Adafruit_I2C + Removed vestigial trailing */ from comments + Removed (now unnecessary) autogain hack + Fold (most) long lines to comply with col 80 limit + Added BSD license header comment +1.1 - Fixes from + https://forums.adafruit.com/viewtopic.php?f=8&t=34922&p=430795#p430782 + - Iain Colledge + Bug #1: The class name has the middle two digits transposed - + Adafruit_TSL2651 should be Adafruit_TSL2561 + Bug #2: The read8 and read16 methods (functions) call the I2C readS8 and + readS16 methods respectively. They should call the readU8 and + readU16 (i.e. unsigned) methods. + Minor fixes and changes due to Pycharm and SonarQube recommendations, it + looks like Python more than C++ now Added Exception thrown on sensor saturation 1.0 - Initial release - Iain Colledge Removed commented out C++ code Added calculate_avg_lux - Changed main method to use calculate_avg_lux and loop argument support added. - Ported "Extended delays to take into account loose timing with 'delay'" update from CPP code - Added hack so that with autogain every sample goes from 1x to 16x as going from 16x to 1x does not work + Changed main method to use calculate_avg_lux and loop argument support + added. + Ported "Extended delays to take into account loose timing with 'delay'" + update from CPP code + Added hack so that with autogain every sample goes from 1x to 16x as going + from 16x to 1x does not work """ from __future__ import print_function @@ -40,9 +87,7 @@ # Logging needs to be set at top after imports # logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) - -# TODO: Not sure why this is inheriting the Adafruit I2C class, might need some refactoring -class AdafruitTSL2561(Adafruit_I2C): +class Adafruit_TSL2561(object): TSL2561_VISIBLE = 2 # channel 0 - channel 1 TSL2561_INFRARED = 1 # channel 1 TSL2561_FULLSPECTRUM = 0 # channel 0 @@ -198,8 +243,10 @@ def enable(self): Enables the device """ logging.debug('enable') - # Enable the device by setting the control bit to 0x03 */ - self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWERON) + # Enable the device by setting the control bit to 0x03 + self._i2c.write8(self.TSL2561_COMMAND_BIT | + self.TSL2561_REGISTER_CONTROL, + self.TSL2561_CONTROL_POWERON) logging.debug('enable_end') def disable(self): @@ -207,8 +254,10 @@ def disable(self): Disables the device (putting it in lower power sleep mode) """ logging.debug('disable') - # Turn the device off to save power */ - self._i2c.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_CONTROL, self.TSL2561_CONTROL_POWEROFF) + # Turn the device off to save power + self._i2c.write8(self.TSL2561_COMMAND_BIT | + self.TSL2561_REGISTER_CONTROL, + self.TSL2561_CONTROL_POWEROFF) logging.debug('disable_end') def get_data(self): @@ -220,7 +269,7 @@ def get_data(self): # Enables the device by setting the control bit to 0x03 self.enable() - # Wait x ms for ADC to complete */ + # Wait x ms for ADC to complete if self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS: time.sleep(self.TSL2561_DELAY_INTTIME_13MS) elif self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS: @@ -228,14 +277,18 @@ def get_data(self): else: time.sleep(self.TSL2561_DELAY_INTTIME_402MS) - # Reads a two byte value from channel 0 (visible + infrared) */ + # Reads a two byte value from channel 0 (visible + infrared) # noinspection PyPep8 - self._broadband = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN0_LOW) + self._broadband = self.read16(self.TSL2561_COMMAND_BIT | + self.TSL2561_WORD_BIT | + self.TSL2561_REGISTER_CHAN0_LOW) - # Reads a two byte value from channel 1 (infrared) */ - self._ir = self.read16(self.TSL2561_COMMAND_BIT | self.TSL2561_WORD_BIT | self.TSL2561_REGISTER_CHAN1_LOW) + # Reads a two byte value from channel 1 (infrared) + self._ir = self.read16(self.TSL2561_COMMAND_BIT | + self.TSL2561_WORD_BIT | + self.TSL2561_REGISTER_CHAN1_LOW) - # Turn the device off to save power */ + # Turn the device off to save power self.disable() logging.debug('getData_end"') @@ -270,17 +323,17 @@ def begin(self): :return: True if connected to a TSL2561 """ logging.debug('begin') - # Make sure we're actually connected */ + # Make sure we're actually connected x = self.read8(self.TSL2561_REGISTER_ID) if not(x & 0x0A): return False self._tsl2561Initialised = True - # Set default integration time and gain */ + # Set default integration time and gain self.set_integration_time(self._tsl2561IntegrationTime) self.set_gain(self._tsl2561Gain) - # Note: by default, the device is in power down mode on bootup */ + # Note: by default, the device is in power down mode on bootup self.disable() logging.debug('begin_end') @@ -311,16 +364,18 @@ def set_integration_time(self, integration_time): if not self._tsl2561Initialised: self.begin() - # Enable the device by setting the control bit to 0x03 */ + # Enable the device by setting the control bit to 0x03 self.enable() - # Update the timing register */ - self.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_TIMING, integration_time | self._tsl2561Gain) + # Update the timing register + self.write8(self.TSL2561_COMMAND_BIT | + self.TSL2561_REGISTER_TIMING, integration_time | + self._tsl2561Gain) - # Update value placeholders */ + # Update value placeholders self._tsl2561IntegrationTime = integration_time - # Turn the device off to save power */ + # Turn the device off to save power self.disable() logging.debug('setIntegrationTime_end') @@ -334,16 +389,18 @@ def set_gain(self, gain): if not self._tsl2561Initialised: self.begin() - # Enable the device by setting the control bit to 0x03 */ + # Enable the device by setting the control bit to 0x03 self.enable() - # Update the timing register */ - self.write8(self.TSL2561_COMMAND_BIT | self.TSL2561_REGISTER_TIMING, self._tsl2561IntegrationTime | gain) + # Update the timing register + self.write8(self.TSL2561_COMMAND_BIT | + self.TSL2561_REGISTER_TIMING, + self._tsl2561IntegrationTime | gain) - # Update value placeholders */ + # Update value placeholders self._tsl2561Gain = gain - # Turn the device off to save power */ + # Turn the device off to save power self.disable() logging.debug('setGain_end') @@ -353,13 +410,6 @@ def get_luminosity(self): the TSL2561, adjusting gain if auto-gain is enabled """ - # This is a hack to ensure that when looping with autogain the gain can go up and down as without - # setting the gain to 1X before every reading it doesn't seem able to go from 16X - # back to 1X again. Going from 1X to 16X works fine. - IC - # TODO: Grok the algorithm and fix it - - if self._tsl2561AutoGain: - self.set_gain(self.TSL2561_GAIN_1X) logging.debug('get_luminosity') valid = False @@ -367,17 +417,17 @@ def get_luminosity(self): if not self._tsl2561Initialised: self.begin() - # If Auto gain disabled get a single reading and continue */ + # If Auto gain disabled get a single reading and continue if not self._tsl2561AutoGain: self.get_data() return - # Read data until we find a valid range */ + # Read data until we find a valid range agc_check = False while not valid: _it = self._tsl2561IntegrationTime - # Get the hi/low threshold for the current integration time */ + # Get the hi/low threshold for the current integration time if _it==self.TSL2561_INTEGRATIONTIME_13MS: _hi = self.TSL2561_AGC_THI_13MS _lo = self.TSL2561_AGC_TLO_13MS @@ -390,30 +440,33 @@ def get_luminosity(self): self.get_data() - # Run an auto-gain check if we haven't already done so ... */ + # Run an auto-gain check if we haven't already done so ... if not agc_check: - if (self._broadband < _lo) and (self._tsl2561Gain == self.TSL2561_GAIN_1X): - # Increase the gain and try again */ + if (self._broadband < _lo) and \ + (self._tsl2561Gain == self.TSL2561_GAIN_1X): + # Increase the gain and try again self.set_gain(self.TSL2561_GAIN_16X) - # Drop the previous conversion results */ + # Drop the previous conversion results self.get_data() - # Set a flag to indicate we've adjusted the gain */ + # Set a flag to indicate we've adjusted the gain agc_check = True - elif (self._broadband > _hi) and (self._tsl2561Gain == self.TSL2561_GAIN_16X): - # Drop gain to 1x and try again */ + elif (self._broadband > _hi) and \ + (self._tsl2561Gain == self.TSL2561_GAIN_16X): + # Drop gain to 1x and try again self.set_gain(self.TSL2561_GAIN_1X) - # Drop the previous conversion results */ + # Drop the previous conversion results self.get_data() - # Set a flag to indicate we've adjusted the gain */ + # Set a flag to indicate we've adjusted the gain agc_check = True else: # Nothing to look at here, keep moving .... - # Reading is either valid, or we're already at the chips limits */ + # Reading is either valid, or we're already at the chip's + # limits valid = True else: - # If we've already adjusted the gain once, just return the new results. - # This avoids endless loops where a value is at one extreme pre-gain, - # and the the other extreme post-gain */ + # If we've already adjusted the gain once, just return the new + # results. This avoids endless loops where a value is at one + # extreme pre-gain, and the the other extreme post-gain valid = True logging.debug('getLuminosity_end') @@ -428,7 +481,7 @@ def calculate_lux(self): """ logging.debug('calculate_lux') self.get_luminosity() - # Make sure the sensor isn't saturated! */ + # Make sure the sensor isn't saturated! if self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_13MS: clip_threshold = self.TSL2561_CLIPPING_13MS elif self._tsl2561IntegrationTime == self.TSL2561_INTEGRATIONTIME_101MS: @@ -436,11 +489,15 @@ def calculate_lux(self): else: clip_threshold = self.TSL2561_CLIPPING_402MS - # TODO: Fix that exception not raised when hits saturation but returns a Lux of around 780 - if (self._broadband > clip_threshold) or (self._ir > clip_threshold): - raise OverflowError('TSL2561 Sensor Saturated') + # Raise exception if either or both sensor channels are saturated + if (self._broadband > clip_threshold) and (self._ir > clip_threshold): + raise OverflowError('TSL2561 Sensor Saturated (both channels)') + elif (self._broadband > clip_threshold): + raise OverflowError('TSL2561 Sensor Saturated (broadband channel)') + elif (self._ir > clip_threshold): + raise OverflowError('TSL2561 Sensor Saturated (IR channel)') - # Get the correct scale depending on the intergration time */ + # Get the correct scale depending on the integration time if self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_13MS: ch_scale = self.TSL2561_LUX_CHSCALE_TINT0 elif self._tsl2561IntegrationTime ==self.TSL2561_INTEGRATIONTIME_101MS: @@ -448,20 +505,20 @@ def calculate_lux(self): else: ch_scale = 1 << self.TSL2561_LUX_CHSCALE - # Scale for gain (1x or 16x) */ + # Scale for gain (1x or 16x) if not self._tsl2561Gain: ch_scale <<= 4 - # Scale the channel values */ + # Scale the channel values channel0 = (self._broadband * ch_scale) >> self.TSL2561_LUX_CHSCALE channel1 = (self._ir * ch_scale) >> self.TSL2561_LUX_CHSCALE - # Find the ratio of the channel values (Channel1/Channel0) */ + # Find the ratio of the channel values (Channel1/Channel0) ratio1 = 0 if channel0 != 0: ratio1 = (channel1 << (self.TSL2561_LUX_RATIOSCALE + 1)) / channel0 - # round the ratio value */ + # round the ratio value ratio = (ratio1 + 1) >> 1 if self.TSL2561_PACKAGE_CS == 1: @@ -519,23 +576,24 @@ def calculate_lux(self): # noinspection PyUnboundLocalVariable,PyUnboundLocalVariable temp = (channel0 * b) - (channel1 * m) - # Do not allow negative lux value */ + # Do not allow negative lux value if temp < 0: temp = 0 - # Round lsb (2^(LUX_SCALE-1)) */ + # Round lsb (2^(LUX_SCALE-1)) temp += 1 << (self.TSL2561_LUX_LUXSCALE - 1) - # Strip off fractional portion */ + # Strip off fractional portion lux = temp >> self.TSL2561_LUX_LUXSCALE - # Signal I2C had no errors */ + # Signal I2C had no errors logging.debug('calculateLux_end') return lux def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): """ - Calculates an averaged Lux value, useful for flickering lights and for smoothing values due to noise + Calculates an averaged Lux value, useful for flickering lights and for + smoothing values due to noise :param testavg: Number of samples to take in a reading, defaults to 25 :return: lux value, unsigned 16bit word (0 - 65535) @@ -554,7 +612,7 @@ def calculate_avg_lux(self, testavg=TSL2561_NO_OF_AVG_SAMPLES): return luxavg if __name__ == "__main__": - LightSensor = AdafruitTSL2561() + LightSensor = Adafruit_TSL2561() LightSensor.enable_auto_gain(True) # See if "loop" has been passed as an arg. From 693426f5ad684240c34c4ccc61219a1e05a9c9c8 Mon Sep 17 00:00:00 2001 From: Chris Satterlee Date: Fri, 18 Dec 2015 12:11:36 -0800 Subject: [PATCH 44/44] Fix class name in example file Add the underscore to the class name in Adafruit_TSL2561_example.py --- Adafruit_TSL2561/Adafruit_TSL2561_example.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Adafruit_TSL2561/Adafruit_TSL2561_example.py b/Adafruit_TSL2561/Adafruit_TSL2561_example.py index bca57e92..bbaf9415 100644 --- a/Adafruit_TSL2561/Adafruit_TSL2561_example.py +++ b/Adafruit_TSL2561/Adafruit_TSL2561_example.py @@ -1,10 +1,10 @@ #!/usr/bin/python from __future__ import print_function -from Adafruit_TSL2561 import AdafruitTSL2561 +from Adafruit_TSL2561 import Adafruit_TSL2561 # Initialise the sensor -LightSensor = AdafruitTSL2561() +LightSensor = Adafruit_TSL2561() # Enable auto gain switching between 1x and 16x # Default is False