import jwt import requests #Cloud Iot CoreのAPI URL _BASE_URL = 'https://cloudiotdevice.googleapis.com/v1' #i2cのバスナンバー _BUS_NUMBER = 1 #i2cのアドレス _I2C_ADDRESS = 0x76 #バス _BUS = smbus2.SMBus(_BUS_NUMBER) #取得用の初期化パラメータ _CALIBRATION_PARAMS = bme280.load_calibration_params(_BUS, _I2C_ADDRESS) def readData(): data = bme280.sample(_BUS, _I2C_ADDRESS, _CALIBRATION_PARAMS) datas = {'temperature':data.temperature , 'pressure':data.pressure, 'humidity':data.humidity} return datas def create_message(id, longitude, latitude): datas = readData() #送信するメッセージをJSON形式にする
def upload_data(): #Restart timer t = Timer(300.0, upload_data) #5 minutes t.start() GPIO.output(Camera, GPIO.HIGH) #Turn camera on time.sleep(2) global dataPoints, deviceId, deviceType channels = 0 ts = time.time() fileName = str(ts) + ".csv" cameraFile = str(ts) + ".jpg" camera.resolution = (640, 480) time.sleep(2) camera.capture(cameraFile) call(["./raspberrypi_capture", fileName]) time.sleep(10) GPIO.output(Camera, GPIO.LOW) #Turn camera off #Upload to blob storage resp = block_blob_service = BlockBlobService( account_name='abudhabi', account_key= 'gOeU6pteZC/U3LnpWUmNShUJBFpttWUm7o/H9ky7pcWNQJr0/2K5q7hQMq2SRvCY2fdDALpNNuf61cermNGdrw==' ) print(resp) resp = block_blob_service.create_container( deviceId, public_access=PublicAccess.Container) print(resp) resp = block_blob_service.create_blob_from_path( deviceId, str(fileName), str(fileName), content_settings=ContentSettings(content_type="text/csv")) print(resp) resp = block_blob_service.create_blob_from_path( deviceId, str(cameraFile), str(cameraFile), content_settings=ContentSettings(content_type="image/jpg")) print(resp) try: calibration_params = bme280.load_calibration_params(bus, address) data = bme280.sample(bus, address, calibration_params) #Message start details for jsonString SGP, GBR msg_txt = "{\"deviceID\":\"" + deviceId + "\",\"tags\":\"Thermal Camera\",\"location\":\"" + gps + "\",\"locationName\":\"" + location + "\",\"" + deviceType + "\":\"Weather Station\",\"countryCode\":\"GBR\",\"dataReadings\":[" msg_txt_sensor = "{\"idRange\":\"4501\",\"channel\":\"0\",\"value\":" + str( ts) + ",\"tags\":\"Thermal Camera\",\"type\":\"Camera\"}," msg_txt_sensor += "{\"idRange\":\"0301\",\"channel\":\"0\",\"value\":" + str( data.pressure ) + ",\"tags\":\"Thermal Sensor\",\"type\":\"Camera\"}," msg_txt_sensor += "{\"idRange\":\"1701\",\"channel\":\"0\",\"value\":" + str( data.humidity ) + ",\"tags\":\"Thermal Sensor\",\"type\":\"Camera\"}," msg_txt_sensor += "{\"idRange\":\"0501\",\"channel\":\"0\",\"value\":" + str( data.temperature ) + ",\"tags\":\"Thermal Sensor\",\"type\":\"Camera\"}" msg_txt_end = "]}" except: #Message start details for jsonString SGP, GBR msg_txt = "{\"deviceID\":\"" + deviceId + "\",\"tags\":\"Thermal Camera\",\"location\":\"" + gps + "\",\"locationName\":\"" + location + "\",\"" + deviceType + "\":\"Weather Station\",\"countryCode\":\"GBR\",\"dataReadings\":[" msg_txt_sensor = "{\"idRange\":\"4501\",\"channel\":\"0\",\"value\":" + str( ts) + ",\"tags\":\"Thermal Camera\",\"type\":\"Camera\"}" msg_txt_end = "]}" #Add end bit of json message msg_txt = msg_txt + msg_txt_sensor + msg_txt_end #Display message and publish print(msg_txt) publish(msg_txt) #reset datapoints dataPoints = 0 #Delete Files time.sleep(60) os.remove(str(fileName)) os.remove(str(cameraFile)) os.remove("IMG_0000.pgm")
import smbus2, bme280, os, asyncio, json from dotenv import load_dotenv from grove.grove_moisture_sensor import GroveMoistureSensor from grove.grove_led import GroveLed from azure.iot.device.aio import IoTHubDeviceClient, ProvisioningDeviceClient from azure.iot.device import MethodResponse # Configuration parameters bme_pin = 1 bme_address = 0x76 moisture_pin = 2 led_pin = 16 # Create the sensors bus = smbus2.SMBus(bme_pin) calibration_params = bme280.load_calibration_params(bus, bme_address) moisture_sensor = GroveMoistureSensor(moisture_pin) # Create the LED led = GroveLed(led_pin) # Load the IoT Central connection parameters load_dotenv() id_scope = os.getenv('ID_SCOPE') device_id = os.getenv('DEVICE_ID') primary_key = os.getenv('PRIMARY_KEY') def getTemperaturePressureHumidity(): return bme280.sample(bus, bme_address, calibration_params)
import time import smbus2 import bme280 import RPi_I2C_driver bus = smbus2.SMBus(1) addr = 0x76 params = bme280.load_calibration_params(bus, addr) mylcd = RPi_I2C_driver.lcd() while True: try: data = bme280.sample(bus, addr, params) mylcd.lcd_display_string(f'P={data.pressure:0.2f}', 1) mylcd.lcd_display_string( f'U={data.humidity:0.2f}' f' T={data.temperature:0.2f}', 2) time.sleep(1) except KeyboardInterrupt: break finally: mylcd.lcd_clear() mylcd.backlight(0)
def __init__(self): self._bus = SMBus(1) self._address = 0x76 self._calibration_params = bme280.load_calibration_params( self._bus, self._address)
def __init__(self, port=1, address=0x77): self.port = port self.address = address self.bus = smbus2.SMBus(self.port) bme280.load_calibration_params(self.bus, self.address)
import smbus2 import bme280 from lcd_16x2_i2c import RPi_I2C_driver import time import sys porta_i2c = 1 endereco = 0x76 bus = smbus2.SMBus(porta_i2c) calibracao_paramentros = bme280.load_calibration_params(bus, endereco) lcd = RPi_I2C_driver.lcd() while True: try: dado = bme280.sample(bus, endereco, calibracao_paramentros) l1 = f"T:{str(round(dado.temperature, 2))} U:{str(round(dado.humidity, 2))}" l2 = f"P:{str(round(dado.pressure, 2))}" print(l1) print(l2) lcd.lcd_display_string(f"{l1}", 1) lcd.lcd_display_string(f"{l2}", 2) time.sleep(1) except KeyboardInterrupt: print("\nKilling program") sys.exit(0)
def get_bme280_data(**kwargs): from time import sleep verbose = True read_interval = kwargs['read_interval'] interface_type = kwargs['interface'] sid = kwargs['id'] if interface_type == 'i2c': try: import smbus2 import bme280 port = 1 address = kwargs['i2c_address'] bus = smbus2.SMBus(port) while True: calibration_params = bme280.load_calibration_params( bus, address) data = bme280.sample(bus, address, calibration_params) temperature = round(data.temperature, 3) humidity = round(data.humidity, 3) pressure = round(data.pressure, 3) redis_db.mset({ f'{sid}_BME280_Temperature': temperature, f'{sid}_BME280_Humidity': humidity, f'{sid}_BME280_Pressure': pressure }) redis_db.expire(f'{sid}_BME280_Temperature', read_interval * 2) redis_db.expire(f'{sid}_BME280_Humidity', read_interval * 2) redis_db.expire(f'{sid}_BME280_Pressure', read_interval * 2) if bool(verbose) is True: print('') print( f'{sid}_BME280: Temperature: {temperature} °C, Humidity: {humidity} %, Pressure: {pressure} hPa' ) sleep(read_interval) except Exception as err: print(f'Problem with sensor BME280: {err}') if interface_type == 'serial': serial_port = kwargs['serial_port'] lecounter = 0 necounter = 0 def serial_data(port, baudrate, timeout): import serial ser = serial.Serial(port, baudrate, timeout) while True: yield ser.readline() for line in serial_data(serial_port, 115200, 5): msg = line.decode('utf-8').split() if len(msg) < 3: lecounter += lecounter redis_db.mset('LECOUNTER', lecounter) continue if msg[0].isnumeric() and msg[1].isnumeric() and msg[2].isnumeric( ): temperature = int(msg[0]) / 1000 humidity = int(msg[1]) / 1000 pressure = int(msg[2]) / 1000 redis_db.mset({ f'{sid}_BME280_Temperature': temperature, f'{sid}_BME280_Humidity': humidity, f'{sid}_BME280_Pressure': pressure }) redis_db.expire(f'{sid}_BME280_Temperature', read_interval * 2) redis_db.expire(f'{sid}_BME280_Humidity', read_interval * 2) redis_db.expire(f'{sid}_BME280_Pressure', read_interval * 2) if bool(verbose) is True: print('') print( f'{sid}_BME280: Temperature: {temperature} °C, Humidity: {humidity} %, Pressure: {pressure} hPa' ) else: necounter += necounter redis_db.mset('NECOUNTER', necounter) sleep(read_interval)
from time import sleep # things network keys. paste keys between quotes appeui = methods_.stringToBytes('') deveui = methods_.stringToBytes('') appkey = methods_.stringToBytes('') debug = 48 # set to 49 to enable debugging on CR02 # reset CR02 methods_.cr02_reset() # sw01 i2c address sw01_addr = 0x76 calibration_params = bme280.load_calibration_params(methods_.bus, sw01_addr) methods_.cr02_init(appeui, deveui, appkey, debug) methods_.oc03_init() # open the relay initially methods_.oc03_write(0) while True: SW01 = bme280.sample(methods_.bus, sw01_addr, calibration_params) temperature = round(SW01.temperature, 2) humidity = round(SW01.humidity, 2) pressure = int(round(SW01.pressure, 0)) print("T:", temperature) print("H:", humidity)
def init_sensors(): global i2c_bus global tsl global accel global ina try: # Init the i2c bus i2c_bus = smbus2.SMBus(config['sensors']['i2c_port']) if config['sensors']['bme280_enable']: bme280_data['enabled'] = True # Load some data into the BME280 logger.info('Starting BME280 sensor') bme280.load_calibration_params(i2c_bus, config['sensors']['bme280_address']) # Populate some data get_bme280_data() else: bme280_data['enabled'] = False if config['sensors']['tsl2561_enable']: tsl2561_data['enabled'] = True # Start the TSL2561 sensor logger.info('Starting TSL2561 ambient light sensor') tsl = TSL2561( gain=config['sensors']['tsl2561_gain'], integration_time=config['sensors']['tsl2561_integration_time']) tsl2561_data['door_open'] = False tsl2561_data['door_open_count'] = 0 tsl2561_data['last_door_open_count'] = 0 tsl2561_data['last_door_open'] = 0 tsl2561_data['last_door_open_timestamp'] = 0 tsl2561_data['door_open_warn'] = False # Populate some data get_tsl2561_data() else: tsl2561_data['enabled'] = False if config['sensors']['lis3dh_enable']: lis3dh_data['enabled'] = True # Start the accelerometer and set up the interrupt logger.info('Starting LIS3DH accelerometer') accel = LIS3DH.Accelerometer( 'i2c', i2cAddress=config['sensors']['lis3dh_address']) accel.set_ODR(odr=10, powerMode='normal') accel.axis_enable(x='on', y='on', z='on') accel.set_highpass_filter('autoreset', 0x01, 0x00, 0x00, 0x00, 0x01) accel.interrupt_high_low('low') accel.latch_interrupt('on') accel.set_BDU('on') accel.set_scale() if config['sensors']['lis3dh_interrupt_pin']: # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Set up port as an input with pullup enabled GPIO.setup(config['sensors']['lis3dh_interrupt_pin'], GPIO.IN, pull_up_down=GPIO.PUD_UP) # Add a detection event and callback for falling edge on int pin GPIO.add_event_detect( config['sensors']['lis3dh_interrupt_pin'], GPIO.FALLING, callback=accel_isr) # Accelerometer interrupt setup # turn on AOI1 interrupt accel.set_int1_pin(click=0, aoi1=1, aoi2=0, drdy1=0, drdy2=0, wtm=0, overrun=0) # set INT1_THS to 256mg accel.set_int1_threshold(256) # set INT1_DURATION to 100ms accel.set_int1_duration(0) # on INT1_CFG enable 6D positioning, X, Y & Z (H & L) accel.set_int1_config(aoi=0, d6=1, zh=1, zl=1, yh=1, yl=1, xh=1, xl=1) # Get some data lis3dh_data['interrupt_state'] = False lis3dh_data['interrupt_count'] = 0 lis3dh_data['last_interrupt_count'] = 0 lis3dh_data['last_interrupt'] = 0 lis3dh_data['last_interrupt_timestamp'] = 0 lis3dh_data['motion_warn'] = False else: info.warn( 'No interrput pin specified for accelerometer! Sensor will be polled but may miss events!' ) get_lis3dh_data() else: lis3dh_data['enabled'] = False if config['sensors']['ina260_enable']: ina260_data['enabled'] = True # Load some data into the BME280 logger.info('Starting INA260 sensor') ina = Controller(address=config['sensors']['ina260_address'], channel=config['sensors']['i2c_port']) # Populate some data get_ina260_data() else: ina260_data['enabled'] = False if config['sensors']['gps_enable']: gps_data['enabled'] = True gps_data['mode'] = 0 gps_data['mode_text'] = gps_mode_text[gps_data['mode']] # Connect to the GPSd daemon logger.info('Connecting to GPSd') gpsd.connect() # Get gpsd mode first packet = gpsd.get_current() gps_data['mode'] = packet.mode gps_data['mode_text'] = gps_mode_text[gps_data['mode']] # Then populate the rest of the data get_gps_data() else: gps_data['enabled'] = False except Exception as e: logger.error("Failed to set up sensors: " + str(e))
def temp_collect(): bus = smbus2.SMBus(1) cal_p = bme280.load_calibration_params(bus, 0x76) data = bme280.sample(bus, 0x76, cal_p) return data.temperature
def calibration_params(self) -> bme280.params: if not hasattr(self, "_calibration_params"): self._calibration_params = bme280.load_calibration_params( BUS, self.address) return self._calibration_params
def _getSensorData(self): bme280.load_calibration_params(self.bus, self.address) return bme280.sample(self.bus, self.address)
def main(): try: # DB connection params dbParams = {"db": "sensori", "precision": "ms"} # Initialization bus = smbus2.SMBus(SENSOR_PORT) bme280.load_calibration_params(bus, SENSOR_ADDRESS) payload = "" counter = 1 problem_counter = 0 GPIO.setmode(GPIO.BOARD) # Set GPIO mode to BOARD PIN_IMP = 7 # Pin 7 is connected to relay GPIO.setup(PIN_IMP, GPIO.OUT) # Sets relay as output # Infinite loop while True: unix_time_ms = int(time.time() * 1000) # Read sensor data and convert it to line protocol data = bme280.sample(bus, SENSOR_ADDRESS) line = "sensors_data temperature={},pressure={},humidity={} {}\n".format( data.temperature, data.pressure, data.humidity, unix_time_ms) payload += line # Verbose print("Temperature: ", data.temperature) print("Pressure: ", data.pressure) print("Humidity: ", data.humidity) if data.temperature > 25: GPIO.output(PIN_IMP, GPIO.HIGH) # Relay on elif data.temperature < 10: # Temp too low triggers relay to avoid liquid forming on the RPi GPIO.output(PIN_IMP, GPIO.HIGH) # Relay on else: GPIO.output(PIN_IMP, GPIO.LOW) # Realay off if counter % SENDING_PERIOD == 0: try: # Try to send data r = requests.post(URL, params=dbParams, data=payload) if r.status_code != 204: raise Exception("data not written") payload = "" except: problem_counter += 1 print('cannot write to InfluxDB') if problem_counter == MAX_LINES_HISTORY: problem_counter = 0 payload = "" counter += 1 # Wait for selected time time_diff_ms = int(time.time() * 1000) - unix_time_ms if time_diff_ms < READING_DATA_PERIOD_MS: time.sleep((READING_DATA_PERIOD_MS - time_diff_ms) / 1000.0) finally: GPIO.cleanup() # Frees GPIO pins
bus.write_byte_data(relay_address, relay_num, 0xFF) def relay_off(bus, relay_num): bus.write_byte_data(relay_address, relay_num, 0x00) client = InfluxDBClient(influxdb_host, database=db) client.create_database(db) # Bosch BME280: # https://www.amazon.com/Adafruit-BME280-Temperature-Humidity-Pressure/dp/B013W1AJUY bme_bus_num = 1 bme_address = 0x76 sensor = smbus.SMBus(bme_bus_num) calibration_params = bme280.load_calibration_params(sensor, bme_address) host = socket.gethostname() # Geeekpi Relay: # https://www.amazon.com/GeeekPi-Raspberry-Expansion-Programming-Programmable/dp/B07Q2P9D7K relay_bus_num = 1 relay_address = 0x10 bus = smbus.SMBus(relay_bus_num) while True: try: data = bme280.sample(sensor, bme_address, calibration_params) temperature = round(data.temperature * 9 / 5 + 32, 2) pascals = data.pressure hectopascals = pascals / 100 humidity = round(data.humidity, 2)
def get_bme280_data(**kwargs): from time import sleep verbose = kwargs['verbose'] read_interval = kwargs['BME280_read_interval'] interface_type = kwargs['BME280_interface'] if interface_type == 'i2c': try: import smbus2 import bme280 port = 1 address = kwargs['BME280_i2c_address'] bus = smbus2.SMBus(port) while True: calibration_params = bme280.load_calibration_params( bus, address) data = bme280.sample(bus, address, calibration_params) redis_db.mset({ 'BME280_Humidity': round(data.humidity, 3), 'BME280_Temperature': round(data.temperature, 3), 'BME280_Pressure': round(data.pressure, 3) }) redis_db.expire('BME280_Temperature', read_interval * 2) redis_db.expire('BME280_Humidity', read_interval * 2) redis_db.expire('BME280_Pressure', read_interval * 2) if bool(verbose) is True: print('') print('BME280 Temperature: {0:0.1f}\xb0C'.format( data.temperature)) print('BME280 Humidity: {0:0.0f}%'.format(data.humidity)) print('BME280 Pressure: {0:0.0f}hPa'.format(data.pressure)) print('') sleep(read_interval) except Exception as err: print(f'Problem with sensor BME280: {err}') if interface_type == 'serial': import serial lecounter = 0 necounter = 0 def serial_data(port, baudrate): ser = serial.Serial(port, baudrate) ser.flushInput() ser.write(b'\x03') # Sent CTRL-C -- interrupt a running program ser.write( b'\x04' ) # Sent CTRL-D -- on a blank line, do a soft reset of the board ser.timeout = None while True: response = ser.readline() print(response) yield ser.readline() #print(response) for line in serial_data( '/dev/serial/by-path/platform-fd500000.pcie-pci-0000:01:00.0-usb-0:1.3:1.0', 38400): msg = line.decode('utf-8').split() if len(msg) < 4: lecounter += 1 redis_db.set('LECOUNTER', lecounter) continue t, h, p, sn = msg[0], msg[1], msg[2], msg[3] if t.isnumeric() and h.isnumeric() and p.isnumeric(): temperature = int(t) / 1000 humidity = int(h) / 1000 pressure = int(p) / 1000 redis_db.mset({ f'{sn}_Temperature': temperature, f'{sn}_Humidity': humidity, f'{sn}_Pressure': pressure }) redis_db.expire(f'{sn}_Temperature', read_interval * 2) redis_db.expire(f'{sn}_Humidity', read_interval * 2) redis_db.expire(f'{sn}_Pressure', read_interval * 2) if bool(verbose) is True: print( f'{sn}: Temperature: {temperature}°C, Humidity: {humidity}%, Pressure: {pressure}hPa' ) else: necounter += 1 redis_db.set('NECOUNTER', necounter) sleep(0.1)
# Setup to flash a LED on GPIO-14 (TXD) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(14, GPIO.OUT) GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(15, GPIO.RISING, callback=toggle_display, bouncetime=200) visible = True port = 1 bus = smbus2.SMBus(port) oled_device = ssd1306(bus) bme280.load_calibration_params(bus) fmt = '{0:5d}: {1} {2:0.3f} deg C, {3:0.2f} hPa, {4:0.2f} %' counter = 1 while True: GPIO.output(14, True) data = bme280.sample(bus) # Use default address (0x76) print( fmt.format(counter, data.timestamp, data.temperature, data.pressure, data.humidity)) with canvas(oled_device) as draw: draw.text((0, 0), text=data.timestamp.strftime("%Y-%m-%d %H:%M:%S"), fill=255) draw.line((0, 12, 128, 12), fill=255) draw.text((0, 14), text='{0:0.3f} deg C'.format(data.temperature),
# apt install python3-pip # sudo pip3 install RPi.BME280 # import time import smbus2 import bme280 from EbOled import EbOled BME280_ADDR = 0x76 BUS_NO = 1 # BME280 i2c = smbus2.SMBus(BUS_NO) bme280.load_calibration_params(i2c, BME280_ADDR) # OLEDパネル oled = EbOled() oled.begin() oled.clear() oled.display() try: while True: data = bme280.sample(i2c, BME280_ADDR) oled.drawString('気温 :' + str(round(data.temperature, 1)) + '℃', 0) oled.drawString('湿度 :' + str(round(data.humidity, 1)) + '%', 1) oled.drawString('気圧 :' + str(round(data.pressure, 1)) + 'hPa', 2) oled.display()
def sample_data_bme280(self): port = 1 address = 0x76 bus = smbus2.SMBus(port) try: bme280.load_calibration_params(bus, address) except Exception as e: print("Error on BME280 sensor. Is it connected?") return while True: try: bme280_data = bme280.sample(bus, address) self.humidity = bme280_data.humidity self.pressure = bme280_data.pressure self.ambient_temperature = bme280_data.temperature timestamp = datetime.now().strftime('%d/%m %H:%M') self.l[0].append(self.ambient_temperature) self.l[1].append(self.humidity) self.l[2].append(self.pressure) self.l[3].append(timestamp) if len(self.l[0]) > 0: array_temp = np.array(self.l[0]) if np.min(array_temp) < self.temp_min: self.temp_min = np.min(array_temp) if np.max(array_temp) > self.temp_max: self.temp_max = np.max(array_temp) if len(self.l[1]) > 0: array_humi = np.array(self.l[1]) if np.min(array_humi) < self.humi_min: self.humi_min = np.min(array_humi) if np.max(array_humi) > self.humi_max: self.humi_max = np.max(array_humi) if len(self.l[2]) > 0: array_pres = np.array(self.l[2]) index_min_press = np.argmin(array_pres) index_max_press = np.argmax(array_pres) else: index_min_press = 0 index_max_press = 0 if index_max_press > index_min_press: self.pixmap_pres = QtGui.QPixmap('./icons/arrow_up.png') # self.window.arrow_press.setScaledContents(True) # self.window.arrow_press.setPixmap(pixmap) else: self.pixmap_pres = QtGui.QPixmap('./icons/arrow_down.png') # self.window.arrow_press.setScaledContents(True) # self.window.arrow_press.setPixmap(pixmap) how_many_days = self.how_many_days max_samples = ( (60 * 60 * 24) / self.reload_seconds) * how_many_days how_many_days_press = 0.5 max_samples_press = ( (60 * 60 * 24) / self.reload_seconds) * how_many_days_press while len(self.l[0]) > max_samples: self.l[0].pop(0) while len(self.l[1]) > max_samples: self.l[1].pop(0) while len(self.l[2]) > max_samples_press: self.l[2].pop(0) self.signal_minmax.emit() self.signal_bme280.emit() sleep(self.reload_seconds) except: print("Error on BME280 sensor")
type=int, default=0, help="Seconds between readings - implies continuous running") parser.add_argument("-t", action='store_true', help="Print title row") args = parser.parse_args() if args.t: print( "datetime, co2_ccs811, co2_mhz, rh_bme280, temp_bme280, temp_mhz" ) sys.exit(0) # setup devices i2c_bus = smbus2.SMBus(i2c_port) ccs811 = create_ccs811(i2c_bus) bme280_cal = bme280.load_calibration_params(i2c_bus, bme_i2c_address) mh_z19.detection_range_2000() if args.verbose: print(f"ccs811 baseline: {ccs811.get_baseline()}") print(f"ccs811 resistance: {ccs811.get_resistance()}") print( f"ccs811 reference resistance: {ccs811.referance_resistance}") print(f"ccs811 current resistance: {ccs811.resistance}") sleep(5) # allow sensors to warmup sample_time = dt.now() n_errors = 0 while True:
def setup(port, file, bme, pms): bus = smbus2.SMBus(port) calibration = bme280.load_calibration_params(bus, bme) pms_sensor = Pms7003Sensor(pms) logging.basicConfig(filename=file, filemode='a', format='%(message)s') return bus, calibration, pms_sensor
def setup_bme280(): global bme280_calib try: bme280_calib = bme280.load_calibration_params(i2cbus, bme_address) except Exception as e: print("Error in getting bme280 calibration " + str(e))
import bme280 import smbus2 from time import sleep I2C_PORT = 1 I2C_BME_ADDRESS = 0x77 I2C_BUS = smbus2.SMBus(I2C_PORT) bme280.load_calibration_params(I2C_BUS, I2C_BME_ADDRESS) def getBME(): bme280_data = bme280.sample(I2C_BUS, I2C_BME_ADDRESS) return { "humidity": bme280_data.humidity, "pressure": bme280_data.pressure, "ambient_temperature": bme280_data.temperature } print(getBME())
#! /usr/bin/env python3 import smbus2 import bme280 #setup port = 1 supply_address = 0x76 return_address = 0x76 bus = smbus2.SMBus(port) calibration_params = bme280.load_calibration_params(bus, supply_address) calibration_params = bme280.load_calibration_params(bus, return_address) # the sample method will take a single reading and return a # compensated_reading object def read_bme(address): if 1: #Supply sensor supply_data = bme280.sample(bus, supply_address, calibration_params) print(supply_data) return (supply_data.temperature, supply_data.pressure, supply_data.humidity) elif 2: # Return Sensor return_data = bme280.sample(bus, return_address, calibration_params) print(return_data)
""" Ejemplo de lectura de temperatura, presión y humedad con el sensor bme280 Se requiere el módulo RPi.bme280 Instalación: pip3 install RPi.bme280 """ import smbus2 import bme280 port = 1 address = 0x76 # usaremos la dirección que hemos encontrado bus = smbus2.SMBus(port) calibration_params = bme280.load_calibration_params( bus, address) # parámetros de compensación # leemos los datos data = bme280.sample(bus, address, calibration_params) # mostramos los datos print(data.id) print(data.timestamp) print(data.temperature) print(data.pressure) print(data.humidity) # los mostramos en otro formato print(data)
#!/usr/bin/env python2.7 import smbus2 import bme280 as bm import time port = 1 address = 0x76 bus = smbus2.SMBus(port) while True: calibration_params = bm.load_calibration_params(bus, address) data = bm.sample(bus, address, calibration_params) print(data.temperature) time.sleep(3)
def __init__(self): self.bus = smbus2.SMBus(self.port) self.calibration_params = bme280.load_calibration_params( self.bus, self.address)
import smbus2 import bme280 import psycopg2 from matplotlib import pyplot as plt time from import conn = psycopg2.connect ( ' dbname = Proyecto_Raul_Abraham_DiegoA ' ) puerto = 1 direccion = 0x 76 bus = smbus2.SMBus (puerto) parametros_calibracion = bme280.load_calibration_params (bus, direccion) def sensarTemperatura (): datos = bme280.sample (bus, direccion, parametros_calibracion) temperatura = datos.temperature temperatura = redonda (temperatura, 3 ) print ( " Temperatura: " + str (temperatura) + " ºC " ) cur = conn.cursor () tiempo = int (time.time ()) comando = " insertar en valores de temperatura ( " + str (tiempo) + " , " + str (temperatura) + " ) " cur.execute (comando) conn.commit () cur.close ()
write_port = '/dev/ttyUSB0' brate = 9600 cmd = 'temp' read_ser = serial.Serial(read_port, baudrate=brate, timeout=None) write_ser = serial.Serial(write_port, baudrate=brate, timeout=None) print(read_ser.name) print(write_ser.name) control = False # 온습도 센서 Grove 연결 port = 1 address = 0x76 bus = smbus2.SMBus(port) bme280.load_calibration_params(bus, address) try: conn = pymysql.connect(host='192.168.0.22', user='******', password='******', \ db='testdb', charset='utf8') while True: try: if read_ser.in_waiting != 0: content = read_ser.readline() # print(content[:-2].decode()) vals = content.decode('utf-8').replace('\r\n', '') print(vals) if vals == '1': control = ~control
def get_bme280_data(**kwargs): from time import sleep verbose = kwargs['verbose'] read_interval = kwargs['read_interval'] interface_type = kwargs['interface'] sid = kwargs['id'] if interface_type == 'i2c': try: import smbus2 import bme280 port = 1 address = kwargs['i2c_address'] bus = smbus2.SMBus(port) while True: calibration_params = bme280.load_calibration_params( bus, address) data = bme280.sample(bus, address, calibration_params) redis_db.mset({ f'{sid}_BME280_Humidity': data.humidity, f'{sid}_BME280_Temperature': data.temperature, f'{sid}_BME280_Pressure': data.pressure }) redis_db.expire(f'{sid}_BME280_Temperature', read_interval * 2) redis_db.expire(f'{sid}_BME280_Humidity', read_interval * 2) redis_db.expire(f'{sid}_BME280_Pressure', read_interval * 2) if bool(verbose) is True: print('') print(f'{sid}_BME280 Temperature: {0:0.1f}\xb0C'.format( data.temperature)) print(f'{sid}_BME280 Humidity: {0:0.0f}%'.format( data.humidity)) print(f'{sid}_BME280 Pressure: {0:0.0f}hPa'.format( data.pressure)) print('') sleep(read_interval) except Exception as err: print(f'Problem with sensor BME280: {err}') if interface_type == 'serial': serial_port = kwargs['serial_port'] serial_speed = kwargs['serial_speed'] try: def serial_data(port, baudrate, timeout): import serial ser = serial.Serial(port, baudrate, timeout) while True: yield ser.readline() for line in serial_data(serial_port, serial_speed, 5): msg = line.decode('utf-8').split() if len(msg) < 3: continue redis_db.mset({ f'{sid}_BME280_Temperature': msg[0], f'{sid}_BME280_Humidity': msg[1], f'{sid}_BME280_Pressure': msg[2] }) redis_db.expire(f'{sid}_BME280_Temperature', read_interval * 2) redis_db.expire(f'{sid}_BME280_Humidity', read_interval * 2) redis_db.expire(f'{sid}_BME280_Pressure', read_interval * 2) if bool(verbose) is True: print( f'{sid}_BME280 on serial: Temperature: {msg[0]} °C, Humidity: {msg[1]} %, Pressure: {msg[2]} hPa' ) sleep(read_interval) except Exception as err: ser.close() print(f'Problem with sensor BME280: {err}')