We just moved to a new office, which has been great, but as the outside temperature reached 30°C the other day, we realized that our air conditioning was not working!
Our landlord is well intentioned but cheap, so who knows when our AC will be fixed. So, we figured it would be a good idea to track the temperature in case we had to prove to him that we regularly saw temperatures over 30°C (86°F).
There are many ways to do this, but we thought it would be most fun to use Python on a Raspberry Pi.
We really like the DS18B20 temperature sensor, as you can communicate with them via I2C. We have several flavours of these sensors, they all work the same: bare sensor, waterproof, and high temp waterproof.
We started with Adafruit's excellent tutorial on the DS18B20 for the Raspberry Pi. There you can learn the basic wiring and how to hook it up to the Pi. We will also use their example code in our program below. This example will work on Raspbian and other similar distributions.
Next, we created a database to log the temperature. There is a great Python library called sqlite3 that allows you to make simple or powerful databases. SQlite is not installed by default on Raspbian, so we need to install it:
sudo apt-get install sqlite3
We also need a few Python libraries for managing time, so install these as well:
sudo pip install python-dateutil
Now that we have all the dependencies installed, we can get to coding. The below code is available for download here.
First we get the required libraries:
import sqlite3
import os
import glob
import time
import dateutil.parser
from datetime import datetime
Now we connect to the database:
time.sleep(60)
With that done, our next step is to run the code and log the temperature! Just type the following:
python readtemp.py
You should see the temperature and time output to the screen, and a new file will appear called temp.sqlite.
Now you can simply connect to your Pi, get the temp.sqlite file, and open it up in a database browser! We prefer to use DB Browser for SQLite, which is a simple and high quality open source tool for viewing and editing databases. Here is a screenshot:
Within DB Browser you can do many things, but if you are comfortable in Excel or similar spreadsheet programs, many find it easiest to just export the data to CSV.
Once you have the CSV, you can plot or do anything you like. Here is a plot of 3 days worth of temperature collection.
You can see that the temperature does not vary much. The X-axis shows time, we did not clean this up but you get the idea!
We hope you enjoyed this post, thank you for visiting our site!