Introduction: Basic Home Automation With Phidgets

About: Phidgets make your ideas real. Reliable sensors, motor controllers, relays and more connect computers and technology to the real world. Applications include robotics, data acquisition, monitoring, automation, …

This simple project will take you through the basics of getting some interior sensing and home automation set up. The project runs from a Phidgets SBC, will read light and sound and turn a light on and off remotely. You can really grow this project to monitor and control your home, but to keep from getting too wordy, this just shows a couple of examples to get you started.

Step 1: Materials

  • a 1073 Phidgets SBC3 with 2m network cable (Cat 5e) and power supply
  • Optional - a 3703 Wi-Fi USB Adapter (you’ll need this if you won’t be able to connect to a router or an ethernet port in the wall)
  • a 3051_1 Dual Relay Board and sensor cable
  • a 1133 Phidgets Sound Sensor and sensor cable
  • a 1142 Phidgets Indoor Light Sensor - 1000 Lux and sensor cable
  • a suitable sized wooden (or metal) board for mounting - an 8” x 12” board should be sufficient - we used a 20” x 10 ½” board, which was more than enough
  • 16 M3 nut and bolt pairs, ⅝” long and 16 plastic spacer, ¼” long that should come packaged with all the phidgets.
  • a power bar or extension cord
  • a piece of wire
  • a lamp
  • exacto knife
  • wire cutters

Step 2: Assembly

To start off, get a plate of wood or metal in the approximate size you want your panel and mount the SBC, sound sensor and indoor light sensor to it. If you want to eventually add more sensors, prepare a larger board so you have room to mount everything. Use the stand-offs provided with all the Phidgets so that there is adequate spacing between the Phidget and the surface of the panel. This is especially important if you are making your panel out of metal; If the electronics touch the panel you are bound to have numerous short circuits.

Step 3: Lighting Control

For the light, we hacked apart the cord of a power bar. An extension cord will work the same way, so you can use that instead. While the power bar is unplugged, strip the outer coating off about 6-inches of the cord coming out of the power bar. There are three wires (black is the load, white is neutral and green is ground). We want to work with the load line, so cut the black wire and strip just an ⅛-inch off the ends to reveal copper wire.

Connect one of the stripped black wire ends to 0C (0’s common) and the other end to NO (normally open) on the dual relay board.

[Edit: A reader suggested adding a fuse in series with the output of the relay. Choose a fuse that's rated equal or lower to the contact rating of your relay. A very good suggestion!]

Connect the dual relay board to the SBC: Connect control 0 on the dual relay board to digital output 0 on the SBC using a piece of wire (the number correlation is arbitrary and we could connect this wire to any digital output). Connect the sensor cable to analog input 4 (this is just for power).

Plug any standard lamp you wish to control into the prepared power bar or extension cord. Make sure the light’s switch is in the “on” position.

Of course, you can put other things into the power bar, but they will only work when the power is on (as in, the digital output 0 on the SBC is on). Different electronics function differently, so it may only mean power is going to it, but not turning it on. Lights are pretty simple so they function well. Also, you won’t be able to control each device individually. You could repeat the process with another cord and attach it in a similar way to the other control on the dual relay board.

Step 4: Connecting Sensors

Attach the indoor light sensor and sound sensor to analog inputs 0 and 2, respectively, using sensor cables. You can attach the sensors to different inputs, but you’ll need to change the code, so start here.

Step 5: More About the Code

The code uses ajax and json for synchronizing the web interface to the SBC and mongoose for the web server (both the necessary jquery and mongoose source files are in the project folder for you). This allows the webpage to show real time updates from the SBC in a fairly clean way.

homeAutomation.c is the heart of it, so let’s start there.

Globals

At the top of the homeAutomation.c file are the global definitions. You’ll need to set the serial number of the SBC you’re using, put in the system password (the one used for logging into the web interface), the index of the sensors and the index of the light you’re controlling. In this case, the serial number is 250000, the password is PASSWORD, the light sensor is on input 0, the sound sensor is on input 2 and the lamp light is on output 0.

#define SbcSerial 250000
#define SbcSystemPassword "PASSWORD"
#define LightSensorIndex 0
#define SoundSensorIndex 2
#define Output_Light1Index 0

As you add more Phidgets, you can add them to the global macros as well.

We also put some calibration numbers and created a global CPhidgetInterfaceKitHandle for our Sbc, which we named McflySbc.

Interpreting incoming data and calibration

Some calibration values are also put up top. The light sensor’s values change from Phidget to Phidget so check the sticker attached to the sensor for the m and b values and type those in.

#define LightCalibrationMValue 1.478777
#define LightCalibrationBValue 33.67076

The function get_data handles the ajax-channelled requests for messages, like sensor values. When adding more sensors you’ll put them into this code in another “else if (!strncmp(request_info->query_string, "sound", reqlen))...” like condition statement. You can copy and paste the existing ones and edit the formula in the inner if statement as needed. Check the user guide of the device for specific formulas and values, but the light and sound ones are already done.

Controlling output

The function set_data sends messages to the SBC to change the output states (like turning a light on or off). Requests come in through Ajax, like “light1On” and “light1Off” and the appropriate output state is set on the SBC. You could connect more lights in this fashion (replacing the 1 with ascending numbers), or something else you want to control around the home (but be careful when working with electricity and make sure you know what you’re doing, or ask someone who does, before messing with electrical currents).

Event Handler

The event_handler connects the get_data and set_data functions when Ajax gets a get_data or send_message request, respectively. Nothing to mess around with here.

Attaching The Interface Kit

SbcAttach sets up the interface kit on the SBC with the ratiometric on, sets the sensor change trigger to 1 for attached sensors and the data rate as well. As you add more sensors you’ll need to add them to the list and put the data rate to something in the lower hundreds range. For the inputs not in use, we’ve set the data rate to 1000ms.

Index.html is the face of the program… like most web-pages, you know how it works.

We use jquery and some very simple css. The jquery file is available online and in the source files for this project. style.css is pretty basic so it won’t be explained here, but feel free to play around with it or use your own stylesheet. You can check out a CSS tutorial on W3 Schools.

Setting Up The Ajax Requests

We start out with some javascript that sets the interval for data requests of the SBC through Ajax. All the sensors will need to be loaded right away and then checked periodically. You can set different sensors to have different intervals by putting them in different setInterval methods and changing the second parameter to be the number of milliseconds you want between data requests. Make sure to give all your sensors a unique and descriptive name. Note that in this example we’re also going to be sensing whether our light attached to the SBC is on or off.

We also have elements with the IDs “light1On” and “light1Off” that, when clicked, we want to send a request through Ajax to the SBC. We set the onclick functionality here. Each element (button or image or whatever you want to cause the output to change) will need its own unique and descriptive ID.

window.onload = function() {

var turnon1 = document.getElementById("light1On");

var turnoff1 = document.getElementById("light1Off");

turnon1.onclick = function() {

$("light1On").load('/ajax/send_message?light1On');

return false;

}

turnoff1.onclick = function() {

$("light1Off").load('/ajax/send_message?light1Off');

return false;

}

}

Note that we keep the id name of the element (like “light”, “output_light1” and “light1Off”) the same as the message that is sent through Ajax to the c program. So the id also appears at the end of the Ajax request (i.e. /ajax/get_data?light for the “light” element and /ajax/send_message?light1On for the “light1On” element). You could change these messages, and then make sure the variable at the end of the Ajax request matches what is in your c program, but you can imagine how confusing this would get, so we suggest keeping them the same.

The Webpage Finally, the body. The table cells where we want the sensor values to be displayed are given the ids we just used in setting up the ajax requests. This makes it so that their content is updated with each new get_data request, described a bit earlier.

Also, the table cells that we want to use to control the lights are given the appropriate ids (“light1On” and “light1Off”) so that when they are clicked the onclick function sends the Ajax request.

You can add more table rows for different sensors, giving the cell where you want your data displayed the id you chose (like “temperature”, if you had a temperature sensor).

To summarize, if you’ve set up the Phidgets exactly as directed in the instructions, all you have to do is:

  1. In homeAutomation.c, set the serial number and password for your SBC
  2. Set the calibration measurements from you light sensor.

If you want to add your own sensor here’s what you’ll need to change:

  1. Set global macros in the homeAutomation.c file, giving each sensor a global name and assigning it the correct sensor input number.
  2. Add the sensor in get_data by copying another sensor’s else if (else if(!strncmp(request_info->query_string, "[SENSORNAME]", reqlen) and so on…. ) and changing the formula per your Phidget’s specifications.
  3. In the SbcAttach function, set the sensor change trigger to 1, the data rate to an acceptable speed and remove the input from the unused inputs list.
  4. In index.html add a line to load the data right away ($("#[SENSORNAME]").load('/ajax/get_data?[SENSORNAME]);
  5. Also in index.html, in setInterval, add that line again so that the sensor keeps being polled for data.
  6. Add a table row and set the second column cell to have the [SENSORNAME] as its id, (<div id=”[SENSORNAME]”>Please Wait…</div>)

For a new output device (remember we’re both looking at the status, as an input, and we’re setting the state)

  1. Set global macros in the homeAutomation.c file, giving each output a global name and assigning it the correct output number.
  2. Add the Phidget in get_data by copying another output’s else if (else if(!strncmp(request_info->query_string, "[OUTPUTNAME]", reqlen) and so on…. ) and changing the variables appropriately.
  3. Add the Phidget in set_data by copying another Phidget’s else if (else if(!strncmp(request_info->query_string, "[OUTPUTCOMMAND]", reqlen) and so on…. ) and changing the setOutputState function for the Phidget you’re controlling and the state you want it in.
  4. In index.html add a line to load the data right away ($("#[OUTPUTNAME]").load('/ajax/get_data?[OUTPUTNAME]);
  5. Also in index.html, in setInterval, add that line again so that the sensor keeps being polled for data.
  6. In the method following window.onload, create two new variables to control turning the Phidget on and off. Copy the onclick methods, changing the OUTPUTCOMMAND as necessary. (VARIABLE.onclick = function() { $("OUTPUTCOMAND").load('/ajax/send_message?OUTPUTCOMMAND)... etc. )
  7. Add a table row and set the second column cell to have the [OUTPUTCOMMAND] as its id, (<div id=”[OUTPUTCOMMAND]”>Please Wait…</div>)

Step 6: Mounting

Chose a location that has a relatively clear view of the room you’re monitoring and is also close enough to a wall socket for plugging in the SBC’s power supply. In this example, we used a wired internet connection through a wall port because there was one nearby, but you could also get a Wi-Fi USB adaptor, which runs smoothly on the SBC and performs like the wired connection.

Keeping wiring short and tidy is a good way to reduce failure points and keep things looking presentable. If you are going to be running cables through the wall it is a good idea to drill a hole in the wall behind the intended panel mounting location and the corresponding point on the panel. This will allow you to run the cables through the panel, into the wall and will ultimately hide some of the wiring.

Step 7: Running

If you haven’t done so yet, and you’re new to working with an SBC, watch the “Getting Started with A Phidgets SBC” video or read through the 1073 User Guide on phidgets.com. These instructions assume you are familiar with the SBC web interface

After making the appropriate changes to the files, load the homeAutomation files onto the SBC as a new project, let’s call it homeAutomation. You can do this through ssh using the scp command, if you’re familiar with linux. For example, ‘scp -r [PATH-TO-FOLDER]/homeAutomation root@sbc.local:/usr/userapps/’. Or you can do it file by file using the web interface, which is recommended for any beginners.

Connect to the SBC via ssh using its hostname or IP address (for example, ssh root@mcflysbc.local). You can do this using PuTTY on Windows or the terminal applicatin on Linux or Mac OS X. Make sure you have enabled the SSH server in the network settings.

Navigate to the folder where the Makefile is:

cd /usr/userapps/homeautomation


Compile the code:

make -f Makefile


Go to the SBC web interface. Go to projects and click the home automation project. In startup settings, choose the homeautomation executable and set it to enabled. Save changes.

There will now be a Start button at the top. When you click it, the program should start running. Bring up http://mcflysbc.local:8000 (you will need to replace mcflysbc with whatever name y ou've given to your Sbc) to see the input and control the light.

Step 8: Setting Up the Web Server

Once you've uploaded your program, compiled it and tested it by going to your local site (for example, http://mcflysbc.local:8000), you'll need to forward the ports through your router so you can see it anywhere on the web, and you'll probably want to get your own domain name so you don't have to remember a scramble of numbers.

Before launching the website, you'll probably want to tune your program to show only the data that you want anyone to see. Go back to the simple home automation guide to get the details on editing the code. For me, I replaced the relay switch with an LED. I still want it to be interactive, but not have my room lights turn on and off with wild abandon.

Find Your SBC's IP Address

Log onto your SBC's web configuration and go to the Network page. The IP Address will be obviously displayed there.

Set up Port Forwarding on your Router

Open your router's setting page. This can be accessed through one of the following addresses: http://192.168.1.1, http://192.168.1.1, http://192.168.2.1, or an address specified in your router's user manual.

Find the port forwarding. Each router is different so it's hard to say where it'll be put for your device. Once you find it, enable a new port forward. Set the internal start port and end port to 8000; the external start port and end port to 80; protocol is TCP; and the IP address will be the IP address of your SBC.

Get a Domain

You can purchase a domain from sites like Hover, Namecheap, Gandi, Dreamhost, Name.com, or GoDaddy. If you don't want to pay, and don't mind an extension on your domain (like ddns.com) then use a service like No-IP. Set up the domain as a DNS host and give the IP address of the SBC that you found in the last step.

Now you can go to your URL and monitor your home from wherever you are.

Step 9: Expansion!

Next up, you can keep graphs of the data collected so you can look at trends over the year. You can also switch the server to a world wide web address so that you can access it anywhere. The SBC supports any USB Video Class (UVC) webcam, so you can set that up too.

You can do all sorts of things with sensors:


And control a number of things:

  • Motors that can open and close blinds
  • Program with an IR transmitter to control TVs or stereos
  • With some pet feeders, motors and clever designs, you could drop a portion of food for your pet whenever you want
  • Fancy LED arrangements to make a cool dance party happen at the press of a button
  • And so much more

Remember to be careful when setting up remotely controlled devices! Test everything thoroughly, and remember that pets need more than just food (they need love, too) so don’t leave them home alone for extended periods of time.