Raspberry Pi fridge monitor

By Russell Barnes. Posted

Make sure your fridge doesn't lose too much heat with a Raspberry Pi-powered monitor and the help of renowned technology hacker and author, Simon Monk

The house is infested with cheese fairies who raid the fridge at all times of day and consume considerable quantities of tasty cheese. In this project, any fridge-door-opening activity will result in a notification email – or, if you prefer, a tweet or Facebook update – telling you the time that the fridge door was opened.

This may seem a somewhat trivial example, but it really serves to show just how easy it is to hook up a sensor that will cause your Raspberry Pi to notify you of events in a variety of ways using the If This Then That framework.

As you’ll see from the below list of required components, this project uses a photoresistor connected to the Raspberry Pi GPIO header using a pair of female-to-female jumper wires.

This tutorial can be found in The MagPi 37

You'll need

Photoresistor (almost any one will work for this project)

2× female-to-female jumper wires

USB Wi-Fi adaptor (unless your fridge has an Ethernet socket nearby)

Detecting Darkness

Unlike an Arduino, for example, a Raspberry Pi does not have analogue inputs that can measure a voltage. It does, however, have digital inputs; if the voltage at a digital input exceeds about 1.65V (half of 3.3V), then the input is read by the Raspberry Pi as HIGH, otherwise it is counted as LOW. So, although you can’t use a photoresistor with a Raspberry Pi to give a measurement of the light level (not without a few extra components anyway), you can use a photoresistor to tell if it’s dark or light.

The digital input pin (GPIO pin 18) has its internal pull-up resistor enabled. So, while the pull-up resistor is trying to pull pin 18 HIGH, the photoresistor will try to pull it low. They are in a of tug-of-war and if the pull-up resistor is winning, the input will be HIGH; if the photoresistor is winning, it will be LOW.

The more light falling on a photoresistor, the lower the resistance (the stronger it pulls pin 18 towards 0V). Typically, a photoresistor will have a resistance of a few hundred to a few thousand ohms when it’s in the light. If you make a photoresistor really dark (say inside a fridge), then its resistance rises to several mega-ohms (millions of ohms). At this point, the built-in pull-up resistor (50 to 100 kilo-ohms) will be easily winning and the input will be HIGH.

If This Then That (IFTTT)

IFTTT is a web service that allows you to set up triggers that then cause an action. For example, you could create an IFTTT ‘Recipe’ that sends you an email (action) whenever someone mentions you on Twitter (trigger). As well as actions and triggers from all sorts of social media and email services, IFTTT can be set up to work with physical events, such as your fridge door opening.

The way this works is that the Raspberry Pi sends a web request to IFTTT as a trigger and then IFTTT performs whatever action you have specified for it. In this case, that is sending an email.

The various channels available to IFTTT often require their own logins, so IFTTT will, from time to time, ask you to enter a user name and password for that channel.

Building the Project

STEP-01 Connect the photoresistor

Connect the two leads of the photoresistor to the female-to-female jumper wires. It does not matter which way around the photoresistor is connected. The other ends of the jumper wires are connected to GND and GPIO 18 of the Raspberry Pi.

Photoresistor

If the photoresistor leads are a bit loose in the jumper wire sockets, bend a little zigzag into them so that they stay firmly in the sockets. If you are worried about the legs of the photoresistor touching each other, you can shorten them with snips.

STEP-02 Start a new recipe in IFTTT

If you don’t have one already, create an account on IFTTT (ifttt.com). Then click on the ‘Create a Recipe’ button.

STEP-03 Create a Maker Channel trigger

Click on the IF part of the new recipe and search for the Maker Channel in the list of channel icons that are shown. Select the only trigger option available (Receive a web request) and enter the text ‘fridge_alert’ into the Event Name field.

STEP-04 Choose an action

Now we come to the THAT part of IFTTT. So, click on Action, choose the Email action channel and then select ‘Send me an email’.

STEP-05 Complete the action fields

You now need to fill in the fields. The ‘subject’ field will become the email subject, while the body field will contain the text of the email. Notice the use of the special names contained between {{ and }}. These are called ‘ingredients’ and allow you to customise the text. In this case, the ‘OccuredAt’ is a timestamp for when the trigger event happened.

STEP-06 Complete the recipe

After you have completed the action, you will return to a summary of the recipe. Click the ‘Create a Recipe’ button to actually create the recipe and make it active.

STEP-07 Find your secret key

Bad things could happen if just anyone were allowed to trigger emails to be sent using IFTTT. So, when the web request is sent from Python to trigger the email, it must be accompanied by a secret key. To find that key, click on the Channels tab at the top of the IFTTT webpage and then find the Maker Channel. In a little while, you are going to need to paste the secret key into your Python program.

 Our If This Than That recipe is complete

Now that the hardware side of the project is complete, and IFTTT has been configured, we need to look at the Python program that will send the web requests to trigger IFTTT.

Download the Python program for this project using the following commands:

$ cd /home/pi
$ git clone https://github.com/simonmonk/pi_magazine.git

This command will actually bring down the code for all the projects in the author’s MagPi series, so if you have already issued this command for one of the earlier articles, change directory to pimagazine and run the following command to update your directory with this project (07fridge_monitor):

$ git pull

How the code works

The Python code for this fridge monitor project is pretty straightforward. If you are interested in how the code works, load it up into a text editor while we go through it.

The first section of code includes all of the libraries you need. This includes the RPi.GPIO library that is needed to interface with the photoresistor and the urllib2 library responsible for sending the web request to IFTTT.

The next section contains variables that are used to configure the program. EVENT must match the text that you specified as the Event Name when you created the trigger. You need to replace the value of the KEY variable with your key that you found in step 7.

The function send_event will be called by the main part of the program when IFTTT needs to be notified. The response from the web request is printed out, just to provide useful information while you are getting the project working.

The main program loop is contained in a try: finally: block, so that the GPIO pins will be tidied up when the program exits. The main loop inside while True: will keep running until you quit the program with CTRL+C. It checks to see if LIGHTPIN is 0, indicating that the fridge door has been opened. When this happens, sendevent is called.

To prevent a whole series of events being sent every time the fridge door is opened, two measures are taken. First, a while loop does nothing while the door is still open, to prevent repeat triggering every time around the outer loop. Second, when the door is finally shut, the program sleeps for a minute to prevent any further triggerings within that minute.

Using your fridge monitor

If you want to make your project a bit more permanent, you could tape the photoresistor to the top-inside surface of the fridge, rather than just letting it dangle like we did.

Before running the Python program, you can test out your recipe from the command line using the wget utility. Type the following command into LXTerminal. You will need to substitute your secret key.

$ curl https://maker.ifttt.com/trigger/fridge_alert/with/key/cyR3vPNFlP9K32W4NZB9cd

You’ll then see the message, ‘Congratulations! You’ve fired the fridge_alert event’.

Check your inbox and you should see an email from IFTTT. If anything went wrong, you should get an error message in place of the congratulations. You can also see the logs for your recipe on the IFTTT website by selecting the recipe and then clicking the icon that looks like a series of bullet points.

Start the fridge monitor program with the following command:

sudo python fridge_monitor.py

IFTTT is a very powerful system, so you might like to experiment by editing the recipe and changing the action so that it tweets or changes your Facebook status instead of sending an email.

Having a keyboard, mouse, and monitor attached to your fridge-mounted Pi is fine during testing, but really, it would be better to have the fridge monitor program start automatically when the Raspberry Pi first starts up. To do this, run the following command to make the program executable.

sudo chmod +x fridge_monitor.py

Then, edit the file /etc/rc.local with the command:

$ sudo nano /etc/rc.local

Add the following line after the first block of comment lines that begin with #.

$ sudo /home/pi/pi_magazine/07_fridge_monitor/fridge_monitor.py &

Restart your Raspberry Pi and this time the fridge monitor program should start up automatically.

Code listing

import time
import RPi.GPIO as GPIO
import urllib2

LIGHT_PIN = 18   # photoresistor pin
EVENT = ‘fridge_alert’
BASE_URL = ‘https://maker.ifttt.com/trigger/’
KEY = ‘cyR3vPNFlP9K32W4NZB9cd’

# Configure the GPIO pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(LIGHT_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def send_event():
    response = urllib2.urlopen(
BASE_URL + EVENT + ‘/with/key/’ + KEY)
    print(response.read())

try:
    while True:
        if GPIO.input(LIGHT_PIN) == 0:
            # Its light (door open)
            send_event()
            # Do nothing until the doior is closed again
            while GPIO.input(LIGHT_PIN) == 0:
                time.sleep(0.1)
            # Do nothing for a further minute anyway
            print(“Wait a minute”)
            time.sleep(60)
            print(“Monitoring again”)

finally:
    print(‘Cleaning up GPIO’)
    GPIO.cleanup()

 The fridge monitor, protecting your fridge

From The MagPi store

Subscribe

Subscribe to the newsletter

Get every issue delivered directly to your inbox and keep up to date with the latest news, offers, events, and more.