How to control the temperature of your terrarium remotely - The Cheap Way

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 prevents some of the worrying with leaving the animals for long period of time for holidays.

In the article How to control the temperature of your terrarium room remotely we explored how to use a Raspberry Pi and a BME280 sensor to monitor temperature, humidity and atmospheric pressure of the room where we keep our animals. Using a Raspberry Pi for this type of projects has the advantage of being very simple, and it can be expanded to have multiple sensors and functions which makes it ideal to monitor a Rack System with multiple aquariums/terrarium, but the disadvantage is the cost. Even though it is not expensive, the cost of a Raspberry Pi starts from £15, and then you need to add the cost of a Micro SD and sensors which, depending on your setup, can bring the cost of a sensor above £25.

In this tutorial, we will explore an alternative to the Raspberry Pi, which is more limited but much less expensive and it will allow us to monitor an aquarium/terrarium for around £5 by using an ESP8266 microchip and a waterproof DS18B20 sensor which will log the temperature at fixed intervals on Google Sheet.

What is an ESP8266:

The ESP8266 is a low-cost Wi-Fi microchip produced by the company Espressif Systems which has become very popular due to the low cost and compatibility with the Arduino IDE, which allows us to programme it as if it is an Arduino with integrated Wi-Fi. Given the popularity of this chip, various companies have produced boards which contain this chip and that simplify the process as these boards contain all the necessary components to connect the chip to a PC and programme it like an Arduino.

In my case, I have used a Wemos D1 Mini that contains the ESP8266-12F, but this tutorial should be compatible with any board containing an ESP8266.

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 electronics dedicated websites, so shop around for the best prices.

  • Bare minimum cmponents:
    • Wemos D1 Mini (£1/5): This can be found for under £2 on Aliexpress or around £5 on Amazon.
    • DS18B20 (£1/2): Like above, the price can vary considerably depending on where you buy it. IMPORTANT: Buy the waterproof version which can be used in aquariums and humid terrariums.
    • 4.7kOhm Resistor (£0.10): The DS18B20 sensor needs a 4.7kOhm resistor. These are very cheap and sometimes included in the price when buying the sensors.
    • Power supply (£5): You will need a MicroUSB cable and a power supply. You can use an old phone charger or, if you don’t have one, you’ll need to buy it. If you want, you can even power this board with a battery or solar panel.

Connection:

Connect the DS18B20, Resistor and Wemos D1 Mini like in the diagram below. Keep in mind, the resistor needs to connect the 3.3V Pin with the Data Pin.

Wemos D1 Sketch

Arduino IDE Configuration:

Let’s start with configuring the Arduino IDE so that it recognises our Wemos D1.

  1. Download the Arduino IDE here: https://www.arduino.cc/en/main/software
  2. Go to File > Preferences
  3. Paste http://arduino.esp8266.com/stable/package_esp8266com_index.json in Additional Boards Manager URLs and click OK
  4. Go to Tools > Boards: > Boards Manager…
  5. Find the esp8266 (it should be at the end) and click on Install
  6. Go back to Tools > Boards: and select your board. In my case I selected LOLIN(WEMOS) D1 R2 & mini

Once we have configured the Wemos D1 we can take care of the libraries that we will need (some of these could already be installed).

  1. Go to Sketch > Include Library > Manage Libraries
  2. Install DallasTemperature
  3. Install OneWire
  4. Install HTTPSRedirect manually
To install HTTPSRedirect manually:
  1. Download this repository on your PC
  2. Move the folder HTTPSRedirect in the folder containing the Arduino IDE libraries. Usually, you can find it in Documents > Arduino > Libreries

Google Sheet Configuration:

The sensor reading will be logged at regular intervals on a Google Sheet. This will allow us to use Google Sheet both as a database to archive the data, and as an interactive Dashboard for the readings.

  1. Let’s start by creating a new Google Sheet and change the privacy settings by going to Share > Get Link and change setting to “Anyone with link can edit”
  2. Change the name of the sheet in which you want to save the temperatures, for example to Temperature

Creating the Google App Script:

When the Wemos D1 completes a sensor reading, this will be sent to a Google App Script, which will then log the reading on the Google Sheet.

In order to configure this small piece of Javascript we will need:

  • Google Sheet ID
  • Name of the sheet in which we want to log the readings
In order to create the script, click on Tools > Script. A new window will open. Choose a name for the script and paste the following code with the necessary edits in the first two lines of the code.

var SS = SpreadsheetApp.openById('~~Sheet ID~~');    //Your Goofle SHeet ID
var sheet = SS.getSheetByName('~~Sheet Name~~');      // Insert the name of the sheet in which you want to log the temperatures
var str = "";

