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 __init__(self, i2c): self.i2c = i2c self.bmp = adafruit_bmp3xx.BMP3XX_I2C(self.i2c) self.bmp.filter_coefficient = 8 self.bmp.pressure_oversampling = 8 self.bmp.temperature_oversampling = 2 self.bmp.sealevel_pressure = 1013.25 self.base = 0
def __init__(self, channel, tca=None, precision=3): if tca: channel = tca[channel] device = adafruit_bmp3xx.BMP3XX_I2C(channel) device.pressure_oversampling = 8 device.temperature_oversampling = 2 self.device = device self.precision = precision # TODO: need to support multiple units self.accepted_units = ["f", "c", "hPa"]
def LogAltitude(rate, stop_event): try: # Set up altimeter info i2c = busio.I2C(board.SCL, board.SDA) bmp = adafruit_bmp3xx.BMP3XX_I2C(i2c) bmp.pressure_oversampling = 8 # Get the average pressure of 40 samples over roughly 2 seconds avg_pressure = 0 avg_sample_count = 0 for i in range(40): avg_pressure = (avg_pressure * avg_sample_count + bmp.pressure) / (avg_sample_count + 1) avg_sample_count += 1 time.sleep(1 / 20) # Set the baseline pressure to this average, effectively setting our current altitude to zero bmp.sea_level_pressure = avg_pressure # Get the current date and time to use for creating the log directory and file current_date = str(datetime.datetime.now()).split(' ') # Remove the decimals from the seconds in the current time current_date[1] = current_date[1].split('.')[0] # Replace the ':' with '-' in the current time current_date[1] = current_date[1].replace(':', '-') # Ensure the log directory exists log_dir = os.path.dirname(os.path.realpath(__file__)) log_dir = os.path.join(log_dir, '../logs/altitude/{}'.format(current_date[0])) if not os.path.exists(log_dir): os.makedirs(log_dir) # Create log file log_name = current_date[1] + '-altitude.log' log = open(os.path.join(log_dir, log_name), 'w') # Logging loop while not stop_event.is_set(): log.write('{} {}\n'.format(str(datetime.datetime.now().time()), str(bmp.altitude))) time.sleep(1 / rate) log.close() except: led = LED(26) led.blink(on_time=0.5, off_time=0.5) stop_event.wait()
def run_barometer(): i2c = busio.I2C(board.SCL, board.SDA) bmp = adafruit_bmp3xx.BMP3XX_I2C(i2c) bmp.pressure_oversampling = 8 bmp.temperature_oversampling = 2 return { "pressure": bmp.pressure, "temperature": bmp.temperature, "altitude": bmp.altitude, }
def detect_pressure_bmp3xx(self): try: import board import busio import adafruit_bmp3xx i2c = busio.I2C(board.SCL, board.SDA) #device test self.sensor_bmp3xx = adafruit_bmp3xx.BMP3XX_I2C(i2c, address=0x76) self.sensor_bmp3xx.filter_coefficient = 16 self.sensor_bmp3xx.pressure_oversampling = 16 self.sensor_bmp3xx.temperature_oversampling = 1 return True except: return False
def init_altimeter(configuration: Configuration): """Initialize the sensor for pressure, temperature, and altitude""" try: logging.info("Initializing altimeter") assignments = configuration.get_pin_assignments("bmp3xx") if not assignments: return None i2c = busio.I2C(assignments.get("scl"), assignments.get("sda")) bmp = adafruit_bmp3xx.BMP3XX_I2C(i2c) bmp._wait_time = 0 # pylint: disable=protected-access return bmp except Exception as ex: # pylint: disable=broad-except bmp = DummyBMP() logging.exception(ex) return bmp
def __init__(self, engine, config_dict): # Initialize my superclass first: super(Bmp3xx, self).__init__(engine, config_dict) self.bmp3xx_dict = config_dict.get('Bmp3xx', {}) loginf('bmp3xxwx configuration %s' % self.bmp3xx_dict) # TODO figure out how to sanely take these for the busio library # self.port = int(self.bmp3xx_dict.get('i2c_port', '1')) self.address = int(self.bmp3xx_dict.get('i2c_address', '0x77'), base=16) self.default_units = self.bmp3xx_dict.get('usUnits', 'US').upper() self.default_units = weewx.units.unit_constants[self.default_units] self.temperatureKeys = surely_a_list( self.bmp3xx_dict.get('temperatureKeys', 'inTemp')) self.temperature_must_have = surely_a_list( self.bmp3xx_dict.get('temperature_must_have', [])) # The conversion from station pressure to MSL barometric pressure depends on the # temperature. So, the default is to only provide the pressure value when there # is already an outdoor temperature value self.pressureKeys = surely_a_list( self.bmp3xx_dict.get('pressureKeys', 'pressure')) self.pressure_must_have = surely_a_list( self.bmp3xx_dict.get('pressure_must_have', ['outTemp'])) self.bus = busio.I2C(board.SCL, board.SDA) # this caches part-speciofic stuff so that a weewx restart is needed # if you change the bmp3xx sensor part; each one is unique # self.calibration_params = bmp3xx.load_calibration_params(self.bus, self.address) self.bmp = adafruit_bmp3xx.BMP3XX_I2C(self.bus, self.address) # TODO add oversampling support # # bmp.pressure_oversampling = 8 # bmp.temperature_oversampling = 2 # loginf('I2C port: %s' % self.port) loginf('I2C address: %s' % hex(self.address)) loginf('fallback default units: %s' % weewx.units.unit_nicknames[self.default_units]) # This is last to make sure all the other stuff is ready to go # (avoid race condition) self.bind(weewx.NEW_LOOP_PACKET, self.new_loop_packet)
def read(self, SIO): if not self.bmp3xx: i2c = busio.I2C(board.SCL, board.SDA, frequency=100000) # freq slower for pm25 self.bmp3xx = adafruit_bmp3xx.BMP3XX_I2C(i2c) self.bmp3xx.pressure_oversampling = 32 self.bmp3xx.temperature_oversampling = 2 try: self.T = self.bmp3xx.temperature self.P = self.bmp3xx.pressure except: traceback.print_exc() self.bmp3xx = None return self.t = time.time() print("BMP3xx", self.t, self.T, "C,\t", self.P, "mbar") SIO.log_readout(self.T_id, self.T, self.t) SIO.log_readout(self.P_id, self.P, self.t)
def __init__(self, _parent): self.Thread = None self.parent = _parent self.name = "MCPBMPCPU" self.format = { "Type": "SR", "Sensor": self.name, "Time": "", "Temp-precise": "", "Temperature-rough": "", "Pressure": "", "Temp-Cpu": "" } self.i2c_bus = busio.I2C(board.SCL, board.SDA) self.bmp = adafruit_bmp3xx.BMP3XX_I2C(self.i2c_bus) self.mcp = adafruit_mcp9808.MCP9808(self.i2c_bus) self.bmp.pressure_oversampling = 8 self.bmp.temperature_oversampling = 2 self.readfreq = 1 self.threadstart()
import time import board import busio import adafruit_bmp3xx # I2C setup i2c = busio.I2C(board.SCL, board.SDA) bmp = adafruit_bmp3xx.BMP3XX_I2C(i2c) bmp.pressure_oversampling = 8 bmp.temperature_oversampling = 2 while True: print("Pressure: {:6.1f} Temperature: {:5.2f}".format( bmp.pressure, bmp.temperature)) time.sleep(1)
import typer import adafruit_bmp3xx 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 press_sensor = adafruit_bmp3xx.BMP3XX_I2C(tca2[2]) press_sensor.pressure_oversampling = 8 press_sensor.temperature_oversampling = 2 def main(num: int = 100): for i in range(num): try: a_t = press_sensor.temperature * 1.8 + 32 except OSError: a_t = None try: a_pr = press_sensor.pressure except OSError: a_pr = None
def work_BMP3XX(name, data): def getPaths(value, value2, key, offset, raw): Erg = '' if value2: try: value3 = float(value2) Erg += '{"path": "' + key + '","value":' + str(offset + value3) + '},' except: Erg += '{"path": "' + key + '","value":"' + str(value2) + '"},' else: Erg += '{"path": "' + key + '","value": null},' if raw and value: try: value4 = float(value) Erg += '{"path": "' + key + '.raw","value":' + str( value4) + '},' except: Erg += '{"path": "' + key + '.raw","value":"' + str( value) + '"},' return Erg pressureKey = data['data'][0]['SKkey'] temperatureKey = data['data'][1]['SKkey'] if pressureKey or temperatureKey: import adafruit_bmp3xx address = data['address'] i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_bmp3xx.BMP3XX_I2C(i2c, address=int(address, 16)) pressure_oversampling = 8 if 'sensorSettings' in data: if 'pressure_oversampling' in data['sensorSettings']: try: pressure_oversampling = int( data['sensorSettings']['pressure_oversampling']) except: pass temperature_oversampling = 2 if 'sensorSettings' in data: if 'temperature_oversampling' in data['sensorSettings']: try: temperature_oversampling = int( data['sensorSettings']['temperature_oversampling']) except: pass sensor.pressure_oversampling = pressure_oversampling sensor.temperature_oversampling = temperature_oversampling if pressureKey: pressureRaw = data['data'][0]['raw'] pressureRate = data['data'][0]['rate'] pressureOffset = data['data'][0]['offset'] if temperatureKey: temperatureRaw = data['data'][1]['raw'] temperatureRate = data['data'][1]['rate'] temperatureOffset = data['data'][1]['offset'] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = data['port'] tick1 = time.time() tick2 = tick1 while True: time.sleep(0.1) try: Erg = '' if pressureKey: tick0 = time.time() if tick0 - tick1 > pressureRate: try: pressureValue = round(sensor.pressure, 2) except: pressureValue = sensor.pressure try: pressureValue2 = float(pressureValue) * 100 except: pressureValue2 = '' Erg += getPaths(pressureValue, pressureValue2, pressureKey, pressureOffset, pressureRaw) tick1 = time.time() if temperatureKey: tick0 = time.time() if tick0 - tick2 > temperatureRate: try: temperatureValue = round(sensor.temperature, 1) except: temperatureValue = sensor.temperature try: temperatureValue2 = float( temperatureValue) + 273.15 except: temperatureValue2 = '' Erg += getPaths(temperatureValue, temperatureValue2, temperatureKey, temperatureOffset, temperatureRaw) tick2 = time.time() if Erg: SignalK = '{"updates":[{"$source":"OpenPlotter.I2C.' + name + '","values":[' SignalK += Erg[0:-1] + ']}]}\n' sock.sendto(SignalK.encode('utf-8'), ('127.0.0.1', port)) except Exception as e: print("BMP3XX reading failed: " + str(e))
import paho.mqtt.client as mqtt MQTT_SERVER = "192.168.4.1" MQTT_PATH_COMMAND = "command_channel" MQTT_PATH_REPLY = "reply_channel" client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(MQTT_SERVER, 1883, 60) # initialize I2C bus and sensors i2c = busio.I2C(board.SCL, board.SDA) # create library on I2C port bmp388 = adafruit_bmp3xx.BMP3XX_I2C(i2c, address=0x76) bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c) sgp30 = adafruit_sgp30.Adafruit_SGP30(i2c) # set variables for each sensor value bmp_temp = bmp388.temperature bmp_press = bmp388.pressure bme_temp = bme280.temperature bme_hum = bme280.humidity bme_press = bme280.pressure bme_alt = bme280.altitude sgp_CO2 = sgp30.eCO2 sgp_TVOC = sgp30.TVOC # base case bmp388.pressure_oversampling = 8
def __init__(self, sensor_number: int = 0, sea_level_pressure: float = 1000.8, standard_units: bool = True): # get the configuration settings config_settings = get_settings(Configuration) calib_settings = get_settings(Calibration) # save the debug mode self.debug_mode: int = bool(int(config_settings['demomode']['value'])) # save the sensor type self.sensor_type: int = sensor_number # counter for fake breathing waveform data self.sample_counter: int = 0 # init the units type flag self.standard_units: bool = standard_units # get the calibration reading self.pressure_correction = float(calib_settings[f'sensor0']['value']) # list of previous pressure values # we fill the array with 0 for the number of samples per second up for a minute self.pressure_history: list = [0] * 4 * 60 # if we are not in debug mode setup the raspberry pi if not self.debug_mode: import board import busio import adafruit_bmp3xx # are we accessing the I2C bus if sensor_number == SensorHandler.SENSOR_1 or sensor_number == SensorHandler.SENSOR_2: # init the device address device_addr = 0 # i2c bus config i2c = busio.I2C(board.SCL, board.SDA) # type 0 is the i2c bus for sensor 0 if sensor_number == SensorHandler.SENSOR_1: device_addr = 0x76 elif sensor_number == SensorHandler.SENSOR_2: device_addr = 0x77 self.bmp = adafruit_bmp3xx.BMP3XX_I2C(i2c, device_addr) # else we are setting up SPI for sensor 1 else: #self.bmp = self.DebugBmp() import digitalio # spi bus config spi = busio.SPI(board.SCK, board.MOSI, board.MISO) cs = digitalio.DigitalInOut(board.D5) self.bmp = adafruit_bmp3xx.BMP3XX_SPI(spi, cs) else: # load up the demo bmp emulator self.bmp = self.DebugBmp() # set the sensor sampling rates and reference pressure self.bmp.pressure_oversampling = 8 self.bmp.temperature_oversampling = 2 self.bmp.sea_level_pressure = sea_level_pressure
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import time import board import busio import adafruit_bmp3xx #I2C setup i2c = busio.I2C(board.SCL, board.SDA) bmp = adafruit_bmp3xx.BMP3XX_I2C(i2c, 118) #also pass in i2c address # SPI setup #from digitalio import DigitalInOut, Direction #spi = busio.SPI(board.SCK, board.MOSI, board.MISO) #cs = DigitalInOut(board.D8) #bmp = adafruit_bmp3xx.BMP3XX_SPI(spi, cs) bmp.pressure_oversampling = 8 bmp.temperature_oversampling = 2 while True: print("Pressure: {:6.4f} Temperature: {:5.2f}".format( bmp.pressure, bmp.temperature)) time.sleep(1)