try:
    from smbus2 import SMBus
except ImportError:
    from smbus import SMBus

print("""compensated-temperature.py - Use the CPU temperature
to compensate temperature readings from the BME280 sensor.
Method adapted from Initial State's Enviro pHAT review:
https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441

Press Ctrl+C to exit!

""")

bus = SMBus(1)
bme280 = BME280(i2c_dev=bus)


# Get the temperature of the CPU for compensation
def get_cpu_temperature():
    process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
    output, _error = process.communicate()
    output = output.decode()
    return float(output[output.index('=') + 1:output.rindex("'")])


# Tuning factor for compensation. Decrease this number to adjust the
# temperature down, and increase to adjust up
factor = 0.8

cpu_temps = [0] * 5
Example #2
0
from PIL import ImageFont
from fonts.ttf import RobotoMedium as UserFont
import logging

logging.basicConfig(
    format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S')

logging.info(
    """all-in-one.py - Displays readings from all of Enviro plus' sensors
Press Ctrl+C to exit!
""")

# BME280 temperature/pressure/humidity sensor
bme280 = BME280()

# Create ST7735 LCD display class
st7735 = ST7735.ST7735(port=0,
                       cs=1,
                       dc=9,
                       backlight=12,
                       rotation=270,
                       spi_speed_hz=10000000)

# Initialize display
st7735.begin()

WIDTH = st7735.width
HEIGHT = st7735.height
Example #3
0
import threading
import database
import math
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse, HTMLResponse

try:
    from smbus2 import SMBus
except ImportError:
    from smbus import SMBus
from bme280 import BME280
from sgp30 import SGP30

app = FastAPI()
smbus = SMBus(1)
bme280 = BME280(i2c_dev=smbus)
sgp30 = SGP30()
lock = threading.Lock()
eco2, tvoc = 0, 0


def get_cpu_temp():
    file = open('/sys/class/thermal/thermal_zone0/temp')
    cpu_temp = file.readline().strip()
    file.close()
    return float(cpu_temp) / 1000


# Formula source: https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
# Within 0.1% accuracy over temperature range –30°C to +35°C
def calculate_absolute_humidity(temp, relative_hum):
Example #4
0
 def setUp(self):
     self.bus = SMBus(1)
     self.bme280 = BME280(i2c_dev=self.bus)
Example #5
0
oled_i2c = ftdi_i2c(ft232h_device, 0x3C)
oled_dev = ssd1306(oled_i2c)

# Font used for OLED disply
oled_font = ImageFont.truetype('FreePixel.ttf', 16)

# FTDI I2C Bus Controller for BME280
pyftdi_i2c = I2cController()
pyftdi_i2c.configure(ft232h_device)

# Configure BME280 I2C port and override with wrapper
bme280_i2c = pyftdi_i2c.get_port(0x76)
bme280_i2c.__class__ = FTDI_WRAPPER_I2C

# BME280 sensor
bme280 = BME280(i2c_dev=bme280_i2c)


# Prints the published message number upon send
def on_publish(client, userdata, mid):
    print(f'mid: {str(mid)}')


# Paho MQTT client setup to connect to localhost
client = paho.Client()
client.on_publish = on_publish
client.connect('localhost', 1883)
client.loop_start()


# A function that chops a string decimal number at the hundreds place
try:
    from smbus2 import SMBus
except ImportError:
    from smbus import SMBus
from bme280 import BME280

print("""temperature-compare.py - Compares oversampling levels
(requires two BME280s with different addresses).

Press Ctrl+C to exit!

""")

# Initialise the BME280
bus = SMBus(1)
bme280A = BME280(i2c_dev=bus)
bme280B = BME280(i2c_dev=bus, i2c_addr=0x76)

# Set up in "forced" mode
# In this mode `get_temperature` and `get_pressure` will trigger
# a new reading and wait for the result.
# The chip will return to sleep mode when finished.
bme280A.setup(mode="normal",
              temperature_oversampling=1,
              pressure_oversampling=1)
bme280B.setup(mode="normal",
              temperature_oversampling=16,
              pressure_oversampling=16)

while True:
    temperatureA = bme280A.get_temperature()
Example #7
0
def main():
    parser = argparse.ArgumentParser(
        description="Publish enviroplus values over mqtt"
    )
    parser.add_argument(
        "--broker",
        default=DEFAULT_MQTT_BROKER_IP,
        type=str,
        help="mqtt broker IP",
    )
    parser.add_argument(
        "--port",
        default=DEFAULT_MQTT_BROKER_PORT,
        type=int,
        help="mqtt broker port",
    )
    parser.add_argument(
        "--topic", default=DEFAULT_MQTT_TOPIC, type=str, help="mqtt topic"
    )
    parser.add_argument(
        "--interval",
        default=DEFAULT_READ_INTERVAL,
        type=int,
        help="the read interval in seconds",
    )
    args = parser.parse_args()

    # Raspberry Pi ID
    device_serial_number = get_serial_number()
    device_id = "raspi-" + device_serial_number

    print(
        f"""mqtt-all.py - Reads Enviro plus data and sends over mqtt.

    broker: {args.broker}
    client_id: {device_id}
    port: {args.port}
    topic: {args.topic}

    Press Ctrl+C to exit!

    """
    )

    mqtt_client = mqtt.Client(client_id=device_id)
    mqtt_client.on_connect = on_connect
    mqtt_client.on_publish = on_publish
    mqtt_client.connect(args.broker, port=args.port)

    bus = SMBus(1)

    # Create BME280 instance
    bme280 = BME280(i2c_dev=bus)

    # Create LCD instance
    disp = ST7735.ST7735(
        port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000
    )

    # Initialize display
    disp.begin()

    # Try to create PMS5003 instance
    HAS_PMS = False
    try:
        pms5003 = PMS5003()
        pm_values = pms5003.read()
        HAS_PMS = True
        print("PMS5003 sensor is connected")
    except SerialTimeoutError:
        print("No PMS5003 sensor connected")

    # Display Raspberry Pi serial and Wi-Fi status
    print("RPi serial: {}".format(device_serial_number))
    print("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected"))
    print("MQTT broker IP: {}".format(args.broker))

    # Main loop to read data, display, and send over mqtt
    mqtt_client.loop_start()
    while True:
        try:
            values = read_bme280(bme280)
            values["serial"] = device_serial_number
            print(values)
            mqtt_client.publish(args.topic, json.dumps(values))
            display_status(disp, args.broker)
            time.sleep(args.interval)
        except Exception as e:
            print(e)
