The MagPi - July 2018

(Steven Felgate) #1

raspberrypi.org/magpi July 2018 73


BUILD A WEATHER STATION Feature


OPEN IDLE
In Raspbian, select Menu > Programming >
Python 3 (IDLE). Create a new Python file,
save it as bme280_sensor.py in the /home/pi/
weather-station directory and add the code
from bme_280_sensor.py to it.

DEEP BREATH
While the code is running, exhale onto the
BME280 sensor. You should see the humidity
value (and possibly the temperature) increase.
Press CTRL+C to exit the program.

UPDATE THE CODE
Replace the while True loop with a
function called read_all() that returns
the humidity, pressure, and temperature
readings, in that order. Update your code using
bme_280_sensor_2.py as a guide.

GROUND TEMPERATURE
The BME280 will report the air temperature,
but this can be warmer than the ground,
particularly if it’s frosty. A DS18B20 thermal
probe (magpi.cc/JILuTd) stuck into the soil is
a useful supplemental measurement.

WIRING THE SENSOR
Normally the DS18B20 comes with three bare
wires, so the easiest way to test it is to use
PCB mount screw terminal blocks that can be
plugged into breadboards. Add your DS18B20 to
your circuit as shown in Figure 1.

EDIT THE BOOT
Open the file /boot/config.txt:
sudo nano /boot/config.txt
Edit it by adding the line below at
the bottom:

Right The Adafruit BME280 I^2 C
or SPI Temperature Humidity
STEP 1 Pressure Sensor

STEP 2


STEP 3


STEP 4


STEP 5


import bme280
import smbus2
from time import sleep

port = 1
address = 0x77 # Adafruit BME280 address. Other BME280s
may be different
bus = smbus2.SMBus(port)

bme280.load_calibration_params(bus,address)

while True:
bme280_data = bme280.sample(bus,address)
humidity = bme280_data.humidity
pressure = bme280_data.pressure
ambient_temperature = bme280_data.temperature
print(humidity, pressure, ambient_temperature)
sleep( 1 )

01.
02.
03.
04.
05.
06.

07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.

bme280_sensor.py


dtoverlay=w1-gpio
Then open /etc/modules:
sudo nano /etc/modules
Add the lines below at the bottom
of the file:
w1-gpio
w1-therm
Reboot the Raspberry Pi.
Open the file /home/pi/weather-station/
ds18b20_therm.py in IDLE and run it (see
‘Software download’ box on page 71 to use
Git to clone this file). You should see the
temperature printed out in the Python
Shell window.

import bme280
import smbus2
from time import sleep

port = 1
address = 0x76
bus = smbus2.SMBus(port)

bme280_load_calibration_params(bus, address)

def read_all():
bme280_data = bme.sample(bus,address)
return bme280_data.humidity, bme280_data.pressure,
bme280_data.temperature

01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.

bme280_sensor_2.py


CODE
Language: Python
Name:
bme280_sensor.py,
bme280_sensor_2.py
Link:
magpi.cc/GhJlde
Name:
ds18b20_therm.py
Link:
magpi.cc/NQGLtb

STEP 6

Free download pdf