def __init__(self): bus = busio.I2C(board.SCL, board.SDA) self.sea_level_pressure = None # init bme280 try: self.bme280 = adafruit_bme280.Adafruit_BME280_I2C( bus, address=BME280_ADDR) except: self.bme280 = NoOp() print("WARNING: could not connect bme280") # init bmp388 try: self.bmp388 = adafruit_bmp3xx.BMP3XX_I2C(bus, address=BMP388_ADDR) self.bmp388.pressure_oversampling = 8 self.bmp388.temperature_oversampling = 2 except: self.bmp388 = NoOp() print("WARNING: could not connect bmp388") # init sht31d try: self.sht31d = adafruit_sht31d.SHT31D(bus, address=SHT31D_ADDR) except: self.sht31d = NoOp() print("WARNING: could not connect sht31d")
def main(): # SHT31D Temperature and Humidity sensor i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) # TMP36 Temperature Sensor backup_sensor = MCP3008(channel=TEMPERATURE_SENSOR_CHANNEL) # SHT31D Measurements sht31d_temperature_c = sensor.temperature sht31d_temperature_f = round((sht31d_temperature_c * (9 / 5)) + 32, 1) sht31d_temperature_f_adj = round(sht31d_temperature_f + calibrations['SHT31D']['temperature'], 1) sht31d_humidity = int(sensor.relative_humidity) sht31d_humidity_adj = int(sht31d_humidity + calibrations['SHT31D']['humidity']) # TMP36 Measurements temperature_voltage = backup_sensor.voltage tmp36_temperature_c = get_temperature_c(temperature_voltage, round_digits=1) tmp36_temperature_f = round((tmp36_temperature_c * (9 / 5)) + 32, 1) tmp36_temperature_f_adj = round(tmp36_temperature_f + calibrations['TMP36']['temperature'], 1) # Save Measurements print('logging {}F, {}% Humidity '.format(sht31d_temperature_f_adj, sht31d_humidity_adj)) environment_models.AirMeasurement.objects.create( sht31d_temperature_c=sht31d_temperature_c, sht31d_temperature_f=sht31d_temperature_f, sht31d_temperature_f_adj=sht31d_temperature_f_adj, sht31d_humidity=sht31d_humidity, sht31d_humidity_adj=sht31d_humidity_adj, tmp36_temperature_c=tmp36_temperature_c, tmp36_temperature_f=tmp36_temperature_f, tmp36_temperature_f_adj=tmp36_temperature_f_adj )
def read_sensor(location=""): # Try importing the modules then give-up and report to user if it fails import datetime try: import board import busio import adafruit_sht31d except: print("adafruit_sht31d module not installed, install using the command;") print(" sudo pip3 install adafruit-circuitpython-sht31d") return None # set up and read the sensor try: i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c, location) temperature = sensor.temperature humidity = sensor.relative_humidity if humidity == None or temperature == None or humidity > 101: print("--problem reading sht31d") 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 sht31d") return None
def init_hygro(): i2c = board.I2C() # init i2c bus try: hygro = adafruit_sht31d.SHT31D(i2c) # init hygrometer return hygro except: print("icarus.init_hygro() failed") return None
def __init__(self): # Define I2C: self._i2c = board.I2C() # Define touch: # Initially, self._touches stores the pin used for a particular touch. When that touch is # used for the first time, the pin is replaced with the corresponding TouchIn object. # This saves a little RAM over using a separate read-only pin tuple. # For example, after `clue.touch_2`, self._touches is equivalent to: # [board.D0, board.D1, touchio.TouchIn(board.D2)] self._touches = [board.D0, board.D1, board.D2] self._touch_threshold_adjustment = 0 # Define buttons: self._a = digitalio.DigitalInOut(board.BUTTON_A) self._a.switch_to_input(pull=digitalio.Pull.UP) self._b = digitalio.DigitalInOut(board.BUTTON_B) self._b.switch_to_input(pull=digitalio.Pull.UP) self._gamepad = gamepad.GamePad(self._a, self._b) # Define LEDs: self._white_leds = digitalio.DigitalInOut(board.WHITE_LEDS) self._white_leds.switch_to_output() self._pixel = neopixel.NeoPixel(board.NEOPIXEL, 1) self._red_led = digitalio.DigitalInOut(board.L) self._red_led.switch_to_output() # Define audio: self._mic = audiobusio.PDMIn( board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000, bit_depth=16, ) self._sample = None self._samples = None self._sine_wave = None self._sine_wave_sample = None # Define sensors: # Accelerometer/gyroscope: self._accelerometer = adafruit_lsm6ds.LSM6DS33(self._i2c) # Magnetometer: self._magnetometer = adafruit_lis3mdl.LIS3MDL(self._i2c) # DGesture/proximity/color/light sensor: self._sensor = adafruit_apds9960.apds9960.APDS9960(self._i2c) # Humidity sensor: self._humidity = adafruit_sht31d.SHT31D(self._i2c) # Barometric pressure sensor: self._pressure = adafruit_bmp280.Adafruit_BMP280_I2C(self._i2c) # Create displayio object for passing. self.display = board.DISPLAY
def initialize(self): import adafruit_sht31d from adafruit_extended_bus import ExtendedI2C try: self.sensor = adafruit_sht31d.SHT31D( ExtendedI2C(self.input_dev.i2c_bus), address=int(str(self.input_dev.i2c_location), 16)) except: self.logger.exception("Setting up sensor")
def BuildBSHT3xAHumiditySensor(self, sensorType): try: if self.BSHT30A == None: self.BSHT30A = adafruit_sht31d.SHT31D(self.i2c) sensor = bsht30HumiditySensor(self.BSHT30A) # ealier version of circuit python uses this, #except AM2320DeviceNotFound : except ValueError: log.error(sensorType + " not found continue as None") self.am2315 = None sensor = None return sensor
def read_sht31(address=0x44): """ Read temperature and humidity data from a SHT31 sensor :param int address: 0x44 or 0x45 defaults to 0x44 """ if address not in SHT31_ADDRESSES: raise ValueError( "Invalid address {address} must be one of {addresses}".format( address=address, addresses=SHT31_ADDRESSES)) i2c = I2C(SCL, SDA) sensor = sht31d.SHT31D(i2c, address=address) return (round(sensor.temperature, 1), round(sensor.relative_humidity, 1))
def read_config_file(self): config = configparser.ConfigParser() config.read(self.configfile) settings = config['DEFAULT'] #Auth0 Auth Settings self.auth0_request_url = settings.get('auth0_request_url') self.auth0_grant_type = settings.get('auth0_grant_type') self.auth0_client_id = settings.get('auth0_client_id') self.auth0_client_secret = settings.get('auth0_client_secret') self.auth0_audience = settings.get('auth0_audience') #Device Master Settings self.device_id = settings.get('device_id') if self.debug == True: self.measurement_frequency = 30 self.measurement_delay = 2 print('Starting in debug mode') else: self.measurement_frequency = int( settings.get('measurement_frequency')) self.measurement_delay = int(settings.get('measurement_delay')) if self.dummy_data == False: pm_sensor_path = settings.get('pm_sensor_device') self.pm_sensor = SDS011(pm_sensor_path, use_query_mode=True) i2c = busio.I2C(board.SCL, board.SDA) self.temp_sensor = adafruit_sht31d.SHT31D(i2c) self.baro_sensor = adafruit_sht31d.SHT31D(i2c) selt.temp_offset = float(settings.get('temperature_correction')) else: self.pm_sensor = None self.temp_sensor = None self.baro_sensor = None print( 'Starting in dummy data mode - remember to delete bad data from server' ) #Upload endpoint settings self.measurement_endpoint = settings.get('measurement_endpoint')
def ReadSensor(Sensor, Pin): logger = SetupLogger().getLogger(__name__) if 'DHT' in Sensor: # using Adafruit_DHT module to read the sensor try: import Adafruit_DHT except : logger.error('Adafruit_DHT module is not installed correctly! Try pip3 install Adafruit_DHT? Abort now!') sys.exit() DHT_Sensor_Map = {"DHT11": Adafruit_DHT.DHT11, "DHT22": Adafruit_DHT.DHT22} sensor = DHT_Sensor_Map[Sensor] humidity, temperature = Adafruit_DHT.read_retry(sensor, Pin) if humidity is None or temperature is None : logger.error('Can not read data from {0} in PIN {1}! Abort!'.format(Sensor, Pin)) sys.exit() return humidity, temperature elif 'SHT3X' in Sensor: # using adafruit_sht31d module to read the data try: import board, busio, adafruit_sht31d except: logger.error('board, busio, adafruit_sht31d modules were not properly installed! Abort!') sys.exit() i2c = busio.I2C(board.SCL, board.SDA) I2C_sensor = adafruit_sht31d.SHT31D(i2c) humidity = I2C_sensor.relative_humidity temperature = I2C_sensor.temperature if humidity is None or temperature is None : logger.error('Can not read data from {0} in PIN {1}! Abort!'.format(Sensor, Pin)) sys.exit() logger.info('Turn on the heater for 1 second') I2C_sensor.heater = True time.sleep(1) I2C_sensor.heater = False return humidity, temperature else: logger.error('Not a supported sensor type! Abort!') sys.exit()
def __init__(self): # Define I2C: self._i2c = cutebot._i2c # Define buttons: self._a = digitalio.DigitalInOut(board.BUTTON_A) self._a.switch_to_input(pull=digitalio.Pull.UP) self._b = digitalio.DigitalInOut(board.BUTTON_B) self._b.switch_to_input(pull=digitalio.Pull.UP) self._gamepad = gamepad.GamePad(self._a, self._b) # Define LEDs: self._white_leds = digitalio.DigitalInOut(board.WHITE_LEDS) self._white_leds.switch_to_output() self._pixel = neopixel.NeoPixel(board.NEOPIXEL, 1) self._red_led = digitalio.DigitalInOut(board.L) self._red_led.switch_to_output() # Define audio: self._mic = audiobusio.PDMIn( board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000, bit_depth=16, ) self._sample = None self._samples = None self._sine_wave = None self._sine_wave_sample = None # Define sensors: # Accelerometer/gyroscope: self._accelerometer = adafruit_lsm6ds.lsm6ds33.LSM6DS33(self._i2c) # Magnetometer: self._magnetometer = adafruit_lis3mdl.LIS3MDL(self._i2c) # DGesture/proximity/color/light sensor: self._sensor = adafruit_apds9960.apds9960.APDS9960(self._i2c) # Humidity sensor: self._humidity = adafruit_sht31d.SHT31D(self._i2c) # Barometric pressure sensor: self._pressure = adafruit_bmp280.Adafruit_BMP280_I2C(self._i2c) # Create displayio object for passing. self.display = board.DISPLAY
def connectSensors(): global sensor, ss #Connect to sensors try: #Temp/humidity sensor sensor = adafruit_sht31d.SHT31D(i2c, i2caddress) #Soil sensors #ss.insert(0, Seesaw(i2c, addr=0x36)) #ss.insert(1, Seesaw(i2c, addr=0x37)) #ss.insert(2, Seesaw(i2c3, addr=0x36)) #ss.insert(3, Seesaw(i2c3, addr=0x37)) except Exception as e: logger.debug("Could not get SHT31-D Temp/Humidity or soil sensors: " + str(e)) else: return str("ok")
def _read_sensor(self, previous_sensor_data): try: i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) current_time = datetime.datetime.now().replace( microsecond=0).isoformat() current_temp = round(sensor.temperature, 1) current_hum = round(sensor.relative_humidity, 1) return [current_time, current_temp, current_hum] except (RuntimeError, ValueError, OSError) as e: print(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S - "), end='', flush=True) print(e, file=sys.stderr, flush=True) return previous_sensor_data
def __init__(self, address): try: i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c, address) self.humedad = sensor.relative_humidity self.temperatura = sensor.temperature # Recoge el error de lectura del canal SDA except (ValueError, OSError): logging.error('El sensor SHT31 ha dejado de funcionar.') self.humedad = -100 self.temperatura = -100
def load_data(self): data = None try: data = {} # Used 2 fixed known addresses i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) sensor.repeatability = adafruit_sht31d.REP_MED sensor.mode = adafruit_sht31d.MODE_SINGLE data['temperature'] = float(sensor.temperature) data['humidity'] = float(sensor.relative_humidity) except Exception as ex: print(ex) return data
def main(): # initialize I2C i2c = board.I2C() # initialize sensors bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c) sht31d = adafruit_sht31d.SHT31D(i2c) # initialize BLE ble = BLERadio() # create custom advertisement object advertisement = IOTGAdvertisement() # set device name ble.name = "IOTG1" # set initial value # will use only first 5 chars of name advertisement.md_field = ble.name[:5] + "0000" # BLRE advertising interval in seconds BLE_ADV_INT = 0.2 # start BLE advertising ble.start_advertising(advertisement, interval=BLE_ADV_INT) # main loop while True: # print values - this will be available on serial print("Temperature: {:.1f} C".format(bmp280.temperature)) print("Humidity: {:.1f} %".format(sht31d.relative_humidity)) # get sensor data T = int(bmp280.temperature) H = int(sht31d.relative_humidity) # stop advertsing ble.stop_advertising() # update advertisement data advertisement.md_field = ble.name[:5] + chr(T) + chr(H) + "00" # start advertising ble.start_advertising(advertisement, interval=BLE_ADV_INT) # sleep for 2 seconds time.sleep(2)
import time import board import busio import adafruit_sht31d # Create library object using our Bus I2C port i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) loopcount = 0 while True: print("\nTemperature: %0.1f C" % sensor.temperature) print("Humidity: %0.1f %%" % sensor.relative_humidity) loopcount += 1 time.sleep(2) # every 10 passes turn on the heater for 1 second if loopcount == 10: loopcount = 0 sensor.heater = True print("Sensor Heater status =", sensor.heater) time.sleep(1) sensor.heater = False print("Sensor Heater status =", sensor.heater)
i2c = busio.I2C(board.SCL, board.SDA) # sensor addresses # Temperature - MCP9808 (top/bottom, left/right interior array position) temp_TL_array = Sensor(adafruit_mcp9808.MCP9808(i2c, address=0x18), get_i2c_temp, None) # pos1, left-upper rail temp_BL_array = Sensor(adafruit_mcp9808.MCP9808(i2c, address=0x19), get_i2c_temp, None) # pos2, left-lower rail temp_TR_array = Sensor(adafruit_mcp9808.MCP9808(i2c, address=0x1A), get_i2c_temp, None) # pos3, right-upper rail temp_BR_array = Sensor(adafruit_mcp9808.MCP9808(i2c, address=0x1B), get_i2c_temp, None) # pos4, right-lower rail temp_peltier = Sensor(adafruit_mcp9808.MCP9808(i2c, address=0x1C), get_i2c_temp, None) # pos5, peltier heat sink # Humidity & Temp - SHT30-D Weatherproof temp_humd_indoor = Sensor(adafruit_sht31d.SHT31D(i2c), get_i2c_temp, get_i2c_humd) # pos7, inside gc # Humidity & Temp - HTS221 Outdoor temp_humd_outdoor = Sensor(adafruit_hts221.HTS221(i2c), get_i2c_temp, get_i2c_humd) # pos8, outside gc # --- 1W Sensor Initialize --- # 1-wire DS18B20 digital temp sensor addresses os.system('modprobe w1-gpio') os.system('modprobe w1-therm') # w1 address temp_h20 = Sensor('28-8a2017eb8dff', get_w1_temp, None) # pos6, in water reservoir # -- I2C PWM Control Initialize --- pca = adafruit_pca9685.PCA9685(i2c)
def main(): # Soil moisture sensors moisture_sensors = {channel: MCP3008(channel=channel) for channel in MOISTURE_SENSOR_CHANNELS} # TMP36 Temperature Sensor temperature_sensor = MCP3008(channel=TEMPERATURE_SENSOR_CHANNEL) # SHT31D Temperature and Humidity sensor i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) # Hue bridge = Bridge(BRIDGE_IP) bridge.connect() lights = bridge.get_light_objects('id') while True: state_dict = dict() message = "" for channel in moisture_sensors: value = moisture_sensors[channel].value soil_moisture = get_humidity_percentage(value) state_dict['moisture_{}'.format(channel)] = { 'voltage': moisture_sensors[channel].voltage, 'value': value, 'soil_moisture': soil_moisture } message += "| Plant {}: {}% ".format(channel, soil_moisture) # Blue is hue 45808 sat 254 # normal hue 8402 sat 140 if lights[LIGHTS[channel]].on: if soil_moisture < DRY_CUTOFF: print("dry soil detected, turning light blue") lights[LIGHTS[channel]].hue = 45808 lights[LIGHTS[channel]].saturation = 254 elif lights[LIGHTS[channel]].hue == 45808: print("Wet soil but light blue, turning back to normal") lights[LIGHTS[channel]].hue = 8402 lights[LIGHTS[channel]].saturation = 140 else: pass # print("Sensor {}: {}".format(channel, value)) # TMP36 reading temperature_voltage = temperature_sensor.voltage temperature = get_temperature_f(temperature_voltage, round_digits=1) state_dict['temperature'] = { 'voltage': temperature_voltage, 'fahrenheit': temperature, } temperature_message = "| TMP36 Temperature: {}F {}Fc".format( temperature, round(temperature + calibrations['TMP36']['temperature'], 1) ) # SHT31D reading SHT31D_temp = round((sensor.temperature * (9 / 5)) + 32, 1) SHT31D_relative_humidity = int(sensor.relative_humidity) SHT_message = '| SHT31D Temperature: {}F {} Fc Humidity: {}% '.format( SHT31D_temp, round(SHT31D_temp + calibrations['SHT31D']['temperature'], 1), SHT31D_relative_humidity) print(temperature_message + SHT_message + message) time.sleep(.5)
import machine import adafruit_sht31d # Create library object using our Bus I2C port i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21)) # esp32 sensor = adafruit_sht31d.SHT31D(i2c, address=69) print("\033[1mSensor\033[0m = SHT31-D") print("\033[1mSerial Number\033[0m = ", sensor.serial_number, "\n") for i in range(3): if i == 0: sensor.repeatability = adafruit_sht31d.REP_LOW print("\033[1m\033[36mLow Repeatability:\033[0m\n") if i == 1: sensor.repeatability = adafruit_sht31d.REP_MED print("\n\033[1m\033[36mMedium Repeatability:\033[0m\n") if i == 2: sensor.repeatability = adafruit_sht31d.REP_HIGH sensor.clock_stretching = False print("\n\033[1m\033[36mHigh Repeatability:\033[0m") # print("\033[1m\033[95mClock Stretching:\033[0m \033[92mEnabled\033[0m\n") for itr in range(3): print("\033[1mTemperature:\033[0m %0.3f ºC" % sensor.temperature) print("\033[1mHumidity:\033[0m %0.2f %%" % sensor.relative_humidity, "\n")
def __init__(self): self._sensor = adafruit_sht31d.SHT31D(i2c_bus=busio.I2C(24, 23))
from prometheus_client import start_http_server, Gauge from gpiozero import DiskUsage, LoadAverage, CPUTemperature import time import board import busio import adafruit_sht31d import adafruit_tsl2591 if __name__ == '__main__': # Start up the server to expose the metrics. start_http_server(8000) # Connect to I2C sensors i2c = busio.I2C(board.SCL, board.SDA) sht31dSensor = adafruit_sht31d.SHT31D(i2c) #Humidity / Temperature Sensor tsl12591Sensor = adafruit_tsl2591.TSL2591(i2c) #Light Sensor # Define guages humidity = Gauge('grow_relative_humidity_percentage', 'Grow Tent Relative Humidity Percentage') temp = Gauge('grow_temperature', 'Grow Tent Temperature', ['units']) light = Gauge('grow_light', 'Grow Tent Light', ['spectrum']) pi = Gauge('rpi', 'Raspberry Pi', ['internal_device']) # Capture Metrics while True: currentTemp = sht31dSensor.temperature temp.labels('fahrenheit').set((currentTemp * (9 / 5)) + 32) temp.labels('celsius').set(currentTemp) humidity.set(sht31dSensor.relative_humidity)
HOSTNAME=gethostname() # Output path data_root = '/home/pi' # creat serial instance for gps on uart ser = serial.Serial(port='/dev/ttyS0', baudrate=9600, timeout=3000) # create I2C instance for pressure and RH\T i2c = busio.I2C(board.SCL, board.SDA) # Create instance of Pressure sensor PP_sen = adafruit_mpl3115a2.MPL3115A2(i2c) # Create instance of Sht31D RH/T sensor SHT_sen = adafruit_sht31d.SHT31D(i2c) #create file today = datetime.utcnow().strftime('%Y-%m-%d') outfile = os.path.join(data_root, HOSTNAME + '-' + today + '.csv') f = open(outfile,'a') # append to exisiting file or creae new one f.close count = 0 while True: data = ser.readline() data_string = ''.join([chr(b) for b in data]) if data_string[0:6] == '$GPGGA': #get two of thes per second gps_msg1 = data_string
import adafruit_sdcard import storage import adafruit_pcf8523 import adafruit_sht31d # Get battery and system voltage vbat_voltage = AnalogIn(board.VOLTAGE_MONITOR) dvdr_voltage = AnalogIn( board.A5) # voltage divider with 2 equal resistors (220 Ohm) # Create library object using our Bus I2C port i2c_bus = busio.I2C(board.SCL, board.SDA) # Initialize peripherals sht = adafruit_sht31d.SHT31D(i2c_bus) # Configure averaging for sensor readings NUM_TEMP_SAMPLES = 5 TIME_BET_SAMPLES = 1 def get_voltage(pin): return (pin.value * 3.3) / 65536 * 2 #actaul Aref is more like 3.286 while True: # averaged temps sht_cumm_samples = 0 for i in range(NUM_TEMP_SAMPLES):
# SPDX-License-Identifier: MIT """This uses the Feather Sense as a Bluetooth LE sensor node.""" import time import adafruit_ble_broadcastnet import board import adafruit_lsm6ds # accelerometer import adafruit_sht31d # humidity sensor import adafruit_bmp280 # barometric sensor import adafruit_lis3mdl # magnetic sensor i2c = board.I2C() sense_accel = adafruit_lsm6ds.LSM6DS33(i2c) sense_humid = adafruit_sht31d.SHT31D(i2c) sense_barometric = adafruit_bmp280.Adafruit_BMP280_I2C(i2c) sense_magnet = adafruit_lis3mdl.LIS3MDL(i2c) print("This is BroadcastNet Feather Sense sensor:", adafruit_ble_broadcastnet.device_address) while True: measurement = adafruit_ble_broadcastnet.AdafruitSensorMeasurement() measurement.temperature = sense_barometric.temperature measurement.pressure = sense_barometric.pressure measurement.relative_humidity = sense_humid.relative_humidity measurement.acceleration = sense_accel.acceleration measurement.magnetic = sense_magnet.magnetic # print(measurement)
i2c = board.I2C() # Define sensors: # Accelerometer/gyroscope: lsm6ds = adafruit_lsm6ds.LSM6DS33(i2c) # Magnetometer: lis3mdl = adafruit_lis3mdl.LIS3MDL(i2c) # DGesture/proximity/color/light sensor: # TODO: How do we get the light level? # apds9960 = adafruit_apds9960.apds9960.APDS9960(i2c) # apds9960.enable_color = True # Humidity sensor: sht31d = adafruit_sht31d.SHT31D(i2c) # Barometric pressure sensor: bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c) while True: measurement = adafruit_ble_broadcastnet.AdafruitSensorMeasurement() measurement.temperature = (sht31d.temperature, bmp280.temperature) measurement.relative_humidity = sht31d.relative_humidity measurement.pressure = bmp280.pressure measurement.acceleration = lsm6ds.acceleration measurement.magnetic = lis3mdl.magnetic print(measurement) adafruit_ble_broadcastnet.broadcast(measurement) time.sleep(60)
def main(): # Soil moisture sensors moisture_sensors = { channel: MCP3008(channel=channel) for channel in MOISTURE_SENSOR_CHANNELS } # SHT31D Temperature and Humidity sensor i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) # Hue bridge = Bridge(BRIDGE_IP) bridge.connect() lights = bridge.get_light_objects('id') while True: state_dict = dict() message = "" for channel in moisture_sensors: value = moisture_sensors[channel].value soil_moisture = get_humidity_percentage(value) state_dict['moisture_{}'.format(channel)] = { 'voltage': moisture_sensors[channel].voltage, 'value': value, 'soil_moisture': soil_moisture } # record light status state_dict['light_{}'.format(channel)] = { 'on': lights[LIGHTS[channel]].on, 'hue': lights[LIGHTS[channel]].hue, 'saturation': lights[LIGHTS[channel]].saturation, 'brightness': lights[LIGHTS[channel]].brightness, } message += "|| Plant {}: {}%, Light {}: On: {} - {} H, {} S, {} B ".format( channel, soil_moisture, channel, state_dict['light_{}'.format(channel)]['on'], state_dict['light_{}'.format(channel)]['hue'], state_dict['light_{}'.format(channel)]['saturation'], state_dict['light_{}'.format(channel)]['brightness'], ) # Blue is hue 45808 sat 254 # normal hue 8402 sat 140 if lights[LIGHTS[channel]].on: if soil_moisture < DRY_CUTOFF: print("dry soil detected, turning light blue") lights[LIGHTS[channel]].hue = BLUE_HUE lights[LIGHTS[channel]].saturation = BLUE_SATURATION elif lights[LIGHTS[channel]].hue == BLUE_HUE: print("Wet soil but light blue, turning back to normal") # but what is normal? Check other light other_light = lights[LIGHTS[(1, 0)[channel]]] if other_light.hue == BLUE_HUE: # if blue, use preset lights[LIGHTS[channel]].hue = NORMAL_HUE lights[LIGHTS[channel]].saturation = NORMAL_SATURATION print("normal: {} Hue, {} Saturation".format( NORMAL_HUE, NORMAL_SATURATION)) else: lights[LIGHTS[channel]].hue = other_light.hue lights[LIGHTS[ channel]].saturation = other_light.saturation print("normal: {} Hue, {} Saturation".format( other_light.hue, other_light.saturation)) else: pass # print("Sensor {}: {}".format(channel, value)) # SHT31D reading SHT31D_temp = round((sensor.temperature * (9 / 5)) + 32, 1) SHT31D_relative_humidity = int(sensor.relative_humidity) SHT_message = '|| SHT31D Temperature: {} F Humidity: {}% '.format( round(SHT31D_temp + calibrations['SHT31D']['temperature'], 1), round( SHT31D_relative_humidity + calibrations['SHT31D']['humidity'], 1)) print(SHT_message + message + '||') time.sleep(1)
import adafruit_sht31d from datetime import datetime ADAFRUIT_IO_KEY = 'YOUR_ADAFRUIT_IO_KEY' # Set to your Adafruit IO username. ADAFRUIT_IO_USERNAME = '******' # Import Adafruit IO REST client. from Adafruit_IO import Client, Feed, RequestError # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Create library object using our Bus I2C port i2c = busio.I2C(board.SCL, board.SDA) sensor0 = adafruit_sht31d.SHT31D(i2c) sensor1 = adafruit_sht31d.SHT31D(i2c, address = 0x45) enclosurehumidityblack = aio.feeds('blackprinter.enclosurehumidityblack') enclosuretemperatureblack = aio.feeds('blackprinter.enclosuretemperatureblack') ambienthumidityblack = aio.feeds('blackprinter.ambienthumidityblack') ambienttemperatureblack = aio.feeds('blackprinter.ambienttemperatureblack') cputemperatureblack = aio.feeds('blackprinter.cputemperatureblack') # Return CPU temperature as a character string def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() return(res.replace("temp=","").replace("'C\n","")) #Do the actual work while True:
from adafruit_ble_adafruit.accelerometer_service import AccelerometerService from adafruit_ble_adafruit.addressable_pixel_service import AddressablePixelService from adafruit_ble_adafruit.barometric_pressure_service import BarometricPressureService from adafruit_ble_adafruit.button_service import ButtonService from adafruit_ble_adafruit.humidity_service import HumidityService from adafruit_ble_adafruit.light_sensor_service import LightSensorService from adafruit_ble_adafruit.microphone_service import MicrophoneService from adafruit_ble_adafruit.temperature_service import TemperatureService # Accelerometer lsm6ds33 = adafruit_lsm6ds.lsm6ds33.LSM6DS33(board.I2C()) # Used for pressure and temperature. bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(board.I2C()) # Humidity. sht31d = adafruit_sht31d.SHT31D(board.I2C()) # Used only for light sensor apds9960 = adafruit_apds9960.apds9960.APDS9960(board.I2C()) apds9960.enable_color = True mic = audiobusio.PDMIn( board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000, bit_depth=16, ) # Create and initialize the available services. accel_svc = AccelerometerService() accel_svc.measurement_period = 100
#FAN_PWM_LVL = 15 # software pwm duty cycle data_out_path = '/home/pi/Documents/AG_GC/MDP_DATA' # -- COM ADDR -- gc_sht31d_addr = 0x44 # I2C ext_sht31d_addr = 0x45 # I2C LCD_addr = 0x27 # I2C coil_ds18_addr = '28-000006b03811' # 1W # --SENSORS INIT-- # 1W - DS18B20, high temp os.system('modprobe w1-gpio') os.system('modprobe w1-therm') # I2C - SHT31-D, temp & humidity i2c = busio.I2C(board.SCL, board.SDA) gc_temp_humd_i2c = adafruit_sht31d.SHT31D(i2c, address=gc_sht31d_addr) ext_temp_humd_i2c = adafruit_sht31d.SHT31D(i2c, address=ext_sht31d_addr) def get_time(): return datetime.now().strftime("%H:%M:%S") def convert_tempf(temp_c: float): """ convert celcius to farh """ return round((temp_c * 1.8) + 32, 1) def LED_startup_display(LED_pin1: int, LED_pin2: int, LED_pin3: int):