Code

There are two pieces of code needed to run the temperature / humidity monitor. The first code, storagemonitor.py reads data from the sensor and sends it to the Thingspeak account. The second piece of code, storagemonitor.service ensures storagemonitor.py is run when the Raspberry Pi starts up. Once again, open up the terminal...

storagemonitor.py

import smbus2 #i2c Library
import bme280 #BME280 Sensor Library https://pypi.org/project/RPi.bme280
import time
import requests #HTTP Library https://pypi.org/project/requests/
KEY = 'TYMEW6X9PQ7XD26G' #Thingspeak API key


port = 1
address = 0x77 #You can find this with the command sudo i2cdetect -y 1
bus = smbus2.SMBus(port)


url = 'https://api.thingspeak.com/update'


while True:

    try:
        calibration_params = bme280.load_calibration_params(bus, address)
        data = bme280.sample(bus, address, calibration_params)
        temperature = round(data.temperature * 1.8+32) #convert from Celsius to Fahrenheit and round to the nearest whole number
        humidity = round(data.humidity) #round to the nearest whole number
        params = {'key': KEY, 'field1': temperature, 'field2': humidity}
        res = requests.get(url, params=params)
        print (data)
    except:
        print ('error')
    time.sleep(3600) # Wait 36000 seconds (1 hour) before collecting data again

 

Explanation

The actually location and name of this code doesn't matter as long as the value matches the one in storagemonitor.service but in this case we called it storagemonitor.py and placed it in the /home/pi directory

address = 0x77

77 is the address of the sensor found using the command sudo i2cdetect -y 1. If you got a different address, simply replace the "77" with it.

 

KEY = 'FH9F8SBIYY1GVW0O'

This is the Write API Key found in the "API Keys" section of our channel's settings

storagemonitor.service

[Unit]
Description=Humidity / Temperature monitor for VRHC storage
 
[Service]
ExecStart=Sudo python3 /home/pi/storagemonitor.py
StandardOutput=null
Restart=on-failure
 
[Install]
WantedBy=multi-user.target
Alias=storagemonitor.service

Explanation

 

The text that starts after ExecStart= is the command that's executed when the Pi starts up, it simply runs storagemonitor.py.

The storagemonitor.service file must live in /etc/systemd/system/storagemonitor.service if it's going to be run when the Pi starts up

After everything is where it should be, you can enable the service with the command sudo systemctl enable storagemonitor.service