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
$16.99 $10.99
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 eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

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 eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.