Canada Post Workers May Strike on Monday October 22. See our blog for updates. Consider FedEx as an alternative.

Raspberry Pi Powered Temperature Logger

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 great and we suspect he will fix the AC quickly, but we figured it would be a good idea to track the temperature.  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:

conn = sqlite3.connect('temp.sqlite3')
cur = conn.cursor()
And we create the table if it does not yet exist:
(date TEXT, hour TEXT, temp_f FLOAT, temp_c FLOAT)''')
Here we connect to the temperature sensor and tell the program how to read it:
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
And now we read the temperature
def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    return lines
def read_temp():   
lines = read_temp_raw()   
while lines[0].strip()[-3:] != 'YES':       
lines = read_temp_raw()   
equals_pos = lines[1].find('t=')   
if equals_pos != -1: 
temp_string = lines[1][equals_pos+2:]       
temp_c = float(temp_string) / 1000.0       
temp_f = temp_c * 9.0 / 5.0 + 32.0       
return temp_c, temp_f
Here we grab the time and temperature and print it to the screen:
while True:       
timenow =        
timedate =  timenow.strftime("%Y-%m-%d")      
timehours = timenow.strftime("%H:%M")       
print timedate, timehours, read_temp()       
temp = read_temp()       
temp_f = temp[1]       
temp_c = temp[0]
And now we write the temperature and time to the database
cur.execute('''INSERT INTO templog (date, hour, temp_f, temp_c) VALUES (?, ?, ?, ?)''',(timedate, timehours, temp_f, temp_c))
Lastly we sleep for 60 seconds before we start all over again:



With that done, our next step is to run the code and log the temperature!  Just type the following:


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! 



Craig LeMoyne
Craig LeMoyne


Leave a comment

Comments will be approved before showing up.