Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arduino Home Automation Projects
Arduino Home Automation Projects

Arduino Home Automation Projects: Automate your home using the powerful Arduino platform.

By Marco Schwartz
$15.99 per month
Book Jul 2014 132 pages 1st Edition
eBook
$16.99 $10.99
Print
$25.99
Subscription
$15.99 Monthly
eBook
$16.99 $10.99
Print
$25.99
Subscription
$15.99 Monthly

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details


Publication date : Jul 23, 2014
Length 132 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783986064
Category :
Table of content icon View table of contents Preview book icon Preview Book

Arduino Home Automation Projects

Chapter 1. Building Wireless XBee Motion Detectors

In this chapter, we are going to build a project around a very common home automation sensor: a motion sensor. Ever noticed those small modules in white plastic that are in the upper corners in some rooms of people's houses, modules that turn red when you walk in front of them? That's exactly the same thing we are going to do in this project.

However, instead of using proprietary technologies, which is usually the case for these modules, we are going to base our system on Arduino. And for the communication part, we are going to use XBee modules, which are low-power radio modules that are widely used with the Arduino platform. These modules are based on the ZigBee protocol, which is also used in many commercial home automation systems.

Here are the major takeaways that we will see in this chapter:

  • First of all, we will list all the hardware and software components that we need for this project. With these components, we will build one motion sensor module composed of an Arduino board, a motion sensor, and one XBee module.

  • Then, we will test this first module; the motion sensor will be tested on its own, and we will also test the communication part by sending commands via the serial monitor of the Arduino software.

  • Finally, we are going to build a web-based graphical interface that centralizes all the data of our XBee sensors. With a simple interface built on web technologies, you'll be able to instantly see if some motion is detected in your home.

Hardware and software requirements


For this first project, we will need Arduino boards, PIR motion sensors, and some XBee modules and XBee shields, depending on the number of sensors you want to have in your system. For just one sensor, you will need the following components:

Note that I added the link to the components I used for this project as a reference, but you can also choose to use other components.

The motion sensor needs to have three pins: two for the power supply and one signal pin. It should also use a 5V voltage level to be compatible with the Arduino Uno board that also operates at 5V.

For the XBee module, I used a Series 1 XBee module, 1mW, with a trace antenna (which means it doesn't require any external antenna). You could also use a module with an external antenna, but you would then have to connect the antenna to the module. I used Series 1 XBee modules for this project as they are easier to use than Series 2, which have functionalities we do not need for this simple project. This module has a range of about 100 meters without obstacles.

You will also need to connect your XBee module to your Arduino board. For that, each of my motion sensor modules will use an Arduino XBee shield from Sparkfun, but you can use other brands as well. It just needs to make the connections between the XBee module and the Arduino board.

Finally, you will need a way to communicate with these XBee modules from your computer. I used another XBee module (also Series 1, 1mW, with a trace antenna) connected to an XBee explorer board from Sparkfun, which is basically a USB interface board where you can plug any XBee module. I used the following components for the module connected to the computer:

On the software side, you need to have the latest version of the Arduino IDE installed on your computer. For this project, the Arduino IDE 1.0.5 was used.

You will also need the aREST library for Arduino. You can find this library at the following link:

https://github.com/marcoschwartz/aREST

To install the library, extract all the files in a folder named aREST (or create this folder if it doesn't exist yet). Then, place this folder in your /libraries folder inside your main Arduino folder. You will also need to have a web server installed and running on your computer so that you can use the web interface that we are going to develop at the end of this chapter.

To configure your XBee modules, you will also need to have the XCTU software installed. You can find it at the following URL:

http://www.digi.com/products/wireless-wired-embedded-solutions/zigbee-rf-modules/xctu

Hardware configuration


The hardware configuration of this project is not really complex. For each motion sensor module you want to build, you'll need to do the following steps. The first one is to plug an XBee module on the XBee shield. Then, you need to plug the shield into your Arduino board, as shown in the following image:

Now, you can connect the motion sensor. It has three pins: VCC (for the positive power supply), GND (which corresponds to the reference voltage level), and SIG (which will turn to a digital HIGH state in case any motion is detected). Connect VCC to the Arduino 5V pin, GND to Arduino GND, and SIG to Arduino pin number 8 (the example code uses pin 8, but you could also use any digital pin). You should end up with something similar to this image:

You will also need to set a jumper correctly on the board so we can upload a sketch. On the XBee shield, you have a little switch close to the XBee module to choose between the XBee module being connected directly to the Arduino board serial interface (which means you can't upload any sketches anymore) or leaving it disconnected. As we need to upload the Arduino sketch first, you need to put this switch to DLINE, as shown in this image:

You will also need to connect the XBee explorer board to your computer at this point. Simply insert one XBee module to the board as shown in the following image:

Now that this is done, you can power up everything by connecting the Arduino board and explorer module to your computer via USB cables.

Note

If you want to use several XBee motion sensors, you will need to repeat the beginning of the procedure for each of them: assemble one Arduino board with an XBee shield, one XBee module, and one motion sensor. However, you only need one USB XBee module connected to your computer if you have many sensors.

Interfacing the PIR sensor with Arduino


First off, you are going to leave XBee aside and simply check if the motion sensor is working correctly. What you will do in the first sketch is print out the readings from the motion sensor on the serial port. This is the complete code for this part that you can just copy and paste in the Arduino IDE:

// Simple motion sensor
int sensor_pin = 8;

void setup() {
  Serial.begin(9600);
}

void loop() {
  
  // Read sensor data
  int sensor_state = digitalRead(sensor_pin);
  
  // Print data
  Serial.print("Motion sensor state: ");
  Serial.println(sensor_state);
  delay(100);
}

Tip

Downloading the example code and colored images

You can download the example code files and colored images for this Packt book that you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Let's see what this code does. It starts by declaring the pin on which the sensor is connected, in our case 8. In the setup() function of the sketch, we initialize the serial connection with the computer, so we can print out the results on the serial monitor.

Then, in the loop() part of the sketch, we read out the state of the motion sensor using a simple digitalRead() command, and store that result into a variable. This state is then simply printed out on the serial port every 100 ms.

You can now upload the sketch to your Arduino board and open the serial monitor. This is what you should see:

Motion sensor state:0
Motion sensor state:1
Motion sensor state:1
Motion sensor state:1
Motion sensor state:0
Motion sensor state:0

If you can see the state of the sensor changing when you wave your hand in front of it, it means that the sensor is working correctly and that you can proceed to the rest of the project.

Programming an XBee motion detector


You are now going to modify the sketch slightly so that it can transmit the state of the sensor to a central interface running on your computer. However, you not only want to transmit the state of the motion sensor, but also an ID identifying the sensor that is detecting the motion. Programming the detector starts by importing the right libraries:

// Libraries
#include <aREST.h>
#include <SPI.h>

The aREST library implements a REST API for Arduino. REST stands for REpresentational State Transfer, and is widely used in web applications such as Software as a Service (SaaS) applications. In our case, we will use this library to standardize the communication with the central interface that will run on the computer. In this project, the REST commands will be sent over the XBee connection that acts as a serial port from the Arduino point of view.

After importing the libraries, you need to declare the sensor pin and the ID of the module as follows:

// Motion sensor pin and ID
int sensor_pin = 8;
String xbee_id = "2";

After this, you can create the instance of the aREST library that will handle the requests coming from the graphical interface:

// Create aREST instance
aREST rest = aREST();

In the setup() function of the sketch, the first step is to start the serial communication. Be careful here, as the speed of the serial object has to be the same as the speed of your XBee modules, which is 9600 bauds by default:

// Start Serial
   Serial.begin(9600);

You can also set the ID of the module:

   // Give name and ID to device
   rest.set_id(xbee_id);

Note that if you are configuring more than one sensor, you need to change the ID of each sensor you are configuring. Now, thanks to the aREST library, the loop() part of the sketch is pretty simple. We simply have to handle the incoming requests from the computer that will come via the XBee serial interface:

void loop() {
  
  // Handle REST calls
  rest.handle(Serial);
  
}

Now, the sketch is ready to be used.

Note

All the code is available on the GitHub repository of the project:

https://github.com/openhomeautomation/arduino-home-automation/tree/master/chapter1

You can upload the sketch to your Arduino board by making sure that the switch is still set on DLINE. Once this is done, you can test the code locally via the serial monitor of the Arduino IDE. Open the serial monitor, make sure that the serial speed is set to 9600, and type the following:

/digital/8/r

This is the REST command to read a digital value from pin number 8 and return the value, which is exactly what we want to achieve. You should see the following data being returned, depending on the current state of the sensor:

{"return_value": 0, "id": "2", "name": "", "connected": true}

What we are interested in is the return_value field, which contains the result of the digitalRead() function. Try to wave your hand in front of the sensor to see if the return value changes accordingly. Note that the returned data is in the JSON format, which will be really important later when we are going to process this information and display it.

Now that you are sure that the code is working, you can switch over to XBee communication. For that, simply put the switch next to the XBee module to UART. Now, the serial port of the Arduino board is directly wired to the XBee module.

Note

By default, all the XBee modules sold are configured on the same Personal Area Network (PAN) ID, which is 3332. This means that all the modules will receive data from other modules on the same PAN ID. For experimentation, you can leave it at its default value. However, you might want to change this later, in case your neighbor is, for example, using XBee devices as well.

To continue further, insert the XBee module you want to modify in the USB XBee explorer and open the XCTU XBee tool. Click on the top-left button to add a new device and select the USB explorer serial port. You should get the following screen:

You will then be able to change the PAN ID of your device. To configure all the modules in your network, just repeat the procedure for each XBee module.

Building a graphical interface for your XBee motion detectors


Now that the hardware is completely configured, you can build the server-side code to read data from all your motion sensor modules. For this project, I used two modules only, but you can use more modules for the project.

As for many web applications, our control center for the XBee motion detectors will be built using four different languages: HTML, CSS, JavaScript, and PHP. We are going to use HTML and CSS to design the interface itself, JavaScript to handle the different elements of the interface and make the link with PHP, and finally use PHP to communicate directly with the XBee modules.

The first step is to design the interface. We'll basically have several blocks on our page, one block corresponding to one XBee module. For example, this is the HTML code for the first block:

<div class="sensorBlock"><span class="sensorTitle">Sensor 1</span>
     <span class="display" id="display_1"></span>
</div>

Now, you can have a look at the JavaScript code that will handle the different elements of the interface. Note that all this code is included inside a dedicated JavaScript file. What we are going to do here is check the value of the sensor at regular intervals via a digitalRead() command. To do this, we have to call a PHP file with the correct command as an argument:

$.get( "xbee.php", {command: "/digital/8/r"}, function( data ) {

The result from the PHP file is some string data formatted in the JSON format. To actually create a usable object from this string, we can use the parseJSON() function of jQuery:

json_data = jQuery.parseJSON(data);

Now, we have a JavaScript object that has the same properties as the data fields inside the JSON container. For example, to get the ID of the sensor module, you can just type:

var sensorID = json_data.id;

Now that we know which sensor returned some data, we can read the return_value field inside the JSON object to know the status of the motion sensor on this module. If this value is equal to 0, we set the background color of the display block of this sensor to gray. If it is equal to 1, it means that some motion was detected. If this is the case, we change the background color to orange as follows:

if (json_data.return_value == 0){
  $("#display_" + sensorID).css("background-color","gray");
}
else {
  $("#display_" + sensorID).css("background-color","orange");
}

Let's now see the details of this PHP file that is called every time. We saw in the JavaScript code that the PHP file also receives an argument called command. This variable is retrieved inside the PHP file by:

$command = $_GET['command'];

Inside this file, we also need to include the php_serial class:

include "php_serial.class.php";

We also need to declare the right serial port for your XBee explorer device:

$serial_port = "/dev/cu.usbserial-A702LF8B";

Note

You will have to change this according to your own settings. To know which serial port the XBee explorer board is using, simply search for devices starting with cu inside your /dev folder if you are using Linux or OS X. If you are using Windows, you will see the list of the serial ports in your Configuration Panel.

You now need to configure the different settings of the serial connection we are about to open with the board:

$serial = new phpSerial;
$serial->deviceSet($serial_port);
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);

Now, you can actually open the connection:

$serial->deviceOpen();

We can now send the command and read the answer:

$serial->sendMessage($command . "\r");
$answer = $serial->readPort();

Now, we close the serial connection:

$serial->deviceClose();

Finally, we send back the data that was read:

echo $answer;

We are now ready to test our project. You can of course find all the code for this part on the GitHub repository of the project at the following website:

https://github.com/openhomeautomation/arduino-home-automation/tree/master/chapter1

Make sure that your web server is running, and that all the files of the project are placed inside a folder in your web server's main folder. You can now head over to this folder, usually accessible by typing localhost in your favorite web browser. Open the HTML file, and you should see something similar to the following screenshot:

Note that on this example screenshot, the second sensor I had in my system already detected some motion. Now try with your sensors by waving your hand in front of them; you should instantly see that the state of the sensor changes on the interface.

Of course, by modifying the HTML and JavaScript code, you can easily modify this interface to adapt it for more sensors.

Also, be aware that these modules don't need to be connected to your computer directly once the code is loaded onto them. You can just disconnect them from your computer and power them using a simple battery pack (the Arduino Uno board, for example, accepts up to 12 V of power on its jack input).

Note that you can also access this interface from a mobile phone or tablet, just by accessing the localhost folder on your computer. Of course, your computer has to be powered (and the web server running) to access the interface.

Summary


Let's now summarize what we did in this first project of the book. We built XBee motion sensors that are based on Arduino, and learned that you can put them wherever you want in your home. They communicate with a central interface where you can see the status of every sensor live.

Of course, we could have used other wireless communication devices for this project, such as Wi-Fi. However, XBee modules are very energy efficient compared to Wi-Fi modules, so it completely makes sense to use XBee for this project, as you might want to power these motion sensors from batteries.

Let's see what the major takeaways of this chapter were. We first chose the components for our project, and built our fist XBee-based motion sensor using Arduino and a PIR motion sensor. We also connected an XBee module to our computer via a USB so it can communicate with the other modules.

Then, we tested our motion sensor module by first testing the PIR sensor connected to the Arduino Uno board. We also tested the sketch at this point that we used to access the board via XBee.

Finally, we built a web-based interface to visualize the information coming from the different XBee motion sensors live. This interface was tested with two modules, but it is made to easily extend to many more XBee modules.

In the next chapter, we are going to tackle another huge field of home automation: controlling lights. And for this project, we won't be using XBee, but we are going to interface Arduino with a Wi-Fi chip to control lights from any mobile device.

Left arrow icon Right arrow icon

Key benefits

What you will learn

Connect home automation sensors to the Arduino platform Use the XBee technology to build lowpower wireless motion sensors Interface a relay with Arduino to control devices in your home Utilize WiFi to control a lamp remotely Employ Bluetooth and Arduino to measure the temperature remotely Send energy consumption data to the cloud Hack an existing home automation device using Arduino

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details


Publication date : Jul 23, 2014
Length 132 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783986064
Category :

Table of Contents

14 Chapters
Arduino Home Automation Projects Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Building Wireless XBee Motion Detectors Chevron down icon Chevron up icon
Control Lights from Your Phone or Tablet Chevron down icon Chevron up icon
Measuring the Temperature Using Bluetooth Chevron down icon Chevron up icon
Weather Station in the Cloud with Xively Chevron down icon Chevron up icon
Monitor Your Energy Consumption in the Cloud Chevron down icon Chevron up icon
Hack a Commercial Home Automation Device Chevron down icon Chevron up icon
Build Your Own Home Automation System Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.