def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the sensor platform.""" try: # initializing I2C bus using the auto-detected pins i2c = busio.I2C(board.SCL, board.SDA) # initializing the sensor if config[CONF_I2C_ADDRESS] == None: si7021 = adafruit_si7021.SI7021(i2c) else: si7021 = adafruit_si7021.SI7021(i2c, address=config[CONF_I2C_ADDRESS]) except ValueError as error: # this usually happens when the board is I2C capable, but the device can't be found at the configured address if str(error.args[0]).startswith("No I2C device at address"): _LOGGER.error( "%s. Hint: Check wiring!", error.args[0], ) raise PlatformNotReady() from error _LOGGER.error(error) return name = config[CONF_NAME] add_entities([ Si7021TemperatureSensor(si7021, name), Si7021HumiditySensor(Si7021, name) ])
def initialize(self): import adafruit_si7021 from adafruit_extended_bus import ExtendedI2C self.sensor = adafruit_si7021.SI7021( ExtendedI2C(self.input_dev.i2c_bus), address=int(str(self.input_dev.i2c_location), 16))
def read_sensor(location="", extra="", sensor_name="", *args): # Try importing the modules then give-up and report to user if it fails import datetime try: import board import busio import adafruit_si7021 except: print("adafruit_si7021 module not installed, install using the command;") print(" sudo pip3 install adafruit-circuitpython-si7021") return None # set up and read the sensor try: i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) temperature = sensor.temperature humidity = sensor.relative_humidity if humidity == None or temperature == None or humidity > 101: print("--problem reading si7021") return None else: humidity = round(humidity,2) temperature = round(temperature, 2) logtime = datetime.datetime.now() return [['time',logtime], ['humid', humidity], ['temperature', temperature]] except: print("--problem reading si7021") return None
def start(self): """Getting the bus""" if self.bus is None: raise KeyError("Bus missing for SI7021Sensor") # Initialize the hardware driver. try: # Vanilla MicroPython 1.11 and Pycom MicroPython 1.9.4 if platform_info.vendor in [ platform_info.MICROPYTHON.Vanilla, platform_info.MICROPYTHON.Pycom ]: from SI7021 import SI7021 self.driver = SI7021(i2c=self.bus.adapter) # Adafruit CircuitPython elif platform_info.vendor == platform_info.MICROPYTHON.RaspberryPi: import adafruit_si7021 self.driver = adafruit_si7021.SI7021(i2c_bus=self.bus.adapter, address=self.address) else: raise NotImplementedError( 'Si7021 driver not implemented on this platform') return True except Exception as ex: log.exc(ex, 'SI7021 hardware driver failed')
def main(args): """Main function. Read from the sensor and upload it to adafruit.""" i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) temperature = sensor.temperature humidity = sensor.relative_humidity # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). if humidity is not None and temperature is not None: # Convert the temperature to Fahrenheit. temperature = temperature * 9 / 5.0 + 32 print('Temp={0:0.1f}F Humidity={1:0.1f}%'.format( temperature, humidity)) # Upload the data aio = Client('ryhajlo', 'b5fe0936d9a84629a2d49cd45858fc67') try: aio.send('indoor-temperature', temperature) except RequestError: print("Cannot send temperature data") try: aio.send('indoor-humidity', humidity) except RequestError: print("Cannot send humidity data") else: print('Failed to get reading. Try again!') sys.exit(1)
def __init__(self, channel, tca=None, precision=3): if tca: channel = tca[channel] device = adafruit_si7021.SI7021(channel) self.device = device self.precision = precision self.MM_TO_INCH = 0.0393701 self.accepted_units = ["f", "c"]
def __init__(self): self.i2c = busio.I2C(board.SCL, board.SDA, frequency=100000) self.sgp30 = adafruit_sgp30.Adafruit_SGP30(self.i2c) self.si7021 = adafruit_si7021.SI7021(board.I2C()) print("SGP30 serial #", [hex(i) for i in self.sgp30.serial]) self.sgp30.iaq_init() # self.sgp30.set_iaq_baseline(0x8973, 0x8AAE) super().__init__()
def __init__(self): self.i2c = board.I2C() self.ina260 = adafruit_ina260.INA260( self.i2c, 0x41) # important! to change to 0x41 self.si7021 = adafruit_si7021.SI7021(self.i2c) self.ds3502 = adafruit_ds3502.DS3502(self.i2c) print("Device initialized")
def main(verbose): """ Main loop of the app & where all the fun happens. Args: verbose (bool): If True, a lot of info is printed during execution. """ recent_post_status_codes_ok = collections.deque( [True] * CONFIG_DATA['num_recent_post_status_codes_to_look_at'], maxlen=CONFIG_DATA['num_recent_post_status_codes_to_look_at']) # Our interface objects to the Adafruit SI7021 temp & humidity sensor i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) try: while True: # Only way to exit is user hitting Ctrl-C temp_c = sensor.temperature temp_f = int(round(c_to_f(temp_c), 0)) # only want integer portion humidity = int(round(sensor.relative_humidity, 0)) # only want integer portion now = datetime.datetime.now() timestamp = now.strftime(TIMESTAMP_FORMAT) # Package up the data to send to the RESTful API packaged_data = { 'dev_id': CONFIG_DATA['device_id'], 'ts': timestamp, 'temp': temp_f, 'humidity': humidity } if verbose: print('Sending Message...\n =>Data :{}'.format(packaged_data), flush=True) response = requests.post(CONFIG_DATA['post_readings_url'], json=packaged_data) if verbose: print(' <=Status:{}\n Content:{}'.format( response.status_code, response.content), flush=True) # Keep track of the most recent status codes; if none were successful, bail recent_post_status_codes_ok.append(response.status_code == 200) if not any(recent_post_status_codes_ok): print( 'ERROR: The most recent {} POSTs have failed; halting execution' .format( CONFIG_DATA['num_recent_post_status_codes_to_look_at'] )) break # A delay before sending the next reading time.sleep(CONFIG_DATA['delay_between_readings']) except KeyboardInterrupt: # Just fall back to main print('... Ctrl-C detected, ending ...', flush=True)
def get_si7021(): i2c = busio.I2C(board.SCL, board.SDA) while True: try: sensor = adafruit_si7021.SI7021(i2c) break except OSError: continue return sensor
def si7021(): print(colored("SI7021 started. . .", 'green')) si7021 = adafruit_si7021.SI7021(i2c) while True: temp = si7021.temperature humidity = si7021.relative_humidity with lock: database.create_record(conn, "Measurements", ("temp", temp)) database.create_record(conn, "Measurements", ("humidity", humidity)) time.sleep(measurement_interval)
def main(): databaseinit() i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) tsl = adafruit_tsl2561.TSL2561(i2c) print("Configuring TSL2561...") # Enable the light sensor tsl.enabled = True time.sleep(1) # Set gain 0=1x, 1=16x tsl.gain = 0 # Set integration time (0=13.7ms, 1=101ms, 2=402ms, or 3=manual) tsl.integration_time = 1 print("Getting readings...") # Get raw (luminosity) readings individually broadband = tsl.broadband infrared = tsl.infrared while True: lux = tsl.lux humidity = sensor.relative_humidity temperature = sensor.temperature print("\nTemperature: %0.1f C" % temperature) print("Humidity: %0.1f %%" % humidity) if lux is not None: print("Lux = {}".format(lux)) else: print( "Lux value is None. Possible sensor underrange or overrange.") lux = 0 a = { "awakenTime": str(int(math.ceil(timestamp()))), "humidity": str(int(math.ceil(humidity))), "lightValue": str(int(math.ceil(lux))), "temperature": str(int(math.ceil(temperature))) } try: db.child("userdata/" + login['localId']).push(a) print("Database writing success!") except: print( "Database cannot be written, check the permission on database") time.sleep(30.0)
def basic_temp_humid_test(n_iter): """ basic_temp_humid_test(n_iter) runs basic test on temp humid sensor to make sure hardware reads properlu """ i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) for _ in range(n_iter): print("\nTemperature: %0.1f C" % sensor.temperature) print("Humidity: %0.1f %%" % sensor.relative_humidity) time.sleep(2) i2c.deinit()
def read_sensor(sensor): try: i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) temperature = sensor.temperature humidity = sensor.relative_humidity if humidity == None or temperature == None or humidity > 101: print("--problem reading sensor on GPIO:" + sensor_gpio + "--") return '-1', '-1', '-1' else: humidity = round(humidity, 2) temperature = round(temperature, 2) logtime = datetime.datetime.now() return humidity, temperature, logtime except: print("--problem reading si7021") return '-1', '-1', '-1'
def three_sensor_test(n_iter): """ three_sensor_test(n_iter) runs basic test on all three sensors to make sure hardware reads properlu """ i2c = busio.I2C(board.SCL, board.SDA) temp_humid = adafruit_si7021.SI7021(i2c) light = adafruit_veml7700.VEML7700(i2c) moisture = MCP3001() for _ in range(n_iter): print("\nTemperature: %0.1f C" % temp_humid.temperature) print("Humidity: %0.1f %%" % temp_humid.relative_humidity) print("Ambient Light: %0.1f " % light.light) print("Moisture Level: %f " % moisture.value) time.sleep(2) i2c.deinit()
def func1(): # send to database while True: nowt = datetime.now() nowtt = ("{:d}-{:d}-{:d} {:d}:{:d}:{:d}".format(nowt.year, nowt.month, nowt.day, \ nowt.hour, nowt.minute, nowt.second)) waterlevel = analog_read(0) soil1 = analog_read(1) soil2 = analog_read(2) wastewater = analog_read(4) gas1 = analog_read(5) gas2 = analog_read(6) ec = analog_read(7) reading = (soil1 + soil2) / 2 # mushroom i = int(reading) j = int(waterlevel) gass1 = movafilter(fgas(gas1)) gass2 = movafilter(fgas(gas2)) deltag = math.fabs(gass1 - gass2) light = bus.read_i2c_block_data(addr, 0x10) lightconversed = (light[1] + (256 * light[0] / 1.2)) # use Try for prevent i2c error of si7021 try: i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) temp = sensor.temperature humid = sensor.relative_humidity except: temp = 0 humid = 0 insertPythonVaribleInTable(nowtt, j, pcw(wastewater), gass2, gass1, humid, temp, lightconversed, movafilter(fec(ec)), tempC) sleep(60)
def run(self) -> None: sensor = None influx = None while True: if not sensor: log.debug("Initializing temp sensor") sensor = adafruit_si7021.SI7021(board.I2C()) if not influx: log.debug("Initializing Influx client") client = InfluxDBClient(url=self._url, token=self._token, org=self._org) influx = client.write_api(write_options=SYNCHRONOUS) metrics = [ f'temperature,host={self._hostname} degrees_c={sensor.temperature}', f'humidity,host={self._hostname} humidity_pct={sensor.relative_humidity}', ] log.debug(f"Going to write to influx: {metrics}") try: influx.write(bucket=self._bucket, record=metrics) except: log.error("Failed to write to Influx. Will try to reconnect next time.") influx = None sleep(10)
def make_si7021(i2c_bus): return adafruit_si7021.SI7021(i2c_bus)
import csv import argparse from atmos import calculate import adafruit_si7021 def calculateAbsoluteHumidity(rel_humidity, temperature): temp_kelvin = temperature + 273.15 absolute_humidity = calculate('AH', RH=rel_humidity, p=1e5, T=temp_kelvin, debug=True)[0] # convert from kg/m^3 to g/m^3 absolute_humidity = absolute_humidity * 1000 return absolute_humidity # Humidity and temperature sensor si_7021_i2c = busio.I2C(board.SCL, board.SDA) temp_humid_sensor = adafruit_si7021.SI7021(si_7021_i2c) # sgp30_i2c = busio.I2C(board.SCL, board.SDA, frequency=100000) sgp30 = adafruit_sgp30.Adafruit_SGP30(sgp30_i2c) while True: temp = temp_humid_sensor.temperature relative_humidity = temp_humid_sensor.relative_humidity print("\nTemperature: %0.1f C" % temp) print("Humidity: %0.1f %%" % relative_humidity) absolute_humidity = calculateAbsoluteHumidity(relative_humidity, temp) print("Absolute Humidity: {} g/m^3".format(absolute_humidity)) time.sleep(2)
# # SI7021 # import board import digitalio import busio import time import adafruit_si7021 # Ensure automatic deinit with digitalio.DigitalInOut(board.SENSOR_POWER_ENABLE) as en: en.direction = digitalio.Direction.OUTPUT en.value = True time.sleep(0.1) # Important: sleep to let power stabilize with busio.I2C(board.SCL, board.SDA) as i2c: si7021 = adafruit_si7021.SI7021(i2c, address=0x40) while True: print("Temperature: %0.1f degC" % si7021.temperature) print("Humidity : %0.1f %%" % si7021.relative_humidity) time.sleep(2)
def __init__(self): i2c = busio.I2C(board.SCL, board.SDA) self.sensor = adafruit_si7021.SI7021(i2c)
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT """ Initializes the sensor, gets and prints readings every two seconds. """ import time import board import adafruit_si7021 # Create library object using our Bus I2C port sensor = adafruit_si7021.SI7021(board.I2C()) while True: print("\nTemperature: %0.1f C" % sensor.temperature) print("Humidity: %0.1f %%" % sensor.relative_humidity) time.sleep(2)
def __init__(self): self.sensor = adafruit_si7021.SI7021(board.I2C())
import RPi.GPIO as GPIO import board import busio i2c = busio.I2C(board.SCL, board.SDA) import time import adafruit_tsl2561 sensor0 = adafruit_tsl2561.TSL2561(i2c) import adafruit_si7021 sensor1 = adafruit_si7021.SI7021(i2c) import Adafruit_BMP.BMP085 as BMP085 sensor2 = BMP085.BMP085() while True: print('Lux: {}'.format(sensor0.lux)) print('Broadband: {}'.format(sensor0.broadband)) print('Infrared: {}'.format(sensor0.infrared)) print('Luminosity: {}'.format(sensor0.luminosity)) #print('Temperature: {} degrees C'.format(sensor1.temperature)) print('Humidity: {}%'.format(sensor1.relative_humidity)) print('Temp = {0:0.2f} *C'.format(sensor2.read_temperature())) print('Pressure = {0:0.2f} Pa'.format(sensor2.read_pressure())) #print ('Altitude = {0:0.2f} m'.format(sensor2.read_altitude())) #print ('Sealevel Pressure = {0:0.2f} Pa'.format(sensor2.read_sealevel_pressure()))
#temp&RH import time from micropython import const import board import busio import adafruit_si7021 import csv i2c_port = busio.I2C(board.SCL, board.SDA) _USER1_VAL = const(0x3A) sensor = adafruit_si7021.SI7021(i2c_port) print('Temperature: {} degrees C'.format(sensor.temperature)) print('Humidity: {}%'.format(sensor.relative_humidity)) temp = [] humid = [] endtime = time.time() + 21 while True: temp.append(sensor.temperature) humid.append(sensor.relative_humidity) if time.time() > endtime: break time.sleep(2) with open('temprh.csv', 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(temp) writer.writerow(humid)
class SensorData(threading.Thread): def __init__(): global sensor global uid self.temperature = sensor.temperature self.longitude = 0 self.latitude = 0 self.id = uid threading.Thread.__init__(self) global gpsd #bring it in scope gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.current_value = None self.running = True #setting the thread running to true def run(self): global gpsd while gpsp.running: gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer def toJsonfromSensor(self): dict = {} dict['id'] = self.id dict['temperature'] = self.temperature dict['latitude'] = self.latitude dict['longitude'] = self.longitude jsonf = json.dumps(dict) return jsonf if __name__ == '__main__': gpsp = SensorData() # create the thread mqtt_client = MqttClientConnector('geotemperature') host = 'test.mosquitto.org' topic = 'geotemperature' global sensor try: gpsp.start() # start it up while True: #It may take a second or two to get good data #print gpsd.fix.latitude,', ',gpsd.fix.longitude,' Time: ',gpsd.utc os.system('clear') sensor = adafruit_si7021.SI7021(i2c) gpsp.latitude = gpsd.fix.latitude gpsp.longitude = gpsd.fix.longitude gpsp.temperature = sensor.temperature json_data = gpsp.toJsonfromSensor() mqtt_client.publish(topic,json_data,host) print print ' GPS reading' print '----------------------------------------' print 'latitudeitude ' , gpsd.fix.latitudeitude print 'longitudeitude ' , gpsd.fix.longitudeitude print 'time utc ' , gpsd.utc,' + ', gpsd.fix.time print 'altitude (m)' , gpsd.fix.altitude time.sleep(10) #set to whatever except (KeyboardInterrupt, SystemExit): #when you press ctrl+c print "\nKilling Thread..." gpsp.running = False gpsp.join() # wait for the thread to finish what it's doing print "Done.\nExiting."
# SPDX-License-Identifier: MIT """ Example for using the SGP30 with CircuitPython and the Adafruit library""" import time # board automatically detects the board being used and # imports * from appropriate board module/package import board # busio defines classes for each bus type, e.g. I2C for this case import busio import adafruit_sgp30 import adafruit_si7021 i2c = busio.I2C(board.SCL, board.SDA, frequency=100000) sgp30 = adafruit_sgp30.Adafruit_SGP30(i2c) si7021 = adafruit_si7021.SI7021(i2c) print("SGP30 serial #", [hex(i) for i in sgp30.serial]) sgp30.iaq_init() # sgp30.set_iaq_baseline(0x8973, 0x8AAE) elapsed_sec = 0 while True: format = "Temp: {0:4.2f} \t Hum: {1:4.2f} \t" + \ "eCO2: {2:d} ppm \t TVOC = {3:d} ppb" print(format.format(si7021.temperature, si7021.relative_humidity, sgp30.eCO2, sgp30.TVOC)
def __init__(self, i2c_channel): self.channel = i2c_channel sensor = adafruit_si7021.SI7021(i2c_channel) self.sensor = sensor
import busio import adafruit_adxl34x import adafruit_si7021 import adafruit_veml7700 i2c1 = busio.I2C(board.SCL, board.SDA) i2c2 = busio.I2C(board.SCL, board.SDA) i2c3 = busio.I2C(board.SCL, board.SDA) # For ADXL343 accelerometer = adafruit_adxl34x.ADXL343(i2c1) accelerometer.enable_motion_detection() while True: try: sensor = adafruit_si7021.SI7021(i2c2) break except: continue veml7700 = adafruit_veml7700.VEML7700(i2c3) while True: print("******************************") print("\nAcceleration: %f %f %f" % accelerometer.acceleration) print("Motion detected: %s" % accelerometer.events["motion"]) print("\nTemperature: %0.1f C" % sensor.temperature) print("Humidity: %0.1f %%" % sensor.relative_humidity) print("\nAmbient light:", veml7700.light) time.sleep(0.5)
import typer import adafruit_si7021 import adafruit_tca9548a import board import busio # Initialize I2C bus and sensor. i2c = busio.I2C(board.SCL, board.SDA) # mux tca2 = adafruit_tca9548a.TCA9548A(i2c, address=0x72) # each sensor rht_sensor = adafruit_si7021.SI7021(tca2[2]) def main(num: int = 100): for i in range(num): try: a_t = rht_sensor.temperature * 1.8 + 32 except OSError: a_t = None try: a_rh = rht_sensor.relative_humidity except OSError: a_rh = None print(f"env. {a_t: 0.3f}*f {a_rh: 0.3f}%") time.sleep(1.0)