Monitoring Your Home Freezer with a Raspberry Pi

Published on 25 May 2020

Introduction

We have an old freezer in the garage that has a checkered history recently. A few weeks ago, it looked like either it stopped working, or someone flipped a switch intside that stopped it cooling. Some food had to be thrown out, and it was a bit of a massacre. We turned it back on and it seemed to work OK again, but we didn't have a huge amount of confidence, so the obvious solution was to (finally) get a Raspberry Pi, a temperature sensor, and connect it up to the freezer. What we needed though was not just a record of the temperature, but some for of alerting for when the temperature went out above a threshold.

The good thing about doing this is that a Raspberry Pi and sensor can easily cost less than £40 (more though if you need a case and other bits). A small price to pay to avoid food poisoning and wasting a freezer full of food. And you can use the Raspberry Pi for other things when it is not watching your freezer.

The Sensor

I bought a DHT-22 sensor off Amazon, because it would cope with the potential range of temperatures that I was after, and most importantly for me, a search shows that it has been used with Raspberry Pi's before.

pi

Software Requirements

All we need is Python and some modules. There is an Adafruit_DHT module already written, and also one for Twitter which I use to send the notifications. I use a remote session on my laptop with VS Code to give me a bash interface and the ability to write and run the code. You could just use the supplied Python IDE on the Raspberry Pi too.

So installing the modules from bash is pretty easy:

    pip install Adafruit_DHT, Twitter

What you will also need to do, is create a twitter account and sign up for developer access. That is where you will get the Twitter credentials we use. You need to answer some questions, but it took five minutes and was approved instantly.

Connecting the Sensor

A pin guide will show you the pins that are available on the Raspberry Pi to use with the sensor. Mine had three pins:

  • DAT - The data from the sensor itself, which needs to be connected to a GPIO pin
  • VCC - Power, works with either 3v or 5v. I used a 5v pin on the Raspberry Pi
  • GND - Ground. Just connect to an unused ground pin.

DHT22

Older DHT-22 sensors need a breadboard and a 10k Ohm resistor. Mine had that already on a board that the sensor was mounted on.

Writing the code

This was remarkably simply.

    import time,os,Adafruit_DHT,twitter

This will import the modules we need.

    # Sensor details
    DHT_SENSOR = Adafruit_DHT.DHT22
    DHT_PIN = 4

These constants are used to interface with the sensor, and are used when we read the temperature. The number here for DHT_PIN is not the board pin number, but the GPIO number. So GPIO pin 4, is board pin 7 on my Raspberry Pi 4 B. If you connected to a different pin, you will need to adjust that.

    # Twitter details
    TWITTER_CONSUMER_KEY = os.environ['twitter_consumer_key']
    TWITTER_CONSUMER_SECRET = os.environ['twitter_consumer_secret']
    TWITTER_ACCESS_TOKEN_KEY = os.environ['twitter_access_token_key']
    TWITTER_ACCESS_TOKEN_SECRET = os.environ['twitter_access_token_secret']

These read the keys for interfacing with Twitter from the environment variables. You can set these by editing your profile (nano ~/.bash_profile). You may want to reboot after doing so, to just check that they are there OK, and persistent.

api = twitter.Api(consumer_key=TWITTER_CONSUMER_KEY,
consumer_secret=TWITTER_CONSUMER_SECRET,
    access_token_key=TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret=TWITTER_ACCESS_TOKEN_SECRET)

These connect to Twitter using the constants. We will use 'api' later. That is really all we need to do to set up the sensor, twitter, and we are ready to read from the sensor. So next is the code that will loop continuously. In the loop, it will open a .csv file that we log to (if the file is empty, it will write some header information), read from the sensor, write to the log file, and if the temperature is above a specific level, it will send a tweet. It will then close the log file that we opened. There is a maximum of one read per two seconds from the sensor, but we are going to them sleep for two minutes anyway. Given how slowly temperatures change, this could easy be thirty minutes.

    while True:

        #Open the log file
        try:
            f = open('/home/pi/temperature.csv', 'a+')
            if os.stat('/home/pi/temperature.csv').st_size == 0:
                f.write('Date,Time,Temperature,Humidity\r\n') 
        except:
            pass


        hum, temp = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
        
        if hum is not None and temp is not None:
            hum = round(hum,1)
            temp = round(temp,1)
            readDate = time.strftime('%d/%m/%y')
            readTime = time.strftime('%H:%M')

            # Add a line to our log file
            f.write('{0},{1},{2},{3}%\r\n'.format(readDate,readTime,temp,hum))

            # If the temp is > something, post a tweet
            if temp > -10:
                try:
                    status = api.PostUpdate('Freezer alert - {0} - {1} - temperature of {2} C, humidity of {3}%\r\n'.format(readTime,readDate,temp,hum))
                except:
                    print(str(readDate) + ", " + str(readTime) + ", " + "Unable to send tweet.")
            
        else:
            print("Failed to retrieve data from sensor.")

        f.close()

        time.sleep(120)

And that is it. So just subscribe to the Twitter account that you created, and when there is a tweet, you should be notified pretty quickly.

Starting Automatically

You should consider starting the script automatically in case someone knocks the power out, the Raspberry Pi reboots, you get a power cut, or whatever. The easiest way to do that is "crontab -e" and enter something like:

    @reboot /bin/sleep 60 ; /usr/bin/python3 /home/pi/code/freezer.py >> /home/pi/Documents/freezer.log 2>&1

This will run the .py file from the location specified, and also wait 60 seconds before running. This is just to give the Raspberry Pi time to get fully started, connected to the Wifi access point, etc. It will also send any errors to the specified log file.

Installation

Tape the Pi to the side of the freezer, and tape the sensor to the inside. Connect power, and turn on.

Other Suggestions

You can also:

  • Install nginx or apache and write to an HTML file
  • Log the data to DynamoDB
  • Use something like Grafana for a nice graph.

The code also needs a bit more error handling, but that is something I will add over time.

comments powered by Disqus