In this tutorial, you will learn how to quickly set up the Raspberry Pi with the BME280 Pressure, Temperature, and Humidity sensor in Python. This versatile sensor allows you to collect environmental data, making it an excellent choice for weather monitoring, home automation, and other IoT projects. Follow the step-by-step guide to establish the connection between your Raspberry Pi and the BME280 sensor.
Note that in the video we utilize a 4B model of the Raspberry Pi but you can use any models from 1-5 just ensure the pin connections are the same.
You can purchase the BME280 from ShillehTek here:
Please consider subscribing or supporting channel by donating in the link down below to allow us to produce more content!
Subscribe:
Support:
https://www.buymeacoffee.com/mmshilleh
Step 1-) Physical ConnectionConnect Jumper wires between the BME and the Raspberry Pi as follows:
Pip install the following three libraries:
pip install RPI.BME280 smbus2 matplotlib
Note that if its your first time it will take a while to pip install these libraries, so be patient.
Run the sample code in a Python file:
import smbus2
import bme280
import time
import matplotlib.pyplot as plt
from datetime import datetime
# BME280 sensor address (default address)
address = 0x76
# Initialize I2C bus
bus = smbus2.SMBus(1)
# Load calibration parameters
calibration_params = bme280.load_calibration_params(bus, address)
# Create lists to store historical sensor data
timestamps = []
temperature_celsius_values = []
humidity_values = []
pressure_values = []
# Create a variable to control the loop
running = True
# Set up the plot
plt.ion() # Turn on interactive mode
fig, axs = plt.subplots(3, 1, sharex=True, figsize=(10, 8))
fig.suptitle('Real-time Sensor Readings')
# Labels for the subplots
axs[0].set_ylabel('Temperature (ºC)')
axs[1].set_ylabel('Humidity (%)')
axs[2].set_ylabel('Pressure (hPa)')
# Loop forever
while running:
try:
# Read sensor data
print('Running')
data = bme280.sample(bus, address, calibration_params)
# Extract temperature, pressure, humidity, and corresponding timestamp
temperature_celsius = data.temperature
humidity = data.humidity
pressure = data.pressure
timestamp = data.timestamp
# Append data to lists
timestamps.append(timestamp)
temperature_celsius_values.append(temperature_celsius)
humidity_values.append(humidity)
pressure_values.append(pressure)
# Plot the data
for i, (ax, values, label) in enumerate(zip(axs, [temperature_celsius_values, humidity_values, pressure_values], ['Temperature (ºC)', 'Humidity (%)', 'Pressure (hPa)'])):
ax.clear()
ax.plot(timestamps, values, label=label)
ax.legend()
ax.set_ylabel(label)
axs[-1].set_xlabel('Time')
fig.autofmt_xdate(rotation=45)
plt.pause(1) # Pause for 1 second to update the plot
time.sleep(1)
except KeyboardInterrupt:
print('Program stopped')
running = False
except Exception as e:
print('An unexpected error occurred:', str(e))
running = False
# Close the plot at the end
plt.ioff()
plt.show()
Importing Libraries:
import smbus2
: Imports a library for I2C communication on Raspberry Pi.import bme280
: Imports a library to interact with the BME280 sensor.import time
: Imports a library to handle time-related functions.import matplotlib.pyplot as plt
: Imports a library for plotting graphs.from datetime import datetime
: Imports thedatetime
class for handling timestamps.- Importing Libraries:
import smbus2
: Imports a library for I2C communication on Raspberry Pi.import bme280
: Imports a library to interact with the BME280 sensor.import time
: Imports a library to handle time-related functions.import matplotlib.pyplot as plt
: Imports a library for plotting graphs.from datetime import datetime
: Imports thedatetime
class for handling timestamps.
Setting Up BME280 Sensor:
address = 0x76
: Sets the default I2C address of the BME280 sensor.bus = smbus2.SMBus(1)
: Initializes the I2C bus for communication.- Setting Up BME280 Sensor:
address = 0x76
: Sets the default I2C address of the BME280 sensor.bus = smbus2.SMBus(1)
: Initializes the I2C bus for communication.
Loading Calibration Parameters:
calibration_params = bme280.load_calibration_params(bus, address)
: Loads calibration parameters needed for accurate sensor readings.- Loading Calibration Parameters:
calibration_params = bme280.load_calibration_params(bus, address)
: Loads calibration parameters needed for accurate sensor readings.
Creating Lists for Data Storage:
- Lists (
timestamps
,temperature_celsius_values
,humidity_values
,pressure_values
) are created to store historical sensor data. - Creating Lists for Data Storage:Lists (
timestamps
,temperature_celsius_values
,humidity_values
,pressure_values
) are created to store historical sensor data.
Setting Up Plotting:
plt.ion()
: Turns on interactive mode for Matplotlib.fig, axs = plt.subplots(3, 1, sharex=True, figsize=(10, 8))
: Sets up a 3-subplot figure for temperature, humidity, and pressure.- Labels and title are set for each subplot.
- Setting Up Plotting:
plt.ion()
: Turns on interactive mode for Matplotlib.fig, axs = plt.subplots(3, 1, sharex=True, figsize=(10, 8))
: Sets up a 3-subplot figure for temperature, humidity, and pressure.Labels and title are set for each subplot.
Data Acquisition Loop:
while running:
: Initiates an infinite loop for continuously reading sensor data.data = bme280.sample(bus, address, calibration_params)
: Reads temperature, humidity, and pressure data from the BME280 sensor.- Extracts individual values (temperature, humidity, pressure, timestamp) from the sensor data.
- Appends the values to their respective lists (
timestamps
,temperature_celsius_values
,humidity_values
,pressure_values
). - Data Acquisition Loop:
while running:
: Initiates an infinite loop for continuously reading sensor data.data = bme280.sample(bus, address, calibration_params)
: Reads temperature, humidity, and pressure data from the BME280 sensor.Extracts individual values (temperature, humidity, pressure, timestamp) from the sensor data.Appends the values to their respective lists (timestamps
,temperature_celsius_values
,humidity_values
,pressure_values
).
Real-time Plotting:
- Plots the collected data in real-time using Matplotlib.
- Clears and updates each subplot with the latest data points.
- Pauses for 1 second (
plt.pause(1)
) to update the plot. - Real-time Plotting:Plots the collected data in real-time using Matplotlib.Clears and updates each subplot with the latest data points.Pauses for 1 second (
plt.pause(1)
) to update the plot.
Handling User Interruption:
- The loop can be interrupted by a keyboard interrupt (
KeyboardInterrupt
) or any other exception. - If interrupted, the program prints a message and sets
running
toFalse
, exiting the loop. - Handling User Interruption:The loop can be interrupted by a keyboard interrupt (
KeyboardInterrupt
) or any other exception.If interrupted, the program prints a message and setsrunning
toFalse
, exiting the loop.
Closing the Plot:
plt.ioff()
: Turns off interactive mode.plt.show()
: Displays the final plot.- Closing the Plot:
plt.ioff()
: Turns off interactive mode.plt.show()
: Displays the final plot.
This script continuously reads data from the BME280 sensor, updates real-time plots for temperature, humidity, and pressure, and can be stopped by the user with a keyboard interrupt. You can modify the plots as you like!
Conclusion:Hope you got the BME280 running, which again is a very powerful and consistent sensor that all DIY enthusiasts should have. Do not forget to buy it at ShillehTek on Amazon if you have not, since it already comes pre-soldered. Also do not forget to subscribe to the YouTube channel in the link above! Thanks for your time.
Comments