Example #8
0
def bme280_init():
    i2c = i2c_init(1)
    bme = BME280(i2c=i2c)
    return bme
Example #9
0
def bme280_init():
    i2c = i2c_init(1)
    bme = BME280(i2c=i2c)
    print(bme.values)
    return bme
Example #10
0
# simple basic example - ESP32 + i2c lcd display
# cp("examples/lcd2_bme280.py") > main.py


from time import sleep
from utils.octopus import w, i2c_init, lcd2_init, get_hhmm, time_init
from shell.terminal import printTitle
from bme280 import BME280

i2c = i2c_init(1)
bme280 = BME280(i2c=i2c)

w()	# wifi connect
lcd = lcd2_init()	# 8 x 7segment display init

lcd.clear()
lcd.move_to(3,0)
lcd.putstr("octopusLAB")


def clock():
    lcd.move_to(5,1)
    lcd.putstr(get_hhmm(":"))
    sleep(0.5)
    lcd.move_to(5,1)
    lcd.putstr(get_hhmm(" "))
    sleep(1)

time_init() # server > time setup

printTitle("examples/clock.py")
Example #11
0
    pin_sens = 16
else:                   # ESP8266
    pin_scl = 5
    pin_sda = 4
    pin_sens = 2

width = 64
height = 48
frequency = 100000
OP_SINGLE_HRES2 = 0x21
       
i2c = I2C(scl=Pin(pin_scl), sda=Pin(pin_sda), freq=frequency)
oled = SSD1306_I2C(width, height, i2c)
#sensor_Pin = Pin(pin_sens, Pin.IN)
#sensor = DHT22(sensor_Pin)
sensor = BME280(i2c=i2c)
sensor2 = AHT20(i2c)
topic1 = b'TempBME280'
topic2 = b'Humid'
topic3 = b'PressBME280'
topic4 = b'Light'

client_id = hexlify(unique_id())

def connect_to_mqtt(config):
  client = MQTTClient(client_id, config['mqtt']['broker'])
  client.connect()
  print('Connected to %s MQTT broker' % (config['mqtt']['broker']))
  return client

def restart_and_reconnect():
from machine import I2C, ADC, Pin
from sh1106 import SH1106_I2C
from bme280 import BME280
from time import sleep

WIDTH  = 128                                            # oled display width
HEIGHT = 64                                             # oled display height

oled = SH1106_I2C(WIDTH, HEIGHT, i2c)                   # Init OLED display
oled.rotate(True)

bme = BME280(i2c = i2c)                                 # Init BME280 sensor

def get_data():
    temp, press, hum = bme.read_compensated_data()
    temp = temp / 100
    press = press / 25600
    hum = hum / 1024
    return (temp, hum, press)

def print_data(data):
    temp, hum, press = data
    oled.fill(0)
    oled.text("Temperature:",5,5)
    oled.text(" %.1f deg. C" % temp,5,15)
    oled.text("Rel. humidity:",5,25)
    oled.text(" %.1f" % hum + " %",5,35)
    oled.text("Pressure:",5,45)
    oled.text(" %.1f hPa" % press,5,55)
    oled.show()
def smbus_init():
    # Initialise the BME280
    bus = SMBus(1)
    bme280 = BME280(i2c_dev=bus)
    print("smbus_init Init ...")
    return bme280
Example #14
0
# Test les differents senseurs du montage Cabane

from machine import Pin, I2C
from time import sleep

# declare le bus i2c
i2c = I2C(sda=Pin(4), scl=Pin(5))

# Tester le tsl2561 - senseur lux
from tsl2561 import TSL2561
tsl = TSL2561(i2c=i2c)
print("tsl2561: {0:.2f}lx".format(tsl.read()))

# tester le bmp280 - senseur pression/température
from bme280 import BME280, BMP280_I2CADDR
bmp = BME280(i2c=i2c, address=BMP280_I2CADDR)
(t, p, h) = bmp.values  # capturer les valeurs sous format texte
print("bmp280: %s" % t)  # temperature
print("bmp280: %s" % p)  # pression

# tester le am2315 - senseur humidité/température
from am2315 import AM2315
am = AM2315(i2c=i2c)
am.measure()  # reactive le senseur
sleep(1)
am.measure()
print("am2315: {0:.2f}C".format(am.temperature()))
print("am2315: {0:.2f}%Rh".format(am.humidity()))

print("All done!")
Example #15
0
        bmx_present2 = True
    if device == light_address2:
        light_present2 = True 
            
if display_present2:
    oled = SSD1306_I2C(width, height, i2c, addr=display_address2)
if display_present1:
    oled = SSD1306_I2C(width, height, i2c, addr=display_address1)
if ahtx0_present:    
    sensor = AHT20(i2c)
if sht3x_present2:    
    sensor = SHT30(scl_pin=pin_scl, sda_pin=pin_sda, i2c_address=sht3x_address2)            
if sht3x_present1:    
    sensor = SHT30(scl_pin=pin_scl, sda_pin=pin_sda, i2c_address=sht3x_address1)
if bmx_present2:
    sensor2 = BME280(mode=BME280_OSAMPLE_16, address=bmx_address2,i2c=i2c)
if bmx_present1:
    sensor2 = BME280(mode=BME280_OSAMPLE_16, address=bmx_address1,i2c=i2c)
    
topic1 = b'TempDHT22'
topic2 = b'HumidDHT22'
topic3 = b'Press'
topic4 = b'Light'
topic5 = b'LPG'
topic6 = b'CO'
topic7 = b'ME'

client_id = hexlify(unique_id())

def connect_to_mqtt(config):
  client = MQTTClient(client_id, config['mqtt']['broker'])
Example #16
0
    "Output from sudo timedatectl set-time: {}".format(output_timedatectl))

logger.info("GPS initial altitude: " + str(gps.altitude()))

gps.startThread()

# 1hPa reduction per 8.3m altitude (seems that https://www.meteoschweiz.admin.ch/home/messwerte.html?param=messwerte-luftdruck-qfe-10min uses this formula).
# For a more dedicated formula see https://de.wikipedia.org/wiki/Barometrische_Höhenformel, section Reduktion auf Meereshöhe

ADDRESS_IN_CAPSULE = 0x77
qfe = BME280.pressureStatic(
    ADDRESS_IN_CAPSULE
)  # do NOT make an intance here, which would create a thread.
qff = qfe + (gps.altitude() /
             8.3) - 1.1  # - correction-factor. Determined empiric
bme280InCapsule = BME280(qff, ADDRESS_IN_CAPSULE)
bme280InCapsule.startThread("BME280CapsuleThread")

ADDRESS_OUTSIDE = 0x76  # wire SDO to GND
qfe = BME280.pressureStatic(
    ADDRESS_OUTSIDE
)  # do NOT make an intance here, which would create a thread.
qff = qfe + (gps.altitude() /
             8.3) - 1.15  # - correction-factor. Determined empiric
bme280Outside = BME280(qff, ADDRESS_OUTSIDE)
bme280Outside.startThread("BME280OutsideThread")

measureRecorder = MeasureRecorder('./data/log/measures.csv', 2, board, gps,
                                  bme280InCapsule, bme280Outside)
measureRecorder.start_measures()