Showing posts with label electronics. Show all posts
Showing posts with label electronics. Show all posts

Sunday, August 13, 2017

Reading Temperature Sensors and Displaying Data Using I2C Protocol and the Raspberry Pi

For this project, I am going to be using LM57A temperature sensors to measure the temperature inside my network and server cabinets, and communicate that back to the Raspberry Pi using I2C protocol.  I am then going to use that data to control cooling fans inside the cabinet.  I am also going to output the data to a 7-segment display, again using I2C protocol, and store the data in a log file so that it can be analyzed later.  Lastly I am going to have the Raspberry Pi send me an email if the temperature continues to rise and reaches a second threshold.  I am aware that this project is very specific to my own needs, as not too many people have network and server cabinets in their houses, but I believe that the techniques and methods used in this project will be very useful to others trying to do similar things, especially using I2C protocol to send and receive data.  I am going to break this project into several segments for easy reference.  They are as follows: using the LM57A temperature sensor, setting up and using I2C protocol with the Raspberry Pi, using the Adafruit I2C Backpack with a 7-segment display, controlling fans using the Raspberry Pi, and final Python script.


Using the LM57A Temperature Sensor


I looked at using several different temperature sensors for this project, and settled on the LM75A Temperature Sensor High-speed 12C Interface Development Board Module.  I chose the LM75A for several reasons, including cost, on-board analog-to-digital conversion, I2C interface, and ability to hard-wire the I2C address into the chip.  For those of you who would rather not read through my personal experience with the LM57A, here is a link to the data sheet.  For less than $3 US, this is an amazing little device, and has way more features than we will be using here.  You can actually set temperature thresholds on the chip itself, and use it as a thermostat without even involving the Pi, but enough about features we won't be using. I'll try to focus on the features that make this the perfect temperature sensor for this project.

The most important feature of this sensor, is that it has built-in analog-to-digital conversion, so it can send data directly to the Raspberry Pi, which is limited in only having digital GPIO pins.  I was also looking for something with an I2C interface, which I will cover more in-depth in the next section.  The nice thing about I2C is that you can connect multiple devices on the same 2-wire serial connection.  In order for this to work, each device must have a unique 7-bit address, which is where another feature of the LM57A comes in handy.  You can set the last three bits of the address by connecting the solder pads for A0 through A2 on the back of the PCB.  The first four bits of the address are '1001', and are hardwired inside the chip, so that gives us the option to use the addresses '1001000' through '1001111', which are the Hex addresses 0x48 through 0x4F.  With these 8 potential addresses we can hook up 8 of these sensors on one I2C circuit.  In the picture above you can see that the configuration of the pads makes it easy to set the address using a simple solder bridge.  The chip on the left is unset.  The chip in the middle is set to 1001001 (0x49) and the chip on the left is set to 1001011 (0x4B).  These registers must be set, and should not be left floating during use.

One last feature of the LM57A that adds a little bit of convenience to this project is that the input voltage can range from 2.8V to 5.5V.   This means that we can power these little units with either the 3.3V or 5V rail on the Pi.  If it was just the sensors the 3.3V rail would suffice, but since we are also going to be powering a 7-segment LED from the same source, and the 3.3V on the Pi is limited in the amount of current it can supply, we'll go ahead and use the 5V supply on the Pi, which is wired directly to the USB power source, and is only limited by the power supply that you are using for your Pi.

Setting-up and Using I2C Protocol with the Raspberry Pi


The image above is borrowed from
https://www.lammertbies.nl/comm/info/I2C-bus.html
I2C is a very simple, easy to use, serial communication protocol developed in the 1980s, primarily for use in intra-board communications.  It is also commonly referred to as I2C or IIC.  So why use I2C protocol?  Three words: "Conserve GPIO pins."  I2C only uses two wires for serial communication, and can use multiple devices on those same two wires.  It does this by using a master and slave configuration, where there is only one master device, and all other devices on the circuit act as slaves.  Communication can only be initiated by the master in order to eliminate the possibility of more than one device trying to communicate at a time.  It is obvious that this saves us a few pins by consolidating all the temperature sensors onto one serial input, but the real savings comes when using I2C to communicate with the 7-segment LED display.  If we used a traditional 4-digit 7-segment display we would be using up a whopping 12 GPIO pins for the display alone!  Considering there are only 26 usable GPIO pins on the Pi 2B and 3B, and I have already used up several of them on previous projects, this project would come close to maxing out this Pi's available pins if we did not use I2C.  Since we are using I2C, two pins for serial communication and two pins to control the cooling fans is all we will need for this entire project.

Now that I've discussed why I am using I2C, let's get to how to set up I2C on the Raspberry Pi.  Adafruit has a nice tutorial (link), but unfortunately it is out of date and doesn't work with the latest versions of Raspbian.  So, here is my own updated tutorial on enabling and testing I2C.

By default I2C is not enabled, so first we need to enable it.  This can be done the easy way using raspi-config, options 5, then option P5, but I prefer to understand what is happening under the hood, so let's go over how to quickly do this via the CLI.  First we need to edit the /etc/modules file to tell the Pi to load the I2C kernel module on boot.  Open /etc/modules with a text editor and add the following two lines to the end of the file:

i2c-bcm2708
i2c-dev

Next we need to edit the /boot/config.txt file.  Open /boot/config.txt with a text editor and uncomment the following line by removing the pound sign:

#dtparam=i2c_arm=on

And that's it.  I2C is now enabled.  Next we want to install the python module and command line utility that will enable us to utilize I2C.

sudo apt-get install python-smbus
sudo apt-get install i2c-tools

OK, we are ready to test this out.  Hookup one of the LM57A sensors to the Pi.  The I2C-1 SDA and SCL pins are on GPIO pins 3 and 5 respectively, and we will also need to to use a 3.3V and Ground pin to power the sensor.  To test to see if the Pi can see the sensor use the command i2cdetect -y 1, where the 1 refers to the specific I2C bus we are using.  On older models of the Pi this will be 0 instead of 1.


In the image to the left, you can see that the Pi has detected the temperature sensor with an address of 0x48.  On this particular sensor I have set A0, A1, and A2 to 0, so the full address should be 1001000 as explained above.  If we convert this to hexadecimal we get the number 48, which means everything is working as expected.  Next lets see if we can pull a temperature reading from the sensor.  For this we use the command i2cget -y 1 0x48, where 1 is the name of the I2C bus, and 0x48 is the address of the device we are polling.  As you can see, the sensor returned a value of 0x1c.  At first glance this may not seem like a usable temperature value, but lets think about this for a second.  First, this is a hex value, but most of us think in decimal.  If we convert 0x1c to decimal we get 28.  If you are in the United States like I am, we are also not used to thinking in Celsius, so we need to convert 28 degrees C to Fahrenheit, and we get 82.4 degrees F.  It's a warm day and I have the shop door open, so I am willing to accept that as an accurate reading.