function doPost(e) {

  var parsedData;
  var result = {};
  
  try { 
    parsedData = JSON.parse(e.postData.contents);
  } 
  catch(f){
    return ContentService.createTextOutput("Error in parsing request body: " + f.message);
  }
   
  if (parsedData !== undefined){
    
    var flag = parsedData.format;
    
    if (flag === undefined){
      flag = 0;
    }
    var dateTime = new Date();
    sheet.appendRow([dateTime,parsedData]);

}
}

Once you have done the edits, click on Publish > Deploy as Web App and in the section Who has access to the app: select Anyone, even anonymous and click OK.

At this point, the script will be published as a Web App, and you should see a link starting with script.google.com. Save this link as we will need it later.

Programme the Wemos D1 Mini:

This is the last step. In order to complete the coding of the Wemos D1 we will need:

  • Google Apps Script ID
  • Wi-Fi Name
  • Wi-Fi Password 

You can find the Google App Script ID in the link that you just saved. (https://script.google.com/macros/s/~~~Google Apps Script~~~/exec)

 
#include "TickTwo.h"
#include "ESP8266WiFi.h"
#include "HTTPSRedirect.h"
#include "DebugMacros.h"
#include "OneWire.h"
#include "DallasTemperature.h"

// Data wire is plugged into port D2 on the ESP8266
#define ONE_WIRE_BUS D2

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);


float m = 30; // intervall in minutes
float in = m * 60000;
void push();
TickTwo timer(push, in );

float t;
String sheetTemp = "";

const char* ssid = "WiFi Name"; //WiFi Name
const char* password = "WiFi Password"; //WiFi Password
const char* deviceName = "Device name"; //Device name

const char* host = "script.google.com";
const char *GScriptId = "scipt ID"; //scipt ID
const int httpsPort = 443;
const char* fingerprint = "";

// Write to Google Spreadsheet
String url = String("/macros/s/") + GScriptId + "/exec?";

String payload = "";

HTTPSRedirect* client = nullptr;

void setup() {
  Serial.begin(115200);
  timer.start();
  sensors.begin();
  Serial.println(in);
  Serial.flush();

  Serial.println();
  Serial.print("Connecting to wifi: ");
  Serial.println(ssid);
  Serial.flush();
  WiFi.mode(WIFI_STA);
  WiFi.hostname(deviceName);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  client = new HTTPSRedirect(httpsPort);
  client->setInsecure();
  client->setPrintResponseBody(true);
  client->setContentTypeHeader("application/json");

  Serial.print("Connecting to ");
  Serial.println(host);

  bool flag = false;
  for (int i = 0; i < 5; i++) {
    int retval = client->connect(host, httpsPort);
    if (retval == 1) {
      flag = true;
      break;
    }
    else
      Serial.println("Connection failed. Retrying...");
  }

  if (!flag) {
    Serial.print("Could not connect to server: ");
    Serial.println(host);
    Serial.println("Exiting...");
    return;
  }

  delete client;
  client = nullptr;

}

void loop() {
  timer.update();
}

void push() {
  Serial.println("Start of Push Function");

  Serial.print("Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");
  float t = sensors.getTempCByIndex(0);
  if (t != DEVICE_DISCONNECTED_C)
  {
    Serial.print("Temperature for the device is: ");
    Serial.println(t);
  }
  else
  {
    Serial.println("Error: Could not read temperature data");
  }
  sheetTemp = String(t);

  payload = sheetTemp;

  static int error_count = 0;
  static int connect_count = 0;
  const unsigned int MAX_CONNECT = 20;
  static bool flag = false;

  if (!flag) {
    client = new HTTPSRedirect(httpsPort);
    client->setInsecure();
    flag = true;
    client->setPrintResponseBody(true);
    client->setContentTypeHeader("application/json");
  }


  if (client != nullptr) {
    if (!client->connected()) {
      client->connect(host, httpsPort);
    }
  }
  else {
    DPRINTLN("Error creating client object!");
    error_count = 5;
  }

  if (connect_count > MAX_CONNECT) {
    connect_count = 0;
    flag = false;
    delete client;
  }

  if (client->POST(url, host, payload, false)) {
    Serial.println("Uploading temperature to Google Sheet");
  }
  else {
    ++error_count;
    DPRINT("Error-count while connecting: ");
    DPRINTLN(error_count);
  }

  if (error_count > 3) {
    Serial.println("Halting processor...");
    delete client;
    client = nullptr;
    Serial.flush();
  }
  delete client;
  client = nullptr;
  flag = false;
  Serial.println("End of Push Function");
}

 

Data Formatting:

Wemos Dashboard
Example of how the data can be showcased in Google Sheet.

The sensor readings are sent to the sheet you have selected, with each reading being added to the first available empty row, which means we can use Row 1 to label each column.

The advantage of using Google Sheets is that on top of being free, it allows us to easily manipulate the data and create an interface that can be read by a smartphone.

This is an example of my setup, which allows me to see the Min, Max and Average temperatures for various periods of time, a graph of the temperature and a section that showcases the last 3 observations done.

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.”