async def start(): while True: year, month, day, hour, minute, second, ms, dayinyear = localtime() now = "{:4}-{:02}-{:02}T{:02}:{:02}:{:02}.000000+{:02}:00".format( year, month, day, hour, minute, second, connection.config['tz']) bme = bme280.BME280(i2c=i2c) temp, pressure, humidity = bme.read_compensated_data() msg = { "id": "ESP32-bme280", "timestamp": now, "temp": temp, "pressure": pressure / 100, "humidity": humidity, } print(msg) await connection.publish('sensors/indoor', msg) await asyncio.sleep(60)
def main(): ssid = config.get_setting("ssid") password = config.get_setting("password") station = config.get_setting("station") # Turn AP off ap = network.WLAN(network.AP_IF) ap.active(False) connect_wlan(ssid, password) # set time to UTC time ntptime.settime() last_ntp_sync = utime.time() # Initialize I2C pins i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000) bme = bme280.BME280(i2c=i2c) while True: # dirty hack to make sure the local clock stays in sync with the ntp server pool.ntp.org. # Resync every 10min with the upstream ntp server in order to mitigate time shift. # Resetting the time is no problem, since time shift should never be larger than delay of sensor readings. if abs(utime.time() - last_ntp_sync) > 60 * 10: ntptime.settime() last_ntp_sync = utime.time() print("Local time has been synced with pool.ntp.org") transmit_data(read_sensor(bme, station)) time.sleep(60)
def read_and_send(): ## Reads sensor data i2c = machine.I2C(0) bme = bme280.BME280(i2c=i2c) temp, press, hum = bme.values ## Assign measured value to temp, press, hum temp = float(temp[:-1]) ## Convert temperature to floating number press = float(press[:-3]) ## Convert pressure to floating number hum = float(hum[:-1]) ## Convert humidity to floating number print("Temperature: %.2f C" % (temp)) ## Print temperatureto console print("Pressure: %.2f hPa" % (press)) ## Print pressure to console print("Humidity: %.2f %%\n" % (hum)) ## Print humidity to console location_code = 369 ## Arbitrary code value ## 'lifff' - long, int, float, float, float ## payload format: <location --- type of sensor --- values (temp, pressure, humidity)> data_payload = ustruct.pack('lifff', location_code, bme280.BME280_I2CADDR, temp, press, hum) UDP_IP = '192.168.0.105' UDP_PORT = 5005 ## Sends sensor data ## Set up UDP socket and connect sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) print("UDP target IP:", UDP_IP) print("UDP target port:", UDP_PORT) print("message:", data_payload) try: sock.sendto(data_payload, (UDP_IP, UDP_PORT)) except OSError: print("Error sending data. Going to deep sleep now...") machine.deepsleep(6000) gc.collect()
def start(): from ssd1306 import SSD1306_I2C import bme280 from machine import Pin, I2C i2c = I2C(-1, scl=Pin(SCL), sda=Pin(SDA)) ids = i2c.scan() print('found {} on i2c bus (scl={}, sda={})'.format(ids, SCL, SDA)) if not 0x76 in ids: print('could not find bme sensor on i2c bus (scl={}, sda={}) .. exit'. format(SCL, SDA)) return if not 0x3c in ids: print('no ssd1306 display found on i2c bus (scl={}, sda={})'.format( SCL, SDA)) oled = SSD1306_I2C(OLED_W, OLED_H, i2c) if 0x3c in ids else None modes = [ bme280.BME280_OSAMPLE_1, bme280.BME280_OSAMPLE_2, bme280.BME280_OSAMPLE_4, bme280.BME280_OSAMPLE_8, # default bme280.BME280_OSAMPLE_16 ] bme = bme280.BME280(mode=modes[3], i2c=i2c) run(oled, bme)
def __init__(self, mqttcli): self.mqttcli = mqttcli self.tmp102_failed = True self.bme_failed = True I2C_BUS = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4), freq=100000) #print(("I2C Devices Found: {}".format([hex(tmp) for tmp in I2C_BUS.scan()]))) if len(I2C_BUS.scan()) > 10: print("I2C Bus Error. Might be disconnected, please check cable") try: self.BME = bme280.BME280(i2c=I2C_BUS, address=bme280.BME280_I2CADDR + 1, mode=bme280.BME280_OSAMPLE_8) self.bme_failed = False except OSError: self.bme_failed = True try: self.TMP102 = Tmp102(I2C_BUS, 0x48, shutdown=True) self.tmp102_failed = False except OSError: self.tmp102_failed = True
def main(): i2c = I2C(scl=Pin(22), sda=Pin(21)) #ESP32 Dev Board /myown # CCS811 sensor s = CCS811.CCS811(i2c) bme = bme280.BME280(i2c=i2c,address=118) d = Assd1306.SSD1306_I2C(128,64,i2c,0x3c) time.sleep(1) while True: print("**************") print("BME280 values:") print("**************") #print(bme.values) temp,pa,hum = bme.values print('temp:',temp,' Hum:',hum ,'PA:', pa) d.fill(0) d.text("Temp. "+temp, 0, 0) d.text("Hum. "+hum, 0, 10) d.text("PA "+pa, 0, 20) d.show() if s.data_ready(): print(" ") print("**************") print("CSS811 values:") print("**************") print('eCO2: %d ppm, TVOC: %d ppb' % (s.eCO2, s.tVOC)) print(" ") #d.fill(0) d.text('eCO2 ppm',0,30) d.text(str(s.eCO2),70,30) d.text('TVOC ppb',0,40) d.text(str(s.tVOC),70,40) d.show() time.sleep(3)
def serve(): bme = bme280.BME280(i2c=i2c) client_id = CONFIG['MQTT_CLIENT_ID_PREFIX'] + ubinascii.hexlify( machine.unique_id()).decode('utf-8') password = ubinascii.a2b_base64(CONFIG['MQTT_PASSWORD']) client = MQTTClient(client_id, CONFIG['MQTT_BROKER'], user=CONFIG['MQTT_USER'], password=password, port=CONFIG['MQTT_PORT']) client.connect() print("'%s' is connected to '%s'" % (client_id, CONFIG['MQTT_BROKER'])) while True: temp = bme.temperature hum = bme.humidity pres = bme.pressure # uncomment for temperature in Fahrenheit #temp = (bme.read_temperature()/100) * (9/5) + 32 #temp = str(round(temp, 2)) + 'F' # publish the values client.publish("%s.temperature_c" % client_id, temp) client.publish("%s.humidity_rh" % client_id, hum) client.publish("%s.pressure_hpa" % client_id, pres) sleep(300)
def serve(): bme = bme280.BME280(i2c=i2c) # create the onewire object ds = ds18x20.DS18X20(onewire.OneWire(Pin(2))) # the ds18b20 is on GPIO4 # mqtt client client_id = CONFIG['MQTT_CLIENT_ID_PREFIX'] + ubinascii.hexlify( machine.unique_id()).decode('utf-8') password = ubinascii.a2b_base64(CONFIG['MQTT_PASSWORD']) client = MQTTClient(client_id, CONFIG['MQTT_BROKER'], user=CONFIG['MQTT_USER'], password=password, port=CONFIG['MQTT_PORT']) client.connect() print("'%s' is connected to '%s'" % (client_id, CONFIG['MQTT_BROKER'])) while True: temp = bme.temperature hum = bme.humidity pres = bme.pressure temps = ds18b20.read_temperatures(ds) # publish the values client.publish("%s.temp_c" % client_id, temp) client.publish("%s.humidity_rh" % client_id, hum) client.publish("%s.pressure_hpa" % client_id, pres) for serial_nbr, temp in temps.items(): client.publish("%s.%s.temp_c" % (client_id, serial_nbr), '%0.5f' % temp) sleep(300)
def __init__(self, sda="P3", scl="P4", als="P20", ssid="", pw="", frequency=5, debug=0, feed_layer=None): self.feed_layer = feed_layer self.fid = self.feed_layer.get_sensor_feed_fid() self.cfid = self.feed_layer.get_control_feed_fid() self.rtc = RTC() self.debug = debug self.lastsent = 0 self.switch = True self.wlan = WLAN(mode=WLAN.STA) self.connectWlan(ssid=ssid, pw=pw) self.subscribe_state = self.feed_layer.subscribe_control_feed( self.callback) self.frequency = frequency self.__debug("Sensor Feed ID is: " + str(self.fid)) self.__debug("Control Feed ID is: " + str(self.cfid)) try: self.bme280 = bme280.BME280(i2c=I2C(pins=(sda, scl))) except: self.__exitError( "BME280 not recognized. Please check the connections.", loop=True, col=1) self.l_pin = ADC().channel(pin=als)
def BMEConnect(): global BME try: i2c = machine.I2C(scl=machine.Pin(4), sda=machine.Pin(2)) BME = bme280.BME280(i2c=i2c) except: ProblemWithBME()
def temperature_and_humidity(self): try: weather = bme280.BME280(i2c=self.i2c) data = weather.values return data[0], data[2] except: print("The temperature and humidity sensor is not connected") return False, False
def cycle() -> None: """Measurement cycle.""" # Init I2C. i2c = machine.I2C(scl=machine.Pin(config.SCL_PIN), sda=machine.Pin(config.SDA_PIN)) # Init BME280 sensor connected to I2C. bme = bme280.BME280(address=config.BME280_I2C_ADDR, i2c=i2c) # Read measurements. t, p, h = bme.read_compensated_data() t, p, h = t / 100, p / 256, h / 1024 print(t, p, h) error = False # Sync RTC. try: ntptime.settime() except Exception as err: error = True log_error('syncing clock', err) url = config.URL_TEMPLATE.format(t=t, p=p, h=h) try: urlopen(url) except Exception as err: error = True log_error('sending metrics', err) # Init display. display = ssd1306.SSD1306_I2C(DISPLAY_WIDTH, DISPLAY_HEIGHT, i2c, addr=config.DISPLAY_I2C_ADDR) display.fill(0) # Calculate current time. hours = utime.localtime()[3] + config.UTC_OFFSET if hours >= 24: hours -= 24 minutes = utime.localtime()[4] display.text('{:02d}:{:02d}'.format(hours, minutes), DISPLAY_WIDTH - 40, 2) if error: display.text('Error', 0, 0) # Show measurements. display.text('T: {:.2f}C'.format(t), 0, 16) display.text('P: {:.2f}hPa'.format(p / 100), 0, 26) display.text('H: {:.2f}%'.format(h), 0, 36) display.show() utime.sleep(5) display.poweroff()
def testeBME280(): i2c = I2C(0,I2C.MASTER) i2c.scan() sensor = bme280.BME280(i2c=i2c) while True: print('temperatura:',sensor.temperature,'ºC') print('humidade:',sensor.humidity,'%') print('pressão:',sensor.pressure/100,'hPa') time.sleep(5)
def measure_temp_pressure(): i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4)) bme = bme280.BME280(i2c=i2c) response = bme.read_compensated_data() temp_100ths = response[0] pressure_32bit = response[1] temperature = temp_100ths / 100.0 pressure = pressure_32bit / 256.0 / 100.0 return temperature, pressure
def set_up_sensor(self): """ Set up the BME280 sensor. It's necessary to scan for the IC2 address and give it to the constructor of the BME280 (see driver file bme280.py). """ i2c = machine.I2C(scl=self.SCL, sda=self.SDA) address = i2c.scan() self.BME = bme280.BME280(i2c=i2c, address=address[0]) print("Sensor is set up.")
def connect(i2c): import bme280 modes = [ bme280.BME280_OSAMPLE_1, bme280.BME280_OSAMPLE_2, bme280.BME280_OSAMPLE_4, bme280.BME280_OSAMPLE_8, # default bme280.BME280_OSAMPLE_16 ] return bme280.BME280(mode=modes[4], i2c=i2c)
def __init__(self, i2c, addr, num): import bme280 self.driver = bme280.BME280(address=addr, i2c=i2c) if self.driver.humidity_capable: super().__init__([ self.get_temp_prop(), self.get_press_prop(), self.get_humid_prop() ], num) else: super().__init__([self.get_temp_prop(), self.get_press_prop()], num)
def run(): """Main entry point to execute this program.""" try: bme = bme280.BME280(i2c=_i2c, mode=bme280.BME280_OSAMPLE_4) scr = screen.Screen(config) if _delete_ccs811_baseline_requested(): _baseline.delete() if _is_first_run(): # 20 runs (minutes), p9 of datasheet _set_runs_to_condition(20) ccs = ccs811.CCS811(_i2c, mode=ccs811.CCS811.DRIVE_MODE_60SEC) t, p, h = bme.read_data() # Full update of Waveshare on power on scr.update(t, h, None, None, _bat.volts(), False, True) else: ccs = ccs811.CCS811(_i2c, mode=None) _add_run() ccs.read() t, p, h = bme.read_data() ccs.put_envdata(t, h) if _ccs811_is_conditioned(): # Stored baseline should only be loaded after conditioning if not _ccs811_baseline_is_loaded() and _baseline.exists(): baseline = _baseline.retrieve() ccs.put_baseline(baseline) _set_ccs811_baseline_loaded() scr.update(t, h, None, None, _bat.volts()) print('ccs811 baseline %d loaded' % baseline) else: scr.update(t, h, ccs.eco2, ccs.tvoc, _bat.volts(), _ccs811_baseline_is_loaded()) if _new_ccs811_baseline_requested(): baseline = ccs.get_baseline() _baseline.store(baseline) print('ccs811 baseline %d stored' % baseline) else: scr.update(t, h, None, None, _bat.volts()) print('eCO2: %dppm, TVOC: %dppb, %.1fC, %.1f%%RH, baseline: %r' % (ccs.eco2, ccs.tvoc, t, h, _ccs811_baseline_is_loaded())) scr.sleep() _flash_led() except Exception as e: _flash_led(3) print(e) esp32.wake_on_ext0(pin=config.int, level=0) machine.deepsleep()
def doBME(i2c, bmeaddr, bmePwr, dbconfig, tagname='sensor'): """ """ print("Turning BME on ...") bmePwr.on() time.sleep(1) try: sensor = bme.BME280(i2c=i2c, address=bmeaddr) except Exception as e: print(str(e)) sensor = None if sensor is not None: # Toss the first read just in case it's junk/not settled _ = getBMEval(sensor) time.sleep(1) # Do 5 reads, which are then averaged and returned temp, apre, humi = BMEmultivals(sensor, ntries=2, nreads=5) sV = utils.postToInfluxDB(dbconfig, temp, keyname="temperature", tagN=tagname, tagV="bme280") time.sleep(0.25) print() sV = utils.postToInfluxDB(dbconfig, apre, keyname="apparentpressure", tagN=tagname, tagV="bme280") time.sleep(0.25) print() sV = utils.postToInfluxDB(dbconfig, humi, keyname="relativehumidity", tagN=tagname, tagV="bme280") print(temp, apre, humi) else: print("No BME sensor found or error establishing it!") print("Aborting...") print("Turning BME off ...") bmePwr.off() print()
def __init__(self, sda="P3", scl="P4", als="P20", frequency=1, mode=0, debug=0): if not (mode == 0 or mode == 1): self.__exitError("Please initialize this module in either mode 0 or mode 1.") self.mode = mode self.rtc = RTC() self.debug = debug self.wlan = WLAN(mode=WLAN.STA) self.UDPactive = False self.loraActive = False if (mode == 0): adc = ADC() self.bme280 = bme280.BME280(i2c=I2C(pins=(sda, scl))) self.l_pin = adc.channel(pin=als) self.frequency = frequency
def setup_sensors(i2c): while True: try: bme = bme280.BME280(i2c=i2c) light_sensor = max44009.MAX44009(i2c) break except Exception as e: print("One sensor couldn't be initialized: {}".format(e)) time.sleep(3) continue print("Sensors ready") return bme, light_sensor
def __init__(self, i2c): self.sensor = bme280.BME280(i2c=i2c) self.sensor.set_measurement_settings({ 'filter': bme280.BME280_FILTER_COEFF_16, 'standby_time': bme280.BME280_STANDBY_TIME_500_US, 'osr_h': bme280.BME280_OVERSAMPLING_1X, 'osr_p': bme280.BME280_OVERSAMPLING_16X, 'osr_t': bme280.BME280_OVERSAMPLING_2X }) self.sensor.set_power_mode(bme280.BME280_NORMAL_MODE)
def __init__(self, io_id, io_user, io_key, frequency, port=1883): # Turn sensors on/off self.sensor_on = False # Save variables passed for use in other methods self.io_id = io_id self.io_user = io_user self.io_key = io_key self.update_frequency = frequency self.port = port # Now, setup the sensor i2c = I2C(0, I2C.MASTER, baudrate=100000) self.sensor = bme280.BME280(i2c=i2c) utime.sleep_ms(100) print("Weather MQTT client is ready.")
def run(): wifi = None mqtt = None i2c = machine.I2C(scl=machine.Pin(config.I2C_SCL_PIN), sda=machine.Pin(config.I2C_SDA_PIN)) adr = i2c.scan()[0] bme = bme280.BME280(i2c=i2c, address=adr) while True: try: # connect wifi if wifi is None: wifi = core.WifiWrapper(config) if not wifi.isconnected: wifi.connect() # connect mqtt if mqtt is None: mqtt = core.MQTTClientWrapper(config) mqtt.connect() # get values from sensor vals = bme.values temp = vals[0][:-1] pressure = vals[1][:-3] humidity = vals[2][:-1] # publish temperature utime.sleep_ms(500) payload = {'name': 'temperature', 'value': temp, 'unit': 'C'} mqtt.publish(config.MQTT_TOPIC + '/temp', ujson.dumps(payload)) # publish pressure utime.sleep_ms(500) payload = {'name': 'pressure', 'value': pressure, 'unit': 'bar'} mqtt.publish(config.MQTT_TOPIC + '/pressure', ujson.dumps(payload)) # publish humidity utime.sleep_ms(500) payload = {'name': 'humidity', 'value': humidity, 'unit': 'pct'} mqtt.publish(config.MQTT_TOPIC + '/humidity', ujson.dumps(payload)) mqtt.disconnect() core.sleep(config) except Exception as e: print(e)
def debug(): # ds18b20 sensor sensors = dict() if ds18b20.get_sensor_ids() > 0: sensors['ds18b20'] = ds18b20.get_readings() #bmp sensor bmp180 = dict() try: bmp180['temperature'] = sensor.get_temperature("C") bmp180['temperatureF'] = (sensor.get_temperature("F")) bmp180['pressure'] = sensor.get_pressure() bmp180['altitude'] = sensor.get_altitude() except: print "" sensors['bmp180'] = bmp180 sensors.update(bme280.BME280().get()) return json.dumps(sensors, ensure_ascii=False)
def read_humidity_i2c(i2c): """The BME280 temp/humidity sensor is usually on 0x76""" bme = bme280.BME280(i2c=i2c) print(bme.values) (temp, pressure, humidity) = bme.read_compensated_data() return [{ "id": "bme280_0x76_temp", "value": temp / 100.0, "type": "temperature" }, { "id": "bme280_0x76_pressure", "type": "pressure", "value": pressure / 256.0 }, { "id": "bme280_0x76_humidity", "value": humidity / 1024.0, "type": "humidity" }]
def measure_temp_pressure(): i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4)) bme = bme280.BME280(i2c=i2c) def do(): response = bme.read_compensated_data() temp_100ths = response[0] pressure_32bit = response[1] temperature = temp_100ths / 100.0 pressure = pressure_32bit / 256.0 / 100.0 return temperature, pressure temperature, pressure = do() if pressure < 900: #Do it again as the first reading always seems to be a bit dodge time.sleep(1) temperature, pressure = do() return temperature, pressure
def main(): while True: try: i2c = machine.I2C(scl=machine.Pin(0), sda=machine.Pin(2)) bme = bme280.BME280(i2c=i2c, address=119) c.connect() c.publish(b"heartbeat", CLIENT_ID) c.publish(CLIENT_ID + "/temperature", bme.values[0]) c.publish(CLIENT_ID + "/pressure", bme.values[1]) c.publish(CLIENT_ID + "/humidity", bme.values[2]) print("published msg") except Exception as e: print(str(e)) machine.reset() finally: c.disconnect() time.sleep(5)
def main(): # Common I2C bus i2c = I2C(scl=Pin(15), sda=Pin(4)) # BME variables bme = bme280.BME280(i2c=i2c) # Display variables oled = ssd1306.SSD1306_I2C(128, 64, i2c) # Initialise the display pin16 = Pin(16, Pin.OUT) pin16.value(1) while True: oled.fill(0) oled.text('Temp: ' + bme.temperature, 0, 0) oled.text('Pres: ' + bme.pressure, 0, 10) oled.text('Hum: ' + bme.humidity, 0, 20) oled.show() utime.sleep(5)
def main(): logging.basicConfig(level=logging.INFO) ls = light_sensor.LightSensor(LIGHT_SENSOR_I2C_BUS, LIGHT_SENSOR_I2C_ADDRESS) di = display.Display(DISPLAY_PIN_RESET, DISPLAY_PIN_DC, DISPLAY_SPI_PORT, DISPLAY_SPI_DEVICE) tph = bme280.BME280(BME280_I2C_BUS, BME280_I2C_ADDRESS) led0 = led.LED(LED_PIN_RED, LED_PIN_GREEN, LED_PIN_BLUE) while True: ls.start() time.sleep(0.5) visible, infrared = ls.read() temp, _, pressure, humidity = tph.read() di.update(visible, infrared, temp, pressure, humidity) #blue_value = (65535 - visible) / 65535.0 * 100 #logger.info(blue_value) #led0.set_blue(blue_value) led0.set_blue(100) time.sleep(0.01) led0.set_blue(0)