def get_measurements(address, _): """ Measures and returns all available measurements for the room as a dictionnary. INPUT: address (None) address of sensehat (to ignore) temperature_correction (float, unused) correction to apply to measurement value, to account for external effects RETURNS: (Dict) dictionnary as {'luminosity': value1} """ # Initializes dictionnary of measurements collected all_values = { 'luminosity': None } try: if tsl2561 is not None: # Gets all measurements from Sensehat, and applies correction tsl2561_sensor = tsl2561.TSL2561(address) all_values['luminosity'] = tsl2561_sensor.lux() except (IOError, Exception) as e: # Something went wrong when retrieving the values. Log error. # NOTE : Happened once with Exception 'Sensor is saturated'. general_utils.log_error(-409, 'TSL2561', str(e)) ################## return all_values
def main(): sensor_data = { 'temperature': None, 'humidity': None, 'luminosity': None } ### SHT31: Temperature and Humidity Sensor ### sht31_instance = sht31.SHT31(SHT31_ADDRESS, SHT31_CHANNEL) sht31_result = sht31_instance.read() sensor_data['temperature'] = round(sht31_result[0], 2) sensor_data['humidity'] = round(sht31_result[1], 2) ### TSL2561: Luminosity Sensor ### tsl2561_instance = tsl2561.TSL2561(TSL2561_ADDRESS, TSL2561_CHANNEL) tsl2561_result = tsl2561_instance.read() sensor_data['luminosity'] = round(tsl2561_result[0], 1) client = boto3.client('cloudwatch') for i in sensor_data.keys(): metric_data = None metric_data = [ { 'MetricName': DEVICE_ID + '-' + i, 'Value': sensor_data[i], 'Unit': 'Count', 'Dimensions': [ { 'Name': 'Device', 'Value': DEVICE_ID } ] } ] client.put_metric_data(Namespace=NAMESPACE, MetricData=metric_data)
def light_level(self): try: sensor = tsl2561.TSL2561(self.i2c) lumen = sensor.read() return lumen except: print("Light sensor not connected") return "Not connected"
def _read(self, **kwargs): logger.debug("Reading TSL2561 sensor via i2c") try: lux_sensor = tsl2561.TSL2561() broadband, ir = lux_sensor._get_luminosity() lux = lux_sensor._calculate_lux(broadband, ir) except OSError as e: raise SensorNotAvailableException(e) logger.info("Read {} lux (br: {}, ir: {})".format(lux, broadband, ir)) return [lux, broadband, ir]
def create_message(mail_to, subject, device, smart_plug_ip_address): msg = MIMEMultipart() msg['To'] = mail_to msg['Subject'] = subject now = datetime.datetime.now() body = "Date: %s \n" % now.strftime("%Y-%m-%d %H:%M:%S") sht31_result = sht31.SHT31(SHT31_ADDRESS, SHT31_CHANNEL).read() tsl2561_result = tsl2561.TSL2561(TSL2561_ADDRESS, TSL2561_CHANNEL).read() body += "Temperature(C): %s \n" % round(sht31_result[0], 2) body += "Humidity(%%): %s \n" % round(sht31_result[1], 2) body += "Luminosity(lx): %s \n" % round(tsl2561_result[0], 1) body = MIMEText(body, 'plain', 'utf-8') msg.attach(body) command = ("pyhs100 --ip=%s on" % smart_plug_ip_address) os.system(command) time.sleep(3) command = ("fswebcam -d %s -r 1280x960 --jpeg 95 %s" % (device, IMAGE)) os.system(command) time.sleep(1) command = ("pyhs100 --ip=%s off" % smart_plug_ip_address) os.system(command) attachment = MIMEBase("image", "jpeg") file = open(IMAGE) attachment.set_payload(file.read()) file.close() command = "rm %s" % IMAGE os.system(command) Encoders.encode_base64(attachment) msg.attach(attachment) return msg
print('Not joined yet...') print('Network joined!') #create the socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set lorawan data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) ### ### set up sensor bme280 i2c = I2C(0, I2C.MASTER, baudrate=100000) bme = bme280.BME280(i2c=i2c) sensor = tsl2561.TSL2561(i2c) # read sensor data and send via lora while (True): #print(payload) # create lora socket # make the socket blocking s.setblocking(True) #send date #payload = {'temperature': bme.temperature, 'humidity': bme.humidity, "pressure": bme.pressure} #json_ = ujson.dumps(payload) #print(json_) #msg = struct.pack('s', json_)
import time from machine import I2C import tsl2561 import bh1750fvi # pins=(SDA, SCL) i2c = I2C(0, I2C.MASTER, baudrate=100000, pins=('P23', 'P22')) i2c2 = I2C(0, I2C.MASTER, baudrate=100000, pins=('P10', 'P11')) addr = i2c.scan()[0] addr2 = i2c2.scan()[0] print("Device addresses: ", addr, addr2) light_sensor_tsl2561 = tsl2561.TSL2561(i2c, addr) light_sensor_bh1750fvi = bh1750fvi.BH1750FVI(i2c2, addr2) light_sensor_tsl2561.integration_time(402) light_sensor_tsl2561.gain(16) light_sensor_tsl2561._update_gain_and_time() while True: # print light value every 10 seconds light_sensor_tsl2561_val = light_sensor_tsl2561.read() light_sensor_bh1750fvi_val = light_sensor_bh1750fvi.read() print("light_sensor_tsl2561_val: ", light_sensor_tsl2561_val) print("light_sensor_bh1750fvi_val: ", light_sensor_bh1750fvi_val) print("\n") time.sleep(10)
def displaySensor(data, names, units): for i in range(len(data)): print i, data[i] lcd.clear() lcd.message(names[i] + "\n") if (isinstance(data[i], basestring)): lcd.message(data[i] + " " + units[i]) else: lcd.message('{:0.3f}'.format(data[i]) + " " + units[i]) sleep(2) sensors = [] sensors.append(timesensor.TimeSensor()) sensors.append(si7021.SI7021Sensor()) sensors.append(tsl2561.TSL2561()) sensors.append(mpl3115a2.MPL3115A2()) if os.path.exists(logname): f = open(logname, 'a') else: f = open(logname, 'w') names = [] units = [] for s in sensors: names = names + s.getNames() units = units + s.getUnits() f.write(','.join(names) + "\n") f.write(','.join(units) + "\n") while (1):
# Networked sensor script import dht import tsl2561 import json from time import sleep from machine import I2C, Pin, unique_id from umqtt.simple import MQTTClient if __name__ == "__main__": # Setup sensors d = dht.DHT22(Pin(2)) #D4 on NodeMCU board is GPIO 2 i2c = I2C(-1, Pin(5), Pin(4)) #D1 & D2 on NodeMCU board. l = tsl2561.TSL2561(i2c) l.integration_time(402) #Adjusts the length of exposure. l.gain(16) # Set to 1 or 16 but no values between. 16 is more sensitive. # Setup MQTT broker = "192.168.1.64" # ip address of computer running the broker. client_id = "multi_1" # client id. client = MQTTClient(client_id, broker) client.connect() print("Connected to {}".format(broker)) while True: try: # Take sensor measurement!s
Demo code for Qwiic Light Sensor TSL2561, tested on pyboard Auther: Alex Chu Website: www.smart-prototyping.com Email: [email protected] Qwiic Light Sensor TSL2561 product link: https://www.smart-prototyping.com/Zio-Qwiic-Light-Sensor-TSL2561 Display product link: https://www.smart-prototyping.com/Zio-OLED-Display-0-91-in-128-32-Qwiic.html Library: https://github.com/adafruit/micropython-adafruit-tsl2561 """ from machine import Pin, I2C import tsl2561 from ssd1306 import SSD1306_I2C i2c = I2C(sda=Pin("Y10"), scl=Pin("Y9")) oled = SSD1306_I2C(128, 32, i2c, addr=0x3c) light = tsl2561.TSL2561(i2c=i2c, address=0x39) pyb.delay(100) light.active(True) pyb.delay(500) while True: value = round(light.read(), 2) oled.fill(0) oled.text("luminosity is:", 0, 0) oled.text(str(value) + " lux", 0, 20) pyb.delay(10) oled.show() pyb.delay(100)
import time from machine import I2C import tsl2561 # SDA='P23', SCL='P22' i2c = I2C(0, I2C.MASTER, baudrate=100000, pins=('P23', 'P22')) addr = i2c.scan() print("Device addresses: ", addr) addr = addr[0] tsl = tsl2561.TSL2561(i2c, addr) while True: lum = tsl.read() print("Lum: ", lum) time.sleep(1)
#function to read user input for Mode E: Custom def custom_mode(): Threshold_Temp = input("Threshold Temperature: ") Threshold_RH = input("Threshold Humidity: ") Threshold_Light = input("Threshold Light Intensity: ") value = "You have selected:\n" value += "Threshold Temperature: " + str(Threshold_Temp) + " C\n" value += "Threshold Humidity: "+ str(Threshold_RH)+" %\n" value += "Threshold Light Intensity: " + str(Threshold_Light)+" lux\n" print(value) i2c = I2C(scl=Pin(5),sda=Pin(4), freq=100000) #address of the slave thsensor = si7021.Si7021(i2c) #connect ESP8266 to temperature and humidity sensor luxsensor = tsl2561.TSL2561(i2c) #connect ESP8266 to light sensor #connection to wifi print('Connecting Wifi...') ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sta_if =network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('Andy','12345678') #used our own hotspot while not sta_if.isconnected(): pass print('Wifi Connected') #connection to MQTT ( thingspeak mqtt broker used here ) print('Connecting ThingSpeak...')
def _get_light_measure(): _light_sensor = tsl2561.TSL2561(_i2c, address=0x39) return (("light", _light_sensor.read()), )
Used to publish reading of brewed tea to server ''' import network from umqtt.simple import MQTTClient import machine import ubinascii import ujson import utime import tsl2561 import si7021 from machine import I2C, Pin # Set sensor Settings i2c_lux = I2C(scl=Pin(5), sda=Pin(4)) sensor_lux = tsl2561.TSL2561(i2c_lux) sensor_lux.gain(16) sensor_lux.integration_time(402) sensor_temp = si7021.Si7021(64) # Connect to broker ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('EEERover', 'exhibition') client = MQTTClient(machine.unique_id(), '192.168.0.10') client.connect() # Publish reading payload = ujson.dumps({
#! /usr/bin/python3 import tsl2561 import time #Create a sensor object tsl = tsl2561.TSL2561(0x39) #Reset the device tsl.turn_on(False) tsl.turn_on(True) #Set to x16 gain with a 402 ms integration cycle tsl.set_gain("high") tsl.set_integration_cycle(2) try: while True: print("Lux = " + str(tsl.lux())) time.sleep(0.5) except KeyboardInterrupt: print("Exiting.")