So, now we can detect an I2C slave device, and take a reading from it, but the whole point of using I2C is that we can hook up multiple devices to the same two-wire serial bus. Since we only have one set of pins on the Pi to connect to the bus we are going to have to whip up a quick circuit board to connect multiple devices.  This can be done by soldering some pin headers on a circuit board and using solder bridges to connect the pins.  Be sure to use a multi-meter to make sure all the rows are properly bridged, and that none of the rows are bridged together.



Using the Adafruit I2C Backpack for 7-Segment Display


Adafruit makes a very handy little device called the backpack that takes I2C in and uses that to drive an LCD array.  For this project we are using the model HT16K33 that works with a 4-digit 7-segment display.  As always, Adafruit provides a nice tutorial (Here and Here) for getting this thing working, so I don't feel the need to go into great detail, but I'll outline the general process and we'll test it out.

First we need to solder the backpack onto the 7-segment LED display.  This is pretty self-explanatory, just be sure not to solder it on upside-down.  There is a stencil on the backpack that matches the display to help with orientation.  Next we need to solder on the pin headers for the two serial wires plus Vcc and GND.  With the male pin headers sticking out the back of the backpack, we can stick the backpack directly on the homemade I2C bus we just created.

To get this thing working I downloaded the software recommended by Adafruit:

sudo apt-get install -y git build-essential python-dev python-smbus python-imaging python-pip  python-pil

and then:


git clone https://github.com/adafruit/Adafruit_Python_LED_Backpack.git

cd Adafruit_Python_LED_Backpack

sudo python setup.py install

Once that is done, inside the /Adafruit_Python_LED_Backpack folder you just created, there is a folder called /examples which contains well documented code that will give you a thorough understanding of how to use these modules in Python.  If only every hardware maker was as thorough as Adafruit we could save so much time.  You can run these example scripts to make sure that your Backpack and 7-segment display are working correctly.


One last trick I'd like to mention regarding the 7-segment display being used for this project is that while this unit can only display numbers, it is able to display hexadecimal numbers, which gives it the ability to display the letters a through f.  I wanted to be able to display which area each temperature correlated to, so I needed to be able to write the strings "Cab1", "Cab2", and "Base" for basement.  Luckily the only letter in those labels that is not able to be represented in hex is "s".  Luckily there is no difference between 5 and S on a 7-segment display, so that is how I was able to make it display the necessary strings.

Controlling Fans Using the Raspberry Pi


Turning on the cooling fans for the network cabinets is the easy part.  Since I am using 12V fans they will need to be powered by an external power source and controlled by a relay wired to a GPIO pin.  If you are using a relay board similar to the one I am using (JBtek 4 Channel DC 5V Relay Module), then there is no additional circuitry required between the Pi and the board because the relay board already contains a resistor and an opto-isolator to prevent too much current from being drawn from the GPIO pin.  Just be sure to power the relay board with one of your 5V pins wired to Vcc on the board.

If you have followed any of my previous projects, you may know that I have already set-up a 12V (30 amp) power supply, a DC fuse panel, and a relay board for use with my automated sprinklers, so there was nothing for me to purchase other than the fans.  I wired the 12V power supply, through the fuse panel, to a switch to allow me to turn off the power to both sets of fans.  I wired the output of the switch to two relays so that I could control the fans in the two cabinets separately.  From the relays I ran 16 awg wire to the top of each cabinet where the fans would be mounted.  The fans I purchased had old IDE-style power connectors.  I like to keep things modular, so in order to make replacing the fans easy in the future, I cut some power connectors off of an old PSU, and soldered them onto the ends of the 16 awg wires.

Final Python Script


I glossed over using I2C with Python earlier in this post because I'm doing my best to keep these posts as short as possible while still including as much information as possible.  Below I have pasted the entire Python script for this project so that anyone that would like to use the script can copy and paste it.  In addition I have done my best to thoroughly comment the script, so that anyone with a basic understanding of Python syntax should be able to follow along and see exactly how I used Python to send and receive data on the I2C bus.  If anyone has trouble understanding the code, or if you have problems adapting the code to your own project, feel free to leave questions in the comment section below.

Of course, I've edited out my email addresses and password in the code, so if you are going to copy&paste it, be sure to substitute in your own email addresses and the password for the sending email account.



#!/usr/bin/env python

###############################################################
#                                                             #
# i2ctemp2-0.py                                               #
# written by James Campbell                                   #
# July 2017                                                   #
#                                                             #
# Monitor temperatures of network and server cabinets         #
# Display temperatures and time on 7-segment display          #
# If temperatures reach preset threshold then turn on fans    #
# If temperatures reach second threshold then send email      #
# Store temperatures to log file                              #
#                                                             #
###############################################################


import time
import smbus  # lets us access the i2c bus
from Adafruit_LED_Backpack import SevenSegment # used to control 7-segment display
import RPi.GPIO as GPIO  # used to read/write to GPIO pins
import datetime
import smtplib  #used to send email
from email.mime.text import MIMEText  #used to compose email


CAB_1_TEMP = 0x48 # I2C address for Cab 1 temp sensor
CAB_2_TEMP = 0x49 # I2C address for Cab 2 temp sensor
BASEMENT_TEMP = 0x4B # I2C address for basement temp sensor
DISPLAY = 0x70 # I2C address for 7-seg display
BUS_NUM = 1 # 1 is the I2C bus (board pins 3 and 5)
PAUSE_TIME = 3 # the number of seconds to pause on each display
FAN1_PIN = 13 # GPIO Pin to control fan relay for Cab 1
FAN2_PIN = 19 # GPIO Pin to control fan relay for Cab 2
FAN_THRESHOLD = 90 # the temperature threshold (F) for turning on fans
EMAIL_THRESHOLD = 95 # the temperature threshold (F) for sending an email
GMAIL_USER = 'youremail@gmail.com' # email account used to send email
GMAIL_PASS = 'yourpassword' # password for email account used to send email
SENT_FROM = GMAIL_USER
SEND_TO = 'email1@email.com, email2@email.com' # email recipient for alerts
FAN1_RUNNING = False
FAN2_RUNNING = False
EMAIL_TIMER_1 = 0
EMAIL_TIMER_2 = 0
EMAIL_TIMER_B = 0
# FAN_THRESHOLD = 50 # Uncomment this line to test the fans
# EMAIL_THRESHOLD = 50 # Uncomment this line to test the email




def CtoF( Ctemp ):
        return((Ctemp*9.0/5.0)+32) # this line converts the Celcius temperature passed
                                   # to the funtion to Fahrenheit and returns it.

def GET_TEMPS():
        global Ftemp1
        global Ftemp2
        global FtempB

 # below is an example of how to read data from an I2C bus
 # where "bus" has already been defined in the main program
 # using "bus = smbus.SMBus(BUS_NUM)".  This will return 1 byte.
        Ctemp1 = bus.read_byte(CAB_1_TEMP)
        Ctemp2 = bus.read_byte(CAB_2_TEMP)
        CtempB = bus.read_byte(BASEMENT_TEMP)

 # the lines below use the CtoF() Function defined above to 
 # convert Celcius to Fahrenheit
        Ftemp1 = CtoF(Ctemp1)
        Ftemp2 = CtoF(Ctemp2)
        FtempB = CtoF(CtempB)

        # the below is just for troubleshooting
        print ('The follwoing temperatures have been read')
        print '%d, %d, and %d' % (Ftemp1, Ftemp2, FtempB)


def FAN_CHECK():  # This function compares cabinet temps to
                  # thresholds and turns the fan on or off.
        global FAN1_RUNNING
        global FAN2_RUNNING

        if FAN1_RUNNING:
                if Ftemp1 < (FAN_THRESHOLD - 3):
                        GPIO.output(FAN1_PIN, 1)
                        FAN1_RUNNING = False
        else:
                if Ftemp1 > FAN_THRESHOLD:
                        GPIO.output(FAN1_PIN, 0)
                        FAN1_RUNNING = True

        if FAN2_RUNNING:
                if Ftemp2 < (FAN_THRESHOLD - 3):
                        GPIO.output (FAN2_PIN, 1)
                        FAN2_RUNNING = False
        else:
                if Ftemp2 > FAN_THRESHOLD:
                        GPIO.output (FAN2_PIN, 0)
                        FAN2_TIMER_RUNNING = True

        print ('fan check') # for troubleshooting only


def DISPLAY_TEMP( temp, cab_num ): # in this function we will write data
                                   # to the I2C Backpack 7-segment display
                                   # The value for "display" has already been
                                   # set in the main program to refer to the
                                   # bus and address for the 7-seg display

        display.clear() # This clears the display.  If this is not done, any
                        # data that is not overwritten will remain. The display
                        # will not actually clear until .write_display() is called

        display.set_colon(False) # This uses a boolean value to specify if the
                                 # colon is displayed, as in a digital clock

        display.print_hex(cab_num) # This is how you display a hex number on
                                   # the display

        display.write_display() # Once whatever is going to be displayed is set
                                # This line actually sends it to the display

        print ('displaying %s' % hex(cab_num)) # for troubleshooting only

        time.sleep(PAUSE_TIME/2) # This line pauses before changing the display

        display.clear() # Just like above, this line clears the display

        display.print_float(temp, decimal_digits=1) # this line displays the value
                                                    # temp with one digit after
                                                    # the decimal point

        display.write_display() # Just like above, this line actually sends the
                                # data to the display

        print 'displaying temp' # for troubleshooting only

        time.sleep(PAUSE_TIME) # This line pauses before changing the display


def DISPLAY_CLOCK(): # This function will also write to the 7-segment display
                     # but this time instead of cabinet and temperature
                     # it will display the current time.  This will also show you
                     # how to write each specific digit seperately

 # Below is one of the two ways we will use in this script to get the
 # current time.
        now = datetime.datetime.now()
        hour = now.hour
        minute = now.minute

        if hour > 12:
                hour = hour - 12 # This converts 24 hour time to 12 hour time

        display.clear() # Just like above this will clear the display.
 
 # Below we are setting the digits one at a time.  They are numbered 
 # 0 through 3, with 0 starting on the left and 3 ending on the right.

        if (hour / 10) > 0: # These two lines keep 6:00 from showing up as 06:00
                display.set_digit(0, int(hour / 10))

        display.set_digit(1, hour % 10) # this uses modulo to set the second digit
                                        # for hour

        display.set_digit(2, int(minute / 10)) # this line sets the first digit for
                                               # minute by dividing minutes by 10 and
                                               # dropping the remainder

        display.set_digit(3, minute % 10) # this uses modulo to set the second
                                          # digit for minute

        display.set_colon(True) # This line turns on the colon on the display

        display.write_display() # As before, this line actually sends the data to
                                # the 7-seg display

        print 'displaying time' # for troubleshooting only

        time.sleep(PAUSE_TIME) # This line pauses before changing the display again


def SEND_EMAIL ( location, temperature ): # This function sends an email

        timestamp = time.strftime("%m-%d-%y %H:%M:%S")
        subject = '%s Temperature Too High' % (location) + timestamp
        body = 'The temperature in %s is %d degrees.' % (location, temperature)

        msg = MIMEText(body)
        msg['From'] = SENT_FROM
        msg['To'] = SEND_TO
        msg['Subject'] = subject

        try:
                server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
                server.ehlo()
                server.login(GMAIL_USER, GMAIL_PASS)
  server.sendmail(SENT_FROM, SEND_TO, msg.as_string())
  server.close()

                print 'email sent' # for troubleshooting only
        except:
                print 'email atempted and failed' # for troubleshooting only


def EMAIL_CHECK ():
 # This function decides if an email should be sent, and calls SEND_EMAIL() if so.
 # I don't want to spam myself with emails, so the two conditions for emailing
 # are that the temperature is above the threashold, and an email has not been
 # sent in the last 15 minutes
 
        global EMAIL_THRESHOLD
        global EMAIL_TIMER_1
        global EMAIL_TIMER_2
        global EMAIL_TIMER_B

        print 'email check' # for troubleshooting only
  
        if Ftemp1 > EMAIL_THRESHOLD and time.time() > (EMAIL_TIMER_1 + 900):
             SEND_EMAIL ('Network_cabinet_1', Ftemp1)
             EMAIL_TIMER_1 = time.time() #reset email timer
             print 'ending email for cab1' # for troubleshooting only
   
        if Ftemp2 > EMAIL_THRESHOLD and time.time() > (EMAIL_TIMER_2 + 900):
             SEND_EMAIL ('Server_cabinet_2', Ftemp2)
             EMAIL_TIMER_2 = time.time()
             print 'sending email for cab2' # for troubleshooting only
   
        if FtempB > EMAIL_THRESHOLD and time.time() > (EMAIL_TIMER_B + 900):
             SEND_EMAIL ('Basement', FtempB)
             EMAIL_TIMER_B = time.time()
             print 'sending email for basement' # for troubleshooting only


def WRITE_TO_FILE():
        print 'writing to file' # for troubleshooting only
        timestamp = time.strftime("%y-%m-%d %H:%M:%S") # the is the second way we
                                                       # have used in this script
                                                       # to get the current date/time

        f=open('/mnt/usb/temperature.txt', 'a') # this opens a file for writing.
                                                # the 'a' means append, which will 
                                                # add anything written to the end
                                                # of the file.

        # The line below writes to the file we are appending
        f.write('%s cab1 %d cab2 %d basement %d\n' % (timestamp, Ftemp1, Ftemp2, FtempB))
        f.close() # This closes the file we just appended.



# Begining of Program

bus = smbus.SMBus(BUS_NUM) # sets the variable bus to refer to I2C bus 1

# The line below sets the variable display to refer to our specific
# 7-segment display by address and bus number.
display = SevenSegment.SevenSegment(address=DISPLAY, busnum=BUS_NUM)

GPIO.setwarnings(False) # turns off GPIO warnings to terminal
GPIO.setmode(GPIO.BCM)  # sets mode for GPIO pins to BCM
GPIO.setup(FAN1_PIN, GPIO.OUT)  # sets relay 1 control pin as output
GPIO.setup(FAN2_PIN, GPIO.OUT)  # sets relay 2 control pin as output

GPIO.output(FAN1_PIN, 1)  # sets relay 1 control pin to high (relay open)
GPIO.output(FAN2_PIN, 1)  # sets relay 2 control pin to high (relay open)

display.begin()  # initializes 7-segment display

while True:  # infinite loop which will run the functions listed below
      # in that order and then repeat
        GET_TEMPS()
        FAN_CHECK()
        EMAIL_CHECK()

 # For the three lines below, the hex value is how I am displaying the
 # label strings to the seven segment display for cab1, cab2, and basement.
        DISPLAY_TEMP( Ftemp1, 0xCAB1 )
        DISPLAY_TEMP( Ftemp2, 0xCAB2 )
        DISPLAY_TEMP( FtempB, 0xBA5E )

        DISPLAY_CLOCK()
        WRITE_TO_FILE()


Final Result


So we put together the hardware and the software, and we end up with a functional device.  Here is the result of the project.  When the temperature in the cabinets rises above 90 degrees the fans will turn on.  They will stay on until the temperature drops back below 88.  If the temperature continues to rise above 95 degrees the device will email me with the current temperatures.  All temperatures are recorded in a log file along with a time-stamp so that I can review the temperature data at any time.






Sunday, July 9, 2017

Watering the Garden with Raspberry Pi

If you've ever planted a garden or grass seed in the spring, you know that watering can be a time consuming task, and going out of town for a weekend can be disastrous for your new plants if the weather is hot and no one is around to water them.  More importantly, I just like to build things, so why not scratch that building itch and create an automated hose bib that can be scheduled to turn on and off using a Raspberry Pi?

My original approach to this project involved a watering system located near the garden, but I ran into several complications during the design phase.  The first issue arose trying to power the Pi as well as the electronic solenoid valve that would control the water flow.  Running wires across the back yard was not an ideal solution, and battery power was going to require frequent recharging.  I was also going to have to find a way to protect the electronics from the sun's UV rays as well as moisture, while at the same time allowing enough air-flow to let heat escape.  It occurred to me that locating all of the electronics inside the house and using them to control a hose bib on the side of the house solved both of these issues, and also added the flexibility to allow me to change the location of my automatic sprinklers or drip-watering-systems whenever necessary.

With this basic concept in mind, I broke the project into three segments: electronic hardware, plumbing hardware, and control software.  For the electronic hardware, I would need to be able to switch on and off a 12V fused power source that would supply an electric solenoid valve that would control the water.  This could easily be done by controlling a relay with a GPIO pin on the Pi.  For the plumbing hardware, I would need to tap into my water line and run it through the electric solenoid valve, and from there outside to a hose bib.  I would also need to be sure to include a check valve to prevent the back-flow of water from the outside, and there would need to be a way to drain any outdoor pipes to prevent freezing in the winter.  The control software would be the easiest.  All I needed was a short start-up script to set-up the GPIO pin, and then the timing of opening and closing the valve could be done with cron jobs.  With a plan in place it was time to get building.

Electronic Hardware

For this project I purchased a 12V / 3amp normally-closed brass solenoid valve to control the water flow.  You can buy a plastic one cheaper, but I had reservations about connecting a plastic water valve to my plumbing.  Basically all I needed to do was to connect a GPIO pin from the Pi to a relay that could then switch on/off the 12V power supply to the valve.  I went with a 4-channel relay module since I already had plans for future projects that would require additional relays.  I had a 12V / 30 amp power supply from previous projects on hand, which will provide more than enough current for this project, as well as anything I might need it for in the future.  The only thing left to plan was a fuse for the power to the valve.  For most people a simple in-line fuse holder would solve this problem, but I just so happened to have an old DC fuse panel lying around looking for a job to do, so I put it to use.  Here is the schematic for the final design:


In the above schematic I also drew in the relay board.  Obviously if you use the same relay board that I did, you don't need to build any of this, but I wanted to include it so that anyone using a different relay could adapt the circuit to their own needs.

Regarding the switches, I added the first switch to cut the 12V power so I don't have to pull the fuse every time I want to make adjustments to the set-up.  This particular switch has an LED that is powered via the same 12V that it switches, so I had to add a resistor to the ground leg on the switch to limit the current for the LED without limiting the current to the valve.  This was done by simply cutting the wire and adding the resistor in-line.  I also added a second switch to bypass the relay and open the valve without involving the Pi.  This is a standing "request" from my wife that anything I automate must still have a manual switch for operation.

One last, but very important note, when I finally had the whole set-up finished, I tested it out.  As soon as I sent power to the solenoid, my Pi emailed me that my smoke detector was alerting and gave me an audible alert that it was preparing to shut down.  What!?!?  These are all separate systems that should have nothing to do with each other except that the same Pi controls them all!  Well, since I had run my 12V lines along the same path as the jumpers for all of my GPIO pins, as soon as I switched the solenoid on, the electrical noise on the 12V lines interfered with the signals on the other GPIOs, causing a moment of havoc for the Pi. This could have been solved by rerouting my wires, or by trying to smooth things over with capacitors, but I happened to have some ferrite core noise suppression filters lying around, so I tried one out.  After testing several times, I can verify that this does in fact solve the problem.  With the noise filter there are no issues, without it the Pi goes a little nuts.  So keep this in mind when determining your cable management, or invest in some filters to solve the problem after the fact.

Plumbing Hardware


I hate plumbing, but it's a handy thing to know how to do.  I know just enough about it to make me dangerous, but that probably applies to a lot of things.  I won't go into too much detail here, because everyone's plumbing situation is going to be different, so there is no one-size-fits-all solution.  I am going to try to focus on the few components that will be universally required, and then just skip to the final result.  If you are not completely comfortable with altering the plumbing in your house, then you may want to look into another way to do this project.  Plumbers are expensive, so mistakes could be costly, not to mention messy.  You've been warned, so I accept no responsibility if you choose to proceed and accidentally flood your house.


Above is the basic set up for the plumbing piece.  Starting on the left, the first piece we need is a cut-off valve.  If my improvised plumbing leaks or brakes, or my Pi goes all Superman 3 on me, I need to have a way to cut off the water from it's source.  Next comes the solenoid valve that will be controlled by the Pi.  After that we need to use a check valve to prevent the water from the hose from draining back into my water pipes (this is probably required by code in most places).  Finally, I used a T-junction and another cut-off valve to allow for draining the outdoor pipes.  This valve will stay closed during normal operation, and will only be opened at the end of the season in order to drain the outdoor pipes so they don't freeze.  The outlet for this valve will lead to a sink basin in my shop so that I don't have to mess with sewer lines and traps.


So that is the basic design.  To the right is the fully installed product.  To tap into the waterline I opted to slice into one of my newer Pex waterlines, which is much easier than trying to mess with 70 year old galvanized water pipe.  For the line that continues outside I opted to use galvanized steel water pipe because I wanted something more rigid to support the solenoid valve, and because you can't run Pex outside.  If you do something similar and use steel pipe outside, be sure to paint it to keep it from rusting.


Control Software

With everything in place, all I needed to do was to write a couple of short scripts to control the solenoid valve.  This is the easy part.  Here are the two python scripts called water-on.py and water-off.py:

 #!/usr/bin/env python  
   
 # water-on.py  
   
 import RPi.GPIO as GPIO  
 from time import sleep  
   
 RELAY_PIN = 26  
   
 GPIO.setmode(GPIO.BCM)  
 GPIO.setup(RELAY_PIN, GPIO.OUT)  
   
 GPIO.output(RELAY_PIN, 0)  
 sleep(1200)  
 GPIO.output(RELAY_PIN, 1)  

 #!/usr/bin/env python  
   
 # water-off.py  
   
 import RPi.GPIO as GPIO  
   
 RELAY_PIN = 26  
   
 GPIO.setmode(GPIO.BCM)  
 GPIO.setup(RELAY_PIN, GPIO.OUT)  
 GPIO.output(RELAY_PIN, 1)  

For the water-on.py script I added in a 20 minute timer before automatically turning the water back off as a fail-safe.  As always, once the scripts are created using a text editor, they need to be made executable by using

chmod +x water-on.py
chmod +x water-off.py

I need to make sure that the GPIO pin that controls the relay isn't floating when the Pi reboots, so I need to run the water-off.py script on boot.  I am going to do this by adding the following line to the /etc/rc.local file:

sudo /home/pi/water/water-off.py

This time I am also going to make the file executable without having to specify the whole path to the file by copying it to the /usr/bin folder like so:

cp /home/pi/water/water-on.py /usr/bin/water-on
cp /home/pi/water/water-off.py /usr/bin/water-off

Notice I dropped the .py when I added the file to /usr/bin.  This is not necessary, but in Linux land file extensions are not required, and it saves me a little bit of typing.  So now the water can be turned on with a simple command.

water-on

But the point of this was not to be able to turn on the water by typing a command, we could do that more easily by flipping a switch.  The goal is to be able to schedule the water to turn on and off automatically.  For this we will use Linux's built in scheduling system called Cron.  To add a task to the cron table we use the following command:

crontab -e

 The first time you edit the cron table you will be prompted to pick a text editor.  I prefer vim, but it's purely a matter of personal taste.  When the file is opened for the first time there is nothing but lines of comments explaining how Cron works.  Since the directions are built into the cron table, I won't go into too much detail here.  To turn the sprinklers on for 20 minutes every morning at 6:00am you would add the following two lines to the end of the cron table:

00 6 * * * water-on &
20 6 * * * water-off

Remember that I added a fail-safe to the water-on script to have it shut off after 20 minutes, so the water-off isn't 100% necessary, but it seems like good practice.  If you wanted to run the sprinklers for more than 20 minutes you could either edit the sleep line of the water-on script, or just add another line to the cron table to turn the water back on after 20 minutes.

So that's it.  Now every morning my Pi will wake up at 6am sharp and take care of my watering for me.  Sure you can buy an off-the-shelf product that will do the same thing, but what's the fun in that?  If anyone needs any help adapting this walk-through to your own projects just let me know in the comments and I'll do my best to help.


Monday, June 26, 2017

Adding a Soft Shutdown Switch to Headless Raspberry Pi

Recently I had to pull one of my Raspberry Pis out of service to make some hardware changes to it.  Because this Pi runs headless, in order to avoid potentially corrupting the SD card I had to log into the Pi from another computer and issue the shutdown command.  While this is only a minor inconvenience, it occurred to me that I could write a short script to shutdown the Pi when a button was pushed.  Since I already had the soldering iron out and the Pi on the bench I decided to run with the idea, and have a little fun with it while I was at it.

The basic solution to this is actually very simple, but I prefer to take simple things and make them unnecessarily complicated and over-engineered.  It's just my nature, but I realize not everyone shares my prerogative.  So in the interest of making this post as useful as possible, I am going to briefly explain the easy way first, and then I'll show you the solution I ended up using.

The Easy Way


