How to control the temperature of your terrarium room remotely

Keeping an eye on temperature is extremely important when keeping salamanders, as they are particularly susceptible to high temperatures, and being able to quickly check on temperature remotely is incredibly easy now with the IoT, and it will prevent some of the worries with leaving the animals for long period of time for holidays.

Some temperature sensor solutions already exist and are readily available online, but what I wanted was something that not only told me temperature, but would also log the information for future data analysis, so I decided to build it myself.

My work is based on this tutorial by Allan Schwartz, which I invite everyone to read as it is the backbone of this tutorial. In the tutorial below you will find some adjustments to the code I found necessary for it to work seamlessly, as well as the missing steps, so that you will be able to follow the tutorial even if you are not familiar with coding, Raspberry Pi or Google API.

Hardware:

Here is a list of components you will need. I have included our Affiliate Amazon* links for ease, but each of these components could be found cheaper on eBay, Aliexpress or Raspberry Pi/electronics dedicated websites, so shop around for the best prices.

  • Bare Minimum components:
    • Raspberry Pi Zero W (£15): This is a tiny board which costs around £15 depending on where you buy it. I decided to buy the version with GPIO pins already soldered (WH) which, while a few pounds more expensive, it saved me from soldering on the Raspberry Pi
    • Micro SD Card (£3/5): Any will do, but probably you want at least 8GB.
    • BME280 chip (£1/10): The price of this chip changes a lot depending on where you buy it, so shop around but make sure to not buy the BMP280 chip by mistake.
    • GPIO Jumper cables (£1/6): You will need 4, but they usually come in packs of 10/20/40, so you only need to buy once for multiple projects. In my setup I used Female-to-Female cables, but you may need Male-to-Male or Male-to-Female depending on your setup.
    • Power Supply (£5): You will need a microUSB cable to supply power to the Pi, if you don’t have a smartphone charger around you’ll need to buy one.
  • Recommended accessories: Things you will need but can use for more projects in the future
    •  Pi Zero Starter Kit (~£5): In order to connect the Pi to a monitor and keyboard you will need a MicroUSB to USB cable and a MicroHDMI to HDMI cable. You can buy these pieces independently or with a kit, which usually also come with a Pi case which could be useful to protect the case.
    • USB Hub (~£5): In order to connect both a mouse and a keyboard to the Raspberry Pi Zero W you will need a USB hub as this model of Pi only has one MicroUSB.
    •  Soldering Iron (£15): You will need one to solder the pins to the sensor or the Raspberry Pi. If you are not comfortable with soldering you may need to buy a sensor or Raspberry Pi with already soldered pins.

Connection:

Connect the BME280 and Raspberry Pi following the diagram below.

Just to note, as these chips are produced by different manufacturers, the order of pins could vary on each chip. 

In my case for example, the 3.3v pin was labelled as VCC, which made it harder to find, furthermore there are 2 extra pins which are not needed for this application, which can be ignored. Make sure to recognise and double check your pin connections.

Cable connections on my chip. Due to the many manufacturers, the order of the pins of your sensor could be different.
Cable connection on the Raspberry Pi Zero W (encased in a case that came with the starter kit)

I2C Configuration:

The BME280 connects to the Raspberry Pi via I2C. As a first step, enable I2C via the Raspberry Pi Configuration interface.

Then open the terminal and copy and paste the following code in order to install the i2c-tools.

sudo apt-get update
sudo apt-get install -y python-smbus i2c-tools

Then reboot the Raspberry Pi.

At this point, by running the command i2cdetect -y 1 you should be able to see the chip. If the chip is not appearing like in the image below, there might either be an issue with the chip, or with the soldering. The first time I tried, the chip was not showing up due to the soldering not being done properly.

BME280 Configuration:

In order to use the BME280 sensor, you need to install the code needed to read and decode the sensor. In order to do so, we will utilise this package at https://github.com/cmur2/python-bme280.

In order to install this package run the following command in the terminal.

git clone https://github.com/cmur2/python-bme280.git

After the command has run, you should find a new folder in your home named python-bme280. Inside the folder is all the information needed to run the sensor and it can be tested with the demo.py file. In order to run it, you need to open the terminal in the folder python-bme280 either via the tools option in the folder, or with the command cd python-bme280, and run the code:

python demo.py

If everything so far has worked as expected, you should be able to see the below:

Successful sensor reading (this particular reading comes from a BMP280 sensor which lacks humidity, hence why returning a value of 0%)

NB: when buying the sensor, make sure to not buy the BMP280 chip in place of the BME280 chip. The BMP280 chip is cheaper but lacks the humidity sensor. The 2 chips are very similar, and judging from posts in forum, when buying cheap versions of BME280, you may be mis-sold the BMP280.

In my case, I thought I had bought the BME280, but in reality I bought the BMP280 chip by mistake, which returns 0% for humidity. For my application humidity is not needed, so it is not an issue, but be sure to not make the same mistake as me.

Connecting with Google Sheets:

We now have all we need to read the sensor information, but we need to send this information to a Google Sheet and in order to do so, we need to activate the Google Sheet API. 

  1. Go to https://console.developers.google.com/ and create a New Project.
  2. Once you have created a new project, go to the API Library and enable the Google Sheets API.
  3. Once you have activated the Google Sheets API, go to Credentials on the menu at the right and click on CREATE CREDENTIALS.
  4. The credential you need to create is a Service account credential.
  5. Once you create it, go to edit the it and create a new Key. You will be given the option to download a file containing the key. Download the file in format JSON and rename it bme280-key.json. Take this file you have downloaded, and move it into the folder python-bme280
  6. At this point, go to your Google Drive and create a new Google Sheet file. This file will be used to log the sensor reading. Make sure to enable sharing with “Anyone with link can Edit” setting.

At this point, you have created an API account, enabled the Google Sheets API and downloaded the authorization key which will allow the Raspberry Pi to send information to the Google Sheet.

Create Python code to log BME280 reading into Google:

We are almost there, now that we can read the sensor correctly, we need to create a Python code that reads the sensor and pushes the reading to a Google Sheets.

As a first step, open your terminal an run the command:

pip install --upgrade google-api-python-client oauth2client

Then, use Thonny (pre-installed on you Raspberry Pi) to create a file called bme280-reading.py in the folder python-bme280 and paste in it the following code:

#-*- coding: utf-8 -*-
# import many libraries
from __future__ import print_function  
from googleapiclient.discovery import build  
from httplib2 import Http  
from oauth2client import file, client, tools  
from oauth2client.service_account import ServiceAccountCredentials  
import bme280  
import datetime

# My Spreadsheet ID ... This is the code of the gsheet file, you can find it into the url
MY_SPREADSHEET_ID = 'SpreadsheetID'
#My Sheet Name ... This is the name of the sheet where you will log the data
MY_SHEET_NAME = 'SheetName'

#This function takes care of uploading the main function to Google Sheet
def update_sheet(sheetname, temperature, pressure, humidity):  
    # This is where the authentication happens. Make sure the name of your key matches bme280-key.json
    SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
    creds = ServiceAccountCredentials.from_json_keyfile_name( 
            'bme280-key.json', SCOPES)
    service = build('sheets', 'v4', http=creds.authorize(Http()))

    # Call the Sheets API, append the next row of sensor data
    # values is the array of rows we are updating, its a single row
    values = [ [ str(datetime.datetime.now()), 
        temperature, pressure, humidity] ]
    body = { 'values': values }
    # call the append API to perform the operation
    result = service.spreadsheets().values().append(
                spreadsheetId=MY_SPREADSHEET_ID, 
                range= MY_SHEET_NAME+'!A1:D1',
                valueInputOption='USER_ENTERED', 
                insertDataOption='INSERT_ROWS',
                body=body).execute()                     

#This function takes the reading from the BME280 sensor and uploads them to the Google Sheet
def main():  
    bme = bme280.Bme280()
    bme.set_mode(bme280.MODE_FORCED)
    tempC, pressure, humidity = bme.get_data()
    pressure = pressure/100.
    print ('Temperature: %f °C' % tempC)
    print ('Pressure: %f hPa' % pressure)
    print ('Humidity: %f %%rH' % humidity)
    
    update_sheet(MY_SHEET_NAME, tempC, pressure, humidity)

if __name__ == '__main__':  
    main()


Once you paste the code, change SpreadsheetID into your Google Sheet File ID, and SheetName into the name of the sheet you want to log the reading into.

At this point everything is ready.

Open the terminal in the folder python-bme280 and run this command:

python bm280-reading.py

If everything went well, you should now see the sensor reading into your google sheet, with the order: Time of reading, temperature, pressure and humidity.

Automate readings:

The bme280-reading.py can be automatically run periodically by using crontab.

Open crontab by using the command crontab -e and add at the end the line:

*/5 * * * * cd /home/pi/python-bme280 && python bme280-reading.py

The */5 part of the command is instructing crontab to run the command every 5 minutes. I recommend reading how to use crontab to select the time interval best suited to your needs. 

Format you data:

The sensor readings are pushed to the sheet you have selected, with each reading being appended to the first row of cells available. Which means you can use Row 1 to label each column.

At this point, you are free to manipulate the data in any way you prefer. For example I am using various formulas to showcase current values, average for the day and day to day comparison in order to quickly monitor the readings from my phone. 

And this is it. Enjoy your new remote sensor.

Example of how the data can be showcased in Google Sheet.
How the data is logged into Google Sheet

About the Author...

Josh Coppola
Josh Coppola

Josh Coppola, born in 1991 in Salerno, developed a passion for animals and nature in general from a young age, with a particular interest in amphibians and reptiles. He moved to London after high school to do a BSc in Business Studies at Cass Business School, which resulted in him having to give up keeping animals for 7 years.

In 2017 he started again to keep caudata, and also picked up an interest in photography, but with very bad results.

“As an objective, I’d like to focus on the breeding in captivity of rare species that are not widespread in the hobby, so we are able to spread them and avoid them disappearing from this hobby forever.”