Connecting a BME280 environmental sensor via I2C
Posted: Sat Dec 31, 2022 11:55 pm
Thought I would share my experience of getting an i2c sensor talking to a STEMlab 125-14 using Python. One of the challenges is a lot of Python sensor drivers hardcode the SMbus number. The code below works around that and allows a BME280 module to be successfully read. If you aren't familiar, the BME280 senses atmospheric temperature, pressure, and humidity. You can also get a calculated altitude. Hooking up the sensor is straightforward using the RP STEMlab's Extension connectors:
I used this module: https://www.sparkfun.com/products/15440. BME280 modules can also be found on Amazon, Ebay, etc. just keep in mind the i2c address may be different and the code will need to match (BME280 can be hardware strapped for 0x76 or 0x77).
The Python script relies on a couple of libraries: smbus2 and RPi.bme280. smbus2 lets us set the i2c bus to 0, which is the correct bus number for the STEMlab125-14. RPi.bme280 is a driver for the BME280 sensor. It abstracts us from all the gory details of talking to the sensor over i2c. When you install the RPi.bme280 library, it will also install smbus2 for you. To install on your Stemlab, type this from the command line:
Assuming you have the sensor hooked up, you can now run the script:
The results will look like this:
The data is formatted for USA units and also for Machinechat's JEDI IoT softwarehttps://www.machinechat.io/jedi. You can change the output for whatever format you need.
Code is here: https://gist.github.com/machinechat/40f ... 10c787d3e4
Daryl
Code: Select all
# Sensor Red Pitaya Extension connector
# VIN E1 - +3V3
# GND E1 - GND
# SDA E2 - I2C_SDA
# SCL E2 - I2C_SCL
The Python script relies on a couple of libraries: smbus2 and RPi.bme280. smbus2 lets us set the i2c bus to 0, which is the correct bus number for the STEMlab125-14. RPi.bme280 is a driver for the BME280 sensor. It abstracts us from all the gory details of talking to the sensor over i2c. When you install the RPi.bme280 library, it will also install smbus2 for you. To install on your Stemlab, type this from the command line:
Code: Select all
pip3 install rpi.bme280
Code: Select all
python3 ./RPitaya_bme280.py
Code: Select all
root@rp-f06578:~/jedi/plugins# python3 ./RPitaya_bme280.py
metric:id=bme280-office1231,n=Temperature,vd=69.95,u=F
metric:id=bme280-office1231,n=Humidity,vd=38.50,u=%
metric:id=bme280-office1231,n=Pressure,vd=29.70,u=inHg
Code is here: https://gist.github.com/machinechat/40f ... 10c787d3e4
Daryl