All we really need to make this work is a momentary-on push button switch wired to a GPIO pin and a short Python script.  I used a typical pull-up resistor configuration for the button.  If you have never done this before use the diagram is to the right.  The Python script will use the RPi.GPIO module to set edge detection on the GPIO pin, and then use a threaded callback function to initiate shutdown.  To do the actual shutdown I will use the Python module os to interact directly with the operating system.  The code is short and sweet.  Feel free to copy or republish it. Here it is:

 #!/usr/bin/env python   
     
 import RPi.GPIO as GPIO  
 import os  
 from time import sleep  
   
 def initiate_shutdown(channel):  
   os.system("shutdown now -h")  
   
 BUTTON_PIN = 21  
   
 GPIO.setmode(GPIO.BCM) # Sets GPIO pins to BCM numbering  
 GPIO.setup(BUTTON_PIN, GPIO.IN) # Sets pin to input  
 GPIO.add_event_detect(BUTTON_PIN, GPIO.FALLING, callback=initiate_shutdown, bouncetime=500) # Sets edge detection on pin  
   
 # infinite loop  
 while True:  
   sleep(60)  

So now, when the button is pushed, the Raspberry Pi will execute a soft shutdown, just as I set out to accomplish.  But what happens if the button is accidentally pushed, perhaps I should add in a short delay before shutting down with a way to abort the procedure.  But this machine is headless, so I would need to devise a way to alert someone that the button was pushed, probably using light or sound.  And I don't want to waste any more GPIO pins than would be absolutely necessary.  It was becoming clear to me that this project needed to be tweaked a bit, so I went back to the drawing board and came up with a solution that fit my situation much better.


The Fun Way


In the end I decided to use a button with a built in LED that would stay on when the Pi was up and running.  I used a second GPIO pin wired to an NPN-transistor to control the LED in the button (once again a very standard way to control an LED, but the diagram is to the right if you need it. *EDIT: Not pictured in the diagram to the right is a current limiting resistor between the GPIO pin and the transistor.  I used a 1k ohm resistor, which limited the current draw from the GPIO pin to 2.5mA.  Thanks to Dan Koellen who pointed this out in the comments.)  When the button is pushed the LED will flash for 30 seconds to show that the shutdown procedure has begun, and it will go off when the Pi has shutdown.  To abort the shutdown procedure I will use the same shutdown-button so I don't waste a third GPIO pin.  When pressed the second time, shutdown is canceled and the LED goes back to always-on.  I also decided that I needed to have an audible notification, and a voice could be more fun than a simple beep or buzzer.  There are plenty of text-to-speech websites that allow you to download the voice as an MP3 for free, so I found one that I liked and recorded soundbites for shutdown-initiated and shutdown-aborted.

For the Python script, I thought I could use the same threaded callback design that I used in the code for the easy solution, but for some reason I couldn't get event detection to work inside the callback function.  Instead I went with a slightly less elegant, but just as effective solution of putting an if statement inside an infinite loop to test for event detection.  There are plenty of ways to play audio using Python, but since I had already imported the os module to shutdown, I decided to use command line functionality to play the mp3.  For this I had to install mpg123 using apt-get install mpg123.  If you do something similar and use a different method to play the audio file, just be sure to background it or run it in a different thread.  Otherwise your program will stop and wait for the audio file to finish playing.  Anyway, enough blathering about the code.  Here it is.  Fell free to copy it if you like, and leave any questions in the comments if you have any issues getting it to work for your specific situation.

 #!/usr/bin/env python   
     
 import RPi.GPIO as GPIO  
 import os  
 from time import sleep  
   
 def play_audio1():  
   os.system('mpg123 -q shutdown30.mp3 &')  
   # print 'playing audio1'  
   
 def play_audio2():  
   sleep (1)  
   os.system('mpg123 -q aborted.mp3 &')  
   # print 'playing audio2'   
   
   
 def stop_audio():  
   os.system('pkill mpg123')  
   # print 'stoped audio'  
       
 def initiate_shutdown():  
   
   GPIO.remove_event_detect(BUTTON_PIN)  
   GPIO.add_event_detect(BUTTON_PIN, GPIO.FALLING, bouncetime=500)  
       
   play_audio1()  
       
   for x in range (1, 30):  
     GPIO.output(LED_PIN, 0)  
     sleep(0.5)  
     GPIO.output(LED_PIN, 1)  
     sleep(0.5)  
     if GPIO.event_detected(BUTTON_PIN):  
       break  
   else:  
     os.system("shutdown now -h")      
   
   stop_audio()  
   play_audio2()  
   GPIO.remove_event_detect(BUTTON_PIN)  
   GPIO.add_event_detect(BUTTON_PIN, GPIO.FALLING, bouncetime=500)    
   GPIO.output(LED_PIN, 1)  
   
 # Begining of Program  
   
 BUTTON_PIN = 21  
 LED_PIN = 20  
   
 GPIO.setmode(GPIO.BCM)  
 GPIO.setup(BUTTON_PIN, GPIO.IN)  
 GPIO.setup(LED_PIN, GPIO.OUT)  
   
 GPIO.output(LED_PIN, 1)  
   
 GPIO.add_event_detect(BUTTON_PIN, GPIO.FALLING, bouncetime=500)  
   
 while True:  
   sleep(1)  
   if GPIO.event_detected(BUTTON_PIN):  
     initiate_shutdown()  

And that is that.  The soft shutdown button is now functional.  Here is the end product (the button is on the right hand side):


And here is a short video of the button in action.  Sorry it's a little shaky.  I either need a tripod for my phone or less caffeine:



EDIT:  I'm adding the following link for anyone interested in learning more about using the RPi.GPIO module in Python to interact with the Pis GPIO pins: https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/

EDIT: One thing I forgot to mention is that in order to have the script run on start-up I added the script to the /etc/rc.local file.  If you use this method be sure to use the full path to the file, and run it using sudo so that it can control the GPIO pins.  Also be sure to add an ampersand to the end of the line to background the script since it uses an infinite loop.  The line in my rc.local file looks like this:
sudo /home/pi/soft-shut/soft-shut.py &

EDIT: When I first ran this script with the audio files I noticed that the volume was really low.  Initially I thought it was the result of buying the cheapest little speakers I could find, but it turned out that by default the volume for the Pi's audio-out is not turned all the way up.  This is easily remedied with the following command that only needs to be run once:

amixer set PCM -- 100%

Wednesday, June 14, 2017

Email Smoke Detector Using Raspberry Pi

     Many years ago I built a device that would monitor the signal wire in my home's interconnected smoke detectors, and send me an email and text message when they sounded an alert.  I used a WRT54GL Linksys router that I re-flashed to run an open-source Linux based operating system, and hardware hacked to add an SD card for added storage space, 5 GPIO pins, and two serial ports.  One of the serial ports was used as a console, and the other was used to interface with an AVR microcontroller that did the actual monitoring of the smoke detectors.  It was over engineered and unnecessarily complicated, but it worked, and it introduced me to Linux scripting and microcontroller programming.  It was probably the first electronics project that I fully engineered from start to finish, and I still look back fondly on that project.

     Recently, as I was pondering on what I could do with the various Raspberry Pis I have acquired, it occurred to me that the Pi, with all it's free GPIO pins, would be perfect to revisit and re-engineer my old smoke detector email device.  In fact, this project would take so few resources that there is no reason I can't use the same Pi for several other "smart home" type tasks.  With that in mind I designed the basic layout of this project to be modular and expandable.  I used a piece of 3/16" thick acrylic sheet and some scavenged motherboard standoffs to mount the Pi and the other circuit boards.  I drilled holes in the acrylic slightly smaller than the threads on the standoffs, and just used the standoffs to tap threads into the acrylic.  It actually worked pretty well, and made for a very stable structure.  I bought a breakout board for the Pi's GPIO pins with a ribbon cable to allow for an easy disconnect point and mounted it on a perf-board with pins to provide a test point when all the cables were connected.  I made sure to leave room on the acrylic sheet for future expansion.


     The basic concept for this project is based on the fact that when one of my smoke detectors activates, it sends 9 volts down a signal wire to let all the other smoke detectors know that they also need to sound in order to alert people in all areas of the house.  If I can detect this 9V signal then it's just a matter of writing the code to send the email.  Since this is the case, the project can be broken into two parts, hardware and software.  For the hardware side, I need to determine how to take that 9V signal and convert it into a 3.3V signal that the Pi can receive on one of it's GPIO pins (more than 3.3V could seriously damage the Pi).  On the software side I need to program the Pi to detect the level change on one of it's GPIO pins and send an email when it receives that signal.  Overall this shouldn't be too complicated.  So, let's get to building.

The Hardware

     The hardware side of things ended up being a little more complicated than I expected due to the electrical noise present on signal wire from the smoke detector.  For the sake of documentation I'll go through the failure of the initial design first, but if all you are looking for is the final solution you can skip to the end of this section.
     I started the design with the idea that all I needed to do was convert the 9V signal from the smoke detector into 3.3V for the Pi's GPIO pins.  There are several ways to convert 9V to 3.3V, but I decided to go with a simple voltage divider circuit, since all it would take are a couple of resistors that I already had lying around.  This is how it works:



For the circuit above, the following formula applies:



Since I am trying to convert 9V to 3.3V, all I need to do is find two resistors in my collection that will make V(out) about 1/3 of V(in).  A little bit of math tells us that R1 needs to be about twice the value of R2.  I settled on an 8.2 kohm resistor for R1 and a 3.9 kohm for R2, since that is what I had readily available.  I built the circuit on a breadboard and tested it with a 9 volt battery.  The battery measured 9.7V across it's terminals, and I measured 3.1V for V(out), which is enough to pull the GPIO pin to high.  A little more math said that at 9V even V(out) would be 2.9V, and according to the following website, the voltage really only needs to be >2V in order to pull the input pin to high  (http://www.mosaic-industries.com/embedded-systems/microcontroller-projects/raspberry-pi/gpio-pin-electrical-specifications)  I thought I had a quick and easy solution, but once I had everything soldered and connected, I was surprised to find that the Pi was sending out multiple false alarms.  It seems that the signal wire for the smoke detector circuit was picking up electrical noise and that was translating into false alarms.  I tried to smooth it out with capacitors, but to no avail.  I decided it was probably better this way, being forced to isolate the smoke detector circuit from the Pis circuitry would protect both the Pi and the smoke detectors, so I went about trying to find the best way to do it.

  I thought about using a relay to isolate the Pi from the noisy electrical system, but there is not enough current on the signal wire to power a relay.  A transistor would probably be just as susceptible to the noise as the Pi, so that solution was out as well.  I brainstormed and researched for days trying to find a solution to this problem, until finally I came across the website of Dr Edward Cheung (http://www.edcheung.com/).  He is a very fascinating man, and I recommend taking the time to look at his web page if you have a chance, but what was of particular interest to me was a project he did in 2004 where he tied the signal wire from his interconnected smoke detectors to his homemade home automation system (http://www.edcheung.com/automa/smoke_det.htm).  In order to do this he used an optoisolator to act as the relay between the smoke detector system and his home automation system.  An optoisolator, also referred to as a photocoupler or an optical coupler, activates a light source, typically an LED, when voltage is applied across one half of the circuit.  A receiver coupled with a transistor on the other side of the circuit detects this light and closes the circuit on that side of the optoisolator.  This electrically isolates the two sides of the circuit. That was exactly the solution I had been searching for (Thank you Dr Cheung).  With this new found idea I quickly ordered some optoisolators and sketched out a circuit design.  I settled on a PC817 for the optoisolator due to it's low cost and quick/free shipping from Amazon.  Here is the datasheet if anyone is interested: http://www.farnell.com/datasheets/73758.pdf   And here is the final circuit:
When it was finally put together it worked perfectly.  A couple of notes regarding the design, I got the idea of using redundant resistors on the smoke detector side of the circuit from Dr Cheung's website as well.  The idea is that if one of the resistors failed it would not interfere with the smoke detector's operation, so the value of R1 and R2 had to be such that just one resistor would be enough to allow for proper operation of the smoke detector, and the sum of both resistors would not be too high as to prevent the optoisolator from sensing the current.  I expected to do some trial and error here, but it turned out that my first try with 680 ohms worked perfectly with one or both resistors.  R3 is just a pull-up resistor to keep the GPIO high until the circuit is closed and it is pulled low by the ground.  The switch on the Pi side of the circuit is to allow me to test multiple iterations of my script without having to set off the smoke detectors every time (my dog hates the sound).  Basically closing the switch simulates the optoisolator closing the circuit due to the smoke detector's activation.


When it came to actually building the circuit on a circuit board instead of the breadboard, I wanted to use a socket for the optoisolator in case I ever needed to change it out.  Unfortunately the only sockets I had lying around were for 16-pin microcontrollers, which were 4 times too big.  I decided to turn this inconvenience into opportunity, and wired the circuit board up to accommodate 4 optoisolators wired to four different GPIO pins.  This way if I ever decide to monitor any other systems with this same Pi, the circuitry is already built.

The Software

While there are many ways I could have approached the software side of this project, I have always wanted to learn to program in Python, so that is what I did.  A couple of Google searches and YouTube tutorials later I was ready to start.  Since this is not a Python tutorial I will just paste the code below.  If anyone would like to use the code to do a similar project of your own please feel free to copy it.  If you republish it, all I ask is to give me credit, and possibly post a link to this blog.  If you are having problems getting the code to work for your own project, please feel free to leave questions in the comments and I will do my best to answer them.  First I am listing the modules that I will be using, as well as providing a link to the Python documentation for each module.

time (used to allow the sleep command to pause the script)
datetime (used to timestamp emails and events)
RPi.GPIO (used manipulate, set, and read GPIO pins on the Raspberry Pi)
email (used to format email messages)
smtplib (used to send email messages)
https://docs.python.org/3.5/library/smtplib.html


And here's the code (obviously email addresses and passwords have been removed):


 #!/usr/bin/env python  
   
 import RPi.GPIO as GPIO # Used to interact with GPIO pins  
 import time # Used for sleep and to timestamp the email  
 from email.mime.text import MIMEText # Used to compose email  
 import smtplib # Used to send email  
   
 # Create a function to run when pin state changes  
 # When this function is called, all it does is send an email  
 # based on the state of the pin  
 def send_alert(channel):  
   
   # Set variables  
   gmail_user = 'address@gmail.com'  
   gmail_pass = 'password'  
   sent_from = gmail_user  
   send_to = 'address1@gmail.com, address2@gmail.com'  
   
   # Create Timestamp  
   timestamp = time.strftime("%m-%d-%y %H:%M:%S")  
   
   # if statement to determine which email msg to send  
   # If the pin is low then the alarm is sounding  
   # Boolean vale of pin when high is true, low is false  
   if GPIO.input(12):  
     subject = 'Smoke Detector Stopped ' + timestamp  
     body = 'Sorry to interrupt you again, but your smoke detector has stopped sounding. It is possible that there is no fire, but it is also possible that the fire has shorted out part or all of your elecrical system. Thank you for your time. \n\n   Sincerly,\n Pi-Server'  
   else:  
     subject = 'Your House May be on Fire ' + timestamp  
     body = 'Sorry to interrupt you, but it seems that your smoke detector is sounding. It is possible that your house is on fire. Thank you for your time. \n\n   Sincerly,\n Pi-Server'  
   
   # Compose the email  
   msg = MIMEText(body)  
   msg['From'] = sent_from  
   msg['To'] = send_to  
   msg['Subject'] = subject  
   
   # Send the email  
   try:   
     server = smtplib.SMTP_SSL('smtp.gmail.com', 465)  
     server.ehlo()  
     server.login(gmail_user, gmail_pass)  
     server.sendmail(sent_from, send_to, msg.as_string())  
     server.close()  
   
     if GPIO.input(12):  
       print 'All-clear email sent!'  
     else:  
       print 'Alert email sent!'  
   except:   
     print 'Something went wrong sending email...'  
   
   
 # Beginning of Program  
   
 GPIO.setmode(GPIO.BCM) # Set's GPIO pins to BCM GPIO numbering  
 INPUT_PIN = 12 # Set's the variable representing the input pin to 12  
 GPIO.setup(INPUT_PIN, GPIO.IN) # Sets the input pin to be an input  
   
 # Wait for the input to change states, run the function send_alert when it does  
 GPIO.add_event_detect(INPUT_PIN, GPIO.BOTH, callback=send_alert, bouncetime=2000)  
   
   
 # Endless loop to keep the program running  
 var = 1  
 while var == 1:  
   print 'smoke detector is being monitored'  
   time.sleep(60)  
   
   

A couple of quick notes here.  In the example above I have only sent the alert to two email addresses.  It is also possible to send a text message using email.  For Verizon, you use the full 10-digit phone number followed by @vtext.com  The advantage of using text message is that it tends to get pushed to your phone faster, since most email just polls the server periodically.  The limitation of using text messages, at least with Verizon, is that to send it from email you are limited to 140 characters including the addresses.  Since I am already sending this to two email addresses, adding two more text message addresses to the message pushes the total over 140 characters, and the message doesn't go through.  The solution to this is simple, I just need to create a second email message that only sends a short message via text.  This is not difficult, I just haven't done it yet.

Whether you've written your own script or used mine above, don't forget to make your file executable:

chmod +x filename.py

If you want to be able to run the script using only the filename without referencing the location then copy the file to /usr/bin, although this is not really necessary in this case since I will just be running the script automatically on boot.

cp /home/pi/filename.py /usr/bin/filename.py

Finally, I want to make the script run when the Pi boots so that I don't have to log in and run the script every time the power flickers.  There are several ways to do this, but the method I used was to edit the /etc/rc.local file.  Use whatever text editor you like, I prefer Vim.

sudo vim /etc/rc.local

Add the following line under the comments, but before the "exit 0"

sudo /home/pi/filename.py &

Don't forget the ampersand at the end to tell the script to run as a separate process.  Since the script is an endless loop, if you leave off the ampersand the Pi could get hung up in the loop and never finish booting.  Also note that this script must be run as root due to accessing the GPIO pins, hence the "sudo".

And that's it.  Connect all the wires, reboot the Pi, and now the Pi is monitoring the smoke detectors.


So What Next?

At the time of writing this blog I have had this project done for about a month.  It has been running 24/7 and tested periodically with both the smoke detectors and the test switch.  No problems so far, and only one false alarm that happened during a lightning storm.  I'm planning on putting this project along with my file server and network equipment on a UPS, so that should stop any power fluctuations from causing false alarms.

So what other uses can I come up with for this Pi?  I'm up for suggestions.  I'm considering a temperature and humidity sensor in the shop, because heat and moisture are bad for both woodworking and electronics.  I'm even considering putting wireless contact sensors on the windows and doors so that the Pi can act as a home security system.

Currently, I'm building a system to allow the Pi to control water flow to a hose bib so I can schedule the sprinklers hooked up to that faucet.  It combines a little plumbing with a little electronics and results in a fairly interesting project.  As soon as I get it up and running I'll post an overview for anyone interested in building something similar.  Until then, stay safe and keep building.