Skip to content

Instantly share code, notes, and snippets.

@877dev
Last active April 21, 2021 19:32
Show Gist options
  • Save 877dev/8e61784520e00a1c58f55a38791f9266 to your computer and use it in GitHub Desktop.
Save 877dev/8e61784520e00a1c58f55a38791f9266 to your computer and use it in GitHub Desktop.
Attaching BME280 sensor to a Pi4 and sending to MQTT broker
#!/usr/bin/python
# Written by 877dev 11/11/2020
import smbus2
import bme280
#import paho.mqtt.client as mqtt #import the client1
import paho.mqtt.publish as publish
port = 1
address = 0x76
bus = smbus2.SMBus(port)
broker_address="192.168.1.95"
calibration_params = bme280.load_calibration_params(bus, address)
# the sample method will take a single reading and return a
# compensated_reading object
data = bme280.sample(bus, address, calibration_params)
# UNCOMMENT PRINT STATEMENTS TO ENABLE TERMINAL PRINTS:
# the compensated_reading class has the following attributes
#print(data.id)
#print(data.timestamp)
#print(data.temperature)
#print(data.pressure)
#print(data.humidity)
# there is a handy string representation too
#print(data)
msgs = [
{'topic':"octoPrint/bme280/temperature", 'payload':(data.temperature)},
("octoPrint/bme280/humidity", (data.humidity), 1, False),
("octoPrint/bme280/pressure", (data.pressure), 1, False)
]
publish.multiple(msgs, hostname=broker_address)
"""
#EXAMPLE FROM PAHO LIBRARY
msgs = [{'topic':"paho/test/multiple", 'payload':"multiple 1"}, ("paho/test/multiple", "multiple 2", 0, False)]
publish.multiple(msgs, hostname="test.mosquitto.org")
"""

How I installed the script:

Note this is from a while back so please check for errors as you go!

Update packages:
sudo apt-get update

Check python version:
python --version - need 2.7

Install tools:
sudo apt-get install i2c-tools python-pip python-smbus - SHOULD BE smbus2 ??

Check bmesensor address (needed later):
i2cdetect -y 1

Install paho mqtt client:
pip install paho-mqtt

Install BME280 library:
pip install RPi.bme280

Install smbus2 library:
sudo pip install smbus2

Create the python script:
sudo nano bme280_publish_mqtt.py

Copy and paste the script, replacing address with your bme snesor address, and replacing broker_address with yours. Exit and save.
Make executable:
chmod +x filename.py

You can now run the script and check it publishes to your mqtt broker:
./filename/py

Steup crontab to run every 1 minute
crontab -e
then add this:

# publish bme280 sensor data to mqtt every 1 minute
*/1 * * * * ~/877mqtt/bme280_publish_mqtt.py >/dev/null 2>&1

Resources used

https://www.circuitbasics.com/how-to-write-and-run-a-python-program-on-the-raspberry-pi/
http://www.steves-internet-guide.com/into-mqtt-python-client/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment