BMP180 on RPi3
Step 1: Enable I2C
Open the Raspberry Pi configuration tool:
sudo raspi-config
Navigate to Interface Options > I2C
and enable it.
Reboot the Raspberry Pi:
sudo reboot
Step 2: Install Required Libraries
Update your Raspberry Pi:
sudo apt update && sudo apt upgrade -y
Install the I2C tools and the necessary Python libraries:
sudo apt install -y i2c-tools python3-smbus python3-pip
Set up a virtual environment and install the circuitpython-bmp180
library:
python3 -m venv env
source env/bin/activate
pip install adafruit-circuitpython-bmp180
Verify that the BMP180 is detected on the I2C bus:
sudo i2cdetect -y 1
You should see the device address (typically 0x77
) in the output.
Step 3: Python Script
Below is the corrected Python script to read data from the BMP180 sensor and send it via an HTTP request.
import os
import urllib3
import board
import busio
import adafruit_bmp180
import time
# global variable
device = 'pi_nas'
http = urllib3.PoolManager()
def http_request(datum, vtype):
"""Sends sensor data via HTTP GET request."""
url = "[http://192.168.185.14:8080/insert/?value=%s&device=%s&type=%s](http://192.168.185.14:8080/insert/?value=%s&device=%s&type=%s)" % (datum, device, vtype)
print(url)
response = http.request('GET', url.replace(" ", "_"))
the_page = response.read()
print(f"Server response: {the_page.decode('utf-8')}")
def log_value(value, typeo):
"""Wrapper to make an HTTP request."""
http_request(value, typeo)
def get_cpu_temperature():
"""Reads the CPU temperature from the Raspberry Pi."""
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
# main function
def main():
"""
Main function to initialize the sensor, read data, and log values.
"""
i2c = busio.I2C(board.SCL, board.SDA)
bmp = adafruit_bmp180.BMP180_I2C(i2c)
# change this to match the location's pressure (hPa) at sea level
bmp.sea_level_pressure = 1013.25
while True:
temperature = bmp.temperature
pressure = bmp.pressure
altitude = bmp.altitude
# Print values to console
print(f"Temperature: {temperature:.1f} °C")
print(f"Pressure: {pressure:.1f} hPa")
print(f"Altitude: {altitude:.1f} mts")
# Log values to the web server
log_value(get_cpu_temperature(), "CPU Temp")
log_value(temperature, "Bar Temp")
log_value(pressure, "Pressure")
log_value(bmp.sea_level_pressure, "Sea Pressure")
log_value(altitude, "Altitude")
time.sleep(2)
if __name__ == "__main__":
main()