Home Automation with Arduino (Best Tutorial 2019)

Home Automation with Arduino

Arduino for home Automation Tutorial 2019

In this tutorial, we build a home automation system with Arduino. We are going to build a simple but complete home automation system that we will completely control from the cloud, thanks to the ESP8266 Wi-Fi chip.


The system will be composed of a motion sensor, a temperature and humidity sensor, and an LED dimmer. This way, it will mimic all the essential components of a real home automation system.


We are going to build three projects based on Home Automation with Arduino 2019We are first going to see how to simply control every component of the system using an online dashboard.


Then, we are going to see how to send automated alarms to your phone when motion is detected in your home. Finally, we are going to see how to automate your home using IFTTT and the system we created. Let's start!


Hardware and software requirements

Home Automation

Let's first see what we need for this project. You will mainly need components we already used in previous blogs, such as the ESP8266 module, an LED, and the DHT11 sensor. 


The only new component here is a PIR motion sensor that we will use to detect motion in our home. I used a simple 5V-compatible PIR motion sensor, which is a pretty standard component.


I listed all the components for this blog, based on one motion sensor module, one LED dimmer, and one sensor module. Of course, if you want to use more of each module, this is no problem, you just need to add more ESP8266 modules to the project.


This is a list of all the components that will be used in this blog:


Adafruit ES8266 module (x3) (https://www.adafruit.com/ products/2471)

FTDI USB module (https://www.adafruit.com/products/284)

 DHT11 sensor (https://www.adafruit.com/products/386)

LED (https://www.sparkfun.com/products/9590)

330 Ohm resistor (https://www.sparkfun.com/products/8377)

PIR motion sensor (https://www.sparkfun.com/products/13285)

Breadboard (x3) (https://www.sparkfun.com/products/12002)

Jumper wires (x3) (https://www.sparkfun.com/products/9194)


On the software side, you will need the aREST library, the PubSub library, and also the DHT sensor library. We already installed those libraries in previous blogs of the blog, but if that's not done yet, you can simply install them using the Arduino IDE library manager.


Hardware configuration

Arduino Hardware

We are now going to assemble the different parts of this project. First, we are going to configure the motion sensor module.


For this first module, after placing the ESP8266 board on the breadboard, connect the VCC pin of the sensor to VCC, GND to GND, and finally the OUT pin of the sensor to pin number 5 of the ESP8266.


Let's now deal with the temperature and humidity module. Place the sensor on the breadboard, and then connect the first pin to VCC, the second pin to pin number 5 of the ESP8266 board, and finally the last pin of the sensor to GND.


This is the final result for this module:

Arduino Broad

Let's now assemble the LED dimmer module. Here, we are going to use a simple LED as the output, but you can, of course, use this as the starting point of a module to control more LEDs in your home or even lamps.


To connect the LED to the ESP8266, simply place the LED in series with the 330 Ohm resistor on the breadboard, the longest pin of the LED in contact with the resistor. Then, connect the other end of the resistor to pin 5 of the ESP8266, and connect the other end of the LED to GND.


Controlling your home from a dashboard

In the first project of this blog, we are going to learn how to control all the modules we assembled before from a cloud dashboard, using the aREST framework we already used in this blog.


First, let's configure all the modules. We are going to start with the LED dimmer module, which is the easiest to configure. Here is the complete code for this module:

// Import required libraries
#include "ESP8266WiFi.h"
#include <PubSubClient.h>
#include <aREST.h>
// Clients WiFiClient espClient; PubSubClient client(espClient);
// Unique ID to identify the device for cloud.arest.io char* device_id = "6g37g4";
// Create aREST instance
aREST rest = aREST(client);
// WiFi parameters
const char* ssid = "wifi-name";
const char* password = "wifi-pass";
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Create an instance of the server WiFiServer server(LISTEN_PORT);
void setup(void)
// Start Serial Serial.begin(115200);
// Set callback client.setCallback(callback);
// Give name and ID to device rest.set_id(device_id); rest.set_name("dimmer");
// Connect to WiFi WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500);
Serial.println(""); Serial.println("WiFi connected");
// Start the server server.begin(); Serial.println("Server started");
// Print the IP address Serial.println(WiFi.localIP());
void loop() {
// Handle REST calls rest.handle(client);
// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {
// Handle
rest.handle_callback(client, topic, payload, length);


There are several things you need to modify in this code. You need to substitute the Wi-Fi name and password for your own. You also need to modify the device ID of the device, so it has a unique identifier on the network.


Finally, you can also modify the name of the device, for example, to add some data about where the module is located in your home. Once that's all done, upload the code to the board, and then move on to the next device: the motion sensor.


For this module, the code is nearly the same, we just need to add some lines to constantly measure the state of the motion sensor and make it available on the cloud. For that, we first define a variable that will host the motion sensor state:

int motion;
Then, we expose this variable to aREST:
rest.variable("motion", &motion);
Next, inside the loop() function of the sketch, we simply measure the state of the motion sensor:
motion = digitalRead(5);
After modifying the same parameters as for the LED module (Wi-Fi credentials, device ID, and name), upload the code to the board.
Finally, let's deal with the sensor module. For this one, you will need to import the
DHT library:
#include "DHT.h"


Then, you will need to define which pin the sensor is connected to:

#define DHTPIN 5
#define DHTTYPE DHT11
After that, create an instance of the sensor:
We also create two variables that will hold the value of the measured temperature and humidity:
float temperature;
float humidity;
In the setup() function of the sketch, we initialize the DHT sensor:
We also expose those variables to the aREST API:
rest.variable("temperature",&temperature); rest.variable("humidity",&humidity);
Finally, inside the loop() function of the sketch, we measure the temperature and humidity of the sensor:
humidity = dht.readHumidity();
temperature = dht.readTemperature();


Again, modify the required parameters inside the sketch and upload it to the board. Note that to power all the modules, you can, for example, use either an external battery or a breadboard power supply.


You do not need to have one FTDI cable per module. It's now time to control all our boards from the cloud! First, go over to the aREST dashboard website: http://dashboard.arest.io/


Create a new dashboard for your home automation system:


Inside this dashboard, switch to edit mode and add the first element that will hold the temperature measurement. Make sure to enter the correct ID of your temperature and humidity module:


We are now going to add the LED dimmer module. As we want to be able to control the intensity of the LED light, create a new element with the Analog option. You should now be able to control the intensity of the LED via a slider inside the dashboard:


Finally, create a new element for the motion sensor:

You should end up with a dashboard that has all the elements of the simple home automation system we just built:


Congratulations, you just built a complete home automation system based on the ESP8266, which you can now control from the cloud. You can, of course, add more modules to the system, and control them from the same dashboard. 


Note that as this dashboard is accessible from anywhere, you don't actually need to be inside your home to access it!


Creating a cloud alarm system

cloud alarm system

We are now going to build another project based on the same hardware we have already built in this blog. This time, we are going to make an alarm system based in the cloud, using the ESP8266 module along with the PIR motion sensor.


I will show you how to do it with just one PIR sensor, but you can, of course, add more modules that will be dispersed around your home or any building you wish to monitor. To do that, we are going to again use IFTTT, which will send you a text message every time motion is detected by any of the motion sensor modules.


Let's first see how to configure a given module. As it's code that is very similar to what we already saw earlier in this blog, I will only highlight the most important parts here.


You need to set the key that is linked to your Maker channel on IFTTT:

const char* host = "maker.ifttt.com";
const char* eventName = "motion_detected"; const char* key = "key";
Then, inside the loop() function of the sketch, we read the status of the motion sensor:
bool motion = digitalRead(5);
We then check whether any motion was detected:
if (motion) {
If that is the case, we build a request that we will send to IFTTT:
String url = "/trigger/";
url += eventName;
url += "/with/key/";
url += key;
We then actually send this request to the IFTTT servers:
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
int timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) {
Serial.println(">>> Client Timeout !");
After that, we read the answer:
String line = client.readStringUntil('\r'); Serial.print(line);


We then wait for a long time before sending new alerts; otherwise, we'll just send a lot of messages to your mobile phone: delay(10 * 60 * 1000);


Now, grab the code (for example from the GitHub repository for the blog), modify it with your own credentials, and upload it to the board.

  • Now, head over to IFTTT to create a new recipe: https://ifttt.com/
  • As the trigger channel, select the Maker channel:
  • As the event, insert motion_detected, which is also what we put in the code:

As the action channel, we'll select SMS here, as it will be the fastest way to contact you in case an alarm is triggered by your motion sensor:


Now, create the recipe and activate it. You should see that whenever you pass your hand in front of the sensor, it will almost immediately send an alert message to your phone. If you wish to stop your alarm system, it's then as simple as deactivating the recipe on IFTTT.


You can, of course, add more sensors to the system, making each publish the same alert on IFTTT. Therefore, whenever any sensor detects motion, you will receive an alert on your phone.


Automating your home

Automating your home

Now we are going to play a bit more with IFTTT. This time, instead of using the motion sensor, we'll see how to use the different trigger channels of IFTTT to create nice automation flows to control the LED module. Of course, remember that you could replace the LED with any appliance you wish to control, for example, a lamp.


The Maker channel of IFTTT can also be used as an active channel, and this is what we are going to use here. We will use it to call the aREST API whenever a given condition is triggered.


We are first going to configure the module again, so it can receive commands from the cloud. This is the part of the code before the setup() function:

// Import required libraries #include "ESP8266WiFi.h" #include <PubSubClient.h> #include <aREST.h>
// Clients
WiFiClient espClient;
PubSubClient client(espClient);
// Unique ID to identify the device for cloud.arest.io char* device_id = "6g37g4";
// Create aREST instance
aREST rest = aREST(client);
// WiFi parameters
const char* ssid = "wifi-name";
const char* password = "wifi-pass";
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Create an instance of the server WiFiServer server(LISTEN_PORT);
This is the setup() function of the code:
void setup(void)
// Start Serial Serial.begin(115200);
// Set callback client.setCallback(callback);
// Give name and ID to device rest.set_id(device_id); rest.set_name("dimmer");
// Connect to WiFi WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500);
Serial.println(""); Serial.println("WiFi connected");
// Start the server
Serial.println("Server started");
// Print the IP address Serial.println(WiFi.localIP());
// LED pin to output pinMode(5, OUTPUT);
Finally, here is the loop() function of the code:
void loop() {
// Handle REST calls rest.handle(client);
// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {
// Handle
rest.handle_callback(client, topic, payload, length);


Now, modify the important credentials (Wi-Fi name and password, and device ID) in the code, and upload it to the board.


Then, go back to IFTTT. The first thing we are going to do is to make a project to light up the LED at a given time (for example, when it's becoming dark outside), and then it off again at another time (for example, when you go to bed).


For that, create a new recipe with Date & Time as the channelYou might need to connect it first if you have never used it before:


For the trigger type, select Every day, and enter the time at which you want the LED to turn on. Then, for the active channel in IFTTT, select the Maker channel, and then select Make a web request. This will allow IFTTT to send a command to the aREST.io cloud server.


As the request, enter the following parameters, of course changing the device ID with the one you used inside the sketch: Now, do the same with the time you want the LED to turn off, for example at 11.30 PM:


Choose the same action channel as earlier:

For the web request, enter the same parameters as before, but this time with the command to switch pin number 5 to LOW. Now, validate the recipe:

It's now time to see the recipe in action! Make sure the ESP8266 board is correctly configured, and also that the recipes are activated in IFTTT. Whenever the time conditions are met, you should immediately see the LED turn on or off. You can, of course, modify the times inside the recipes to test them.


Now, let's play with another trigger channel to see how powerful IFTTT is. You can, for example, use the Weather channel to check whether it's sunset, to automatically turn on the LED at this time without having to enter a fixed time.


To do so, create a new recipe and select the Weather channel, which you need to connect to. To connect the Weather channel, you simply need to enter your current location:

  • As the trigger type, I chose to trigger the even at sunset:
  • As the action channel, I selected the Maker channel, as I did earlier:
  • Also, just as in the previous recipe, I decided to turn the LED on whenever the recipe is triggered:


You can now see the newly created recipe:

You should now see that whenever sunset approaches, the LED will automatically turn on. You can, of course, play with more conditions inside IFTTT, and even use the Maker channel as both the trigger and the action channel, to link the different modules of your home automation system via IFTTT.


Hack a Commercial Home Automation Device

Commercial Home Automation Device

 In this blog, we are going to take another approach to build home automation systems. We will take a basic power switch that you can easily buy off the shelf in stores and hack it by inserting an Arduino system inside it. This way, we are going to build a USB-controlled power switch based on Arduino.


The following will be the major takeaways from this blog:

First, we are going to see how to choose the device to hack, and which components you will need to hack the device. We are also going to take care of the different software modules needed.


Then, we will open up the device to hack and replace most of what is inside with an Arduino board and a relay module.


We will then upload some code to the Arduino board to check if the hardware is working correctly. At this stage, we are already going to command the device remotely from the Arduino IDE.

Finally, we are going to build a web-based interface to control the device directly from your web browser.


Hardware and software requirements

Home Automation Hardware

This project is based on hacking a commercial device to control light directly from your computer via USB. However, the goal is really to teach you how to hack your own device, so the device that you are going to hack doesn't matter that much. Therefore, mentioning a specific brand or product is irrelevant.


Since this blog is about hacking a device that uses dangerous voltages such as 110V or 230V, it should be considered only as an informational source and not be used as such in your home for safety reasons. Indeed, there is no way to be sure that the device will continue working properly in the long term once installed in your home.


Also, make sure to never touch the inside of the device when it is under operation and make sure that no cables are coming out of the plastic enclosure.


What you want first is a device that integrates a plug that's controllable remotely. For example, I chose a pack of four identical devices that can be controlled via a small radio remote. Each of these devices is basically an on/off switch that can be controlled by a relay located inside the device.


These devices were very cheap ($9.90 for the four devices) and are perfect to hack as they can be easily opened up. The following image shows such a device:


You can take any similar device, the most important thing being that the device is somehow controllable from an electronic system such as a remote control. This is important as we will later insert a relay inside the enclosure to control the switch. Mechanical controllable switches (for example, with only an on/off button on it and no electronics inside) won't work for this project.


Then, you need something to insert inside the device we are going to hack. We first need the "brain" of the system, which is going to be an Arduino board. The problem was that the device I chose for this project was too small to put an Arduino Uno board inside it.


 I, therefore, had to use a smaller Arduino board. I chose to use boards from TinyCircuits, which are some of the smallest Arduino boards available.


I used a microcontroller, USB, and prototype board that you can find at http://tiny-circuits.com/.

Of course, you can use any other small Arduino boards such as Arduino Micro. You can also use an Arduino Mini for this project. Any basic Arduino board that will fit into the device you want to hack will work.


Then, you will need a relay module to control the plug. I used a 5V Polulu relay module, the same that we used in Blog 2, Control Lights from Your Phone or Tablet:


This is a list of the parts used for this blog:

  • TinyDuino processor board (https://tiny-circuits.com/index.php/ tinyduino-processor-board.html)
  • TinyShield USB & ICP (https://tiny-circuits.com/index.php/tiny-shield-usb-and-icp.html)
  • TinyShield protoboard (https://tiny-circuits.com/index.php/tiny-shield-proto-board-1.html)
  • Polulu 5V relay module (http://www.pololu.com/product/2480)


On the software side, you need to have the latest version of the Arduino IDE installed on your computer as well as the aREST library for Arduino, which you can find at the following link: https://github.com/marcoschwartz/aREST


You can install the library by simply extracting the library folder in your Arduino /libraries folder (you will have to create this folder if it doesn't exist yet). You will also need to have a web server installed and running on your computer so that we can use the web interface that we are going to develop at the end of the blog.


Hardware configuration

The first step is to actually open the device you want to hack. The device I used included a lot of electronics inside that I simply removed (we won't need these components anymore), leaving just the important parts: the power plug on both sides of the device and two cables going to both parts of the plug:


These two cables will have to be connected together if we want to get some current to flow into the device that is plugged into the hacked device. To do so and control the plug from the Arduino board, you need to insert the relay module now.


Basically, a relay has three output pins: a common pin named COM, a pin that's normally closed (NC), and another pin that's normally open (NO).


Normally closed means that this pin is connected to the COM pin of the relay when no voltage is applied to the input of the relay. On the other hand, normally open means that this pin is disconnected when no input is applied to the relay.


You need to connect one of the red cables going to the plug to the COM pin of the relay, and the other one to the NO pin of the relay so that the circuit closes when we signal the relay. The following image shows the device at this step:


Then, you need to insert the Arduino board into the device and connect the relay module to the Arduino board. The connections to the Arduino board are really easy: connect the VCC pin of the relay module to the Arduino +5V pin, the GND pin to the Arduino GND, and the SIG pin to the Arduino pin 7.


Now, you can plug a USB cable into your Arduino board so that you can control it from your computer. I also made a small hole in the device that I hacked so that the USB cable can fit nicely when the device is closed. You can now close the device. With the device I used, this is how it looked at the end:

You are now ready to write some Arduino code and test the device that you just hacked!


Controlling the device from your computer

Arduino code

We are now going to build the Arduino sketch we will use to control the relay remotely. This will be based again on the aREST library that will help us handle the request sent from your computer.


This Arduino sketch starts by including the required libraries as follows:

#include <SPI.h>
#include <aREST.h>
Then, we can create the aREST instance:
// Create aREST instance aREST rest = aREST();
Then, in the setup() function of the sketch, we simply start the serial connection so that we can access the board later:
void setup(void)
// Start Serial Serial.begin(9600);
Next, we can handle the requests coming on the serial port by using the following code:
void loop() {
// Handle REST calls rest.handle(Serial);


Now, we can actually test the device you just hacked. Note that the code for this part is available on the GitHub repository of the project at the following location:https://github.com/openhomeautomation/arduino-home-automation/tree/master/

Plug the device into the wall and plug a device inside to test it. For example, I used a simple 30W desk lamp to test my project.


Upload the code for the Arduino board and open the serial monitor inside the Arduino IDE. Make sure the serial speed is set to 9600, and type: /mode/7/o


This should set the pin number 7 as an output. You should be greeted by the following message:

  • Setting pin D7 to output You can now switch the relay with/digital/7/1
  • You should hear the relay click and see the device you are trying to control turn on.
  • You should also have the following confirmation on the serial monitor: Pin D7 set to 1


If this doesn't work, the first thing to check is the connections inside the device you hacked. Disconnect it first from the power plug in the wall and open it again. Make sure that everything is wired correctly according to the previous section.


You can also test the relay independently by plugging the SIG pin in a 5V pin to see if it's working. Finally, also make sure that the serial speed matches with the speed defined in the Arduino sketch.


[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]


Building a graphical interface

Arduino graphical interface

However, it's not convenient to control the hacked device from the serial monitor. We are now going to build a simple interface to control this device. The interface will be really basic and include two buttons: one to set the relay on and the other to set the relay off.


The interface is based on HTML for the interface itself, JavaScript to handle the commands, and PHP to interface with the Arduino board.  The following code will be a walkthrough of the different pieces of the interface.


All the files have to be located inside the same folder at the root of your web server folder. You can find the complete code for this part inside the GitHub repository of the blog.


Let's first see the HTML file that contains the interface itself. Inside the HTML file, the following is the code for a button:

<button class="btn btn-block btn-lg btn-primary" type="button"

id="1" onClick="buttonClick(this.id)">On</button>


Inside the JavaScript file, we first define the communication type and the serial port. This is where you need to change the value of the target to set it to your own serial port. To know which port you need to select, simply go to the Tools menu of your Arduino IDE:


Inside this JavaScript file, this is the code you need to modify:

var target = '/dev/cu.usbserial-A102JJ6G';
var type = 'serial';
When the window is first loaded, we need to first set the relay pin as an output.
This is done using a get command inside the JavaScript file:
window.onload = function() {
$.get( "command.php", {target: target, type: type,
command: "/mode/7/o"} );
The buttons call a function called buttonClick and pass their ID as an argument to this function. For example, this is the code for the ON button:
if (clicked_id == "1"){
$.get( "command.php", {target: target, type: type,
command: "/digital/7/1"} );


You can see that all these commands call a PHP file. This file is responsible for interfacing with the Arduino board. The file starts by receiving the different arguments coming from the interface:

$type = $_GET['type'];

$target = $_GET['target'];

$command = $_GET['command'];


Since we'll always use serial communications via the USB port in this project, I will only provide details for the part responsible for serial communications. We assign the target to the serial_port variable:

$serial_port = $target;
Now, we can define the different parameters of the serial connection with the
Arduino board:
$serial = new phpSerial;
Now, open the connection:
We can then send the following command:
$serial->sendMessage($command . "\r");
$answer = $serial->readPort();
And read the answer (that we won't use in this project):
if ($answer == "") {echo "{\"connected\": false}";} else {echo $answer;}


It's now time to test the interface. Please make sure that all the files of the interface are placed inside a folder on your web server folder, and that the web server is running.


You can now open the HTML file inside the interface folder (usually by typing http://localhost in your web browser), and this is what you should see. Now, try to click on the ON button. You should instantly hear the relay switching, and see the lamp that is connected to the hacked device turn on.


If it doesn't work at this stage, there are several things to check. The first thing is to make sure that the web server is running on your computer.


Also, make sure that you access the HTML file via the localhost folder, and not directly by clicking on the file in your file explorer. Finally, check that the hardware is working correctly by trying to send the commands directly in the Arduino IDE.


You can also get some help on this project by posting your question on the official Arduino forum at http://forum.arduino.cc/. 


So far in this blog, we have used only already-assembled Arduino boards and interfaced them with different sensors and modules to build home automation projects. In the previous blog, we changed things a bit and hacked a commercial device using Arduino.


However, in this last blog of the blog, we are going to take things further and build our own system for home automation. As an example, I will take the design and fabrication of a very simple low-power Arduino board. This board can then be used for home automation projects such as battery-powered motion sensors.


Note that the goal of this last blog of the blog is really to give you a step-by-step method to build your own home automation systems. Therefore, you should not focus on the specific example that is developed in this blog, but more on the overall methodology to design your own systems.


The following will be the major takeaways from this blog:

First, we will choose the required hardware components for the project and install a library dedicated to low-power applications.


Then, we are going to build a prototype of our custom home automation system on a breadboard to make sure it works correctly. We are also going to test the low-power Arduino library to make sure the board will be power efficient.


In the next part of the blog, we will move from the prototyping stage to actually make our own boards. We'll see how to use PCB design software so that you can make your own PCB and then send it to a manufacturer to be built.

Finally, we are going to see how to make a 3D-printed case for your home automation system and fabricate it.


Hardware and software requirements

Let's first see what components are needed for this project. As an example in this blog, I will use a project I have previously worked on, which is a low-power Arduino board. This board has just the bare minimum of components to be usable.


This way, no power is wasted on components that are not necessary when the system is operating, such as LEDs, a USB interface, and so on. This board can then be used in very low-power applications such as motion sensors based on XBee.


The most important component of this project will be the microcontroller itself. The microcontroller is at the heart of all Arduino boards. It is the component that we program every time we write a new sketch.


I based my design on the Arduino Uno board design, so I used the same Atmel ATmega328 controller as the Arduino Uno board. For this project, you will need one of these microcontrollers, which are sold separately.


Please make sure that you are buying one with the Arduino bootloader so that you can directly upload the Arduino code to the microcontroller.


You will also need several smaller components to make the microcontroller work. You will need one 10 uF capacitor, two 22 pF capacitors, one 10k ohm resistor, one 220 ohm resistor, one green LED, and one 16 MHz crystal clock.


You will also need a battery to power up the project. I used a battery pack that can contain two AA batteries (1.5V each) to power the project. You can use the battery of your choice by keeping in mind that the official documentation for this chip says that the voltage should be between 1.8V and 5.5V. However, I really recommend using at least 3 V to power the project.


To program the microcontroller, you will need an external programmer because the project does not integrate a programmer. Instead of using a dedicated programmer, I simply used an Arduino Uno board for this task. 


Finally, you will need a breadboard and some jumper cables to make the connections between the different components of the project.


This is the list of all the parts that were used for this project:

ATmega328 microcontroller with Arduino bootloader (https://www.sparkfun.com/products/10524)
10 uF capacitor (https://www.sparkfun.com/products/746)
2 x 22 pF capacitors (https://www.sparkfun.com/products/8571)
10k ohm resistor (https://www.sparkfun.com/products/8374)
220 or 330 ohm resistor (https://www.sparkfun.com/products/8377)
Green LED (https://www.sparkfun.com/products/9650)
16 MHz crystal clock (https://www.sparkfun.com/products/536)
 2 x 1.5V AA batteries (https://www.sparkfun.com/products/9100)
Breadboard (https://www.sparkfun.com/products/12002)
Male/female jumper wires (https://www.sparkfun.com/products/8431)


On the software side, you will need to download the JeeLib Arduino library to enable low-power operation of your system: https://github.com/jcw/jeelib


To install an Arduino library, simply place the library folder in the /libraries folder of the main Arduino folder.

You will also need to download the EAGLE to design your own printed circuit board (PCB) for this project. You can download it from the following link: http://www.cadsoftusa.com/download-eagle/


To design your own 3D-printed case, you can use OpenSCAD, which is a free design tool. You can find it at the following address: http://www.openscad.org/


Building an Arduino system from scratch

Let's now see how to build an Arduino system on a breadboard using the components we chose.

There are several components to assemble, so the best thing to do is follow the instructions from the following schematic diagram that summarizes all the connections you have to make:


I recommend putting the Arduino microcontroller (ATmega328) first in the middle of the breadboard so you can add the different components around it. This schematic illustrates the placement of the different components:


We can now test the project, just to see if it is working correctly. To do so, we are going to make the LED flash with the Blink sketch that comes with the Arduino IDE.


Testing the Arduino system

It's time now to test the Arduino system. Let's do it in the following way:


First, take off the chip and place it on the Arduino Uno board, which has to be connected to your computer. To remove the chip from the breadboard or the Arduino Uno board, you can simply use your fingernails or the edge of a knife. Of course, make sure that there is no power flowing through the chip whenever you remove it from a board.


Load the Blink sketch that comes with the Arduino IDE and uploads the code to the board. You should see that the onboard LED is going on and off continuously.


Now, disconnect the board from your computer and remove the microcontroller. Put it back on the breadboard and connect the power with the battery pack. You should see that the LED inserted on the breadboard is going on and off.


If that doesn't work, there are several things you can check. First, make sure that you correctly wired the different parts of the project according to the schematics. Then, make sure that the microcontroller has been programmed correctly by checking that the onboard LED of the Arduino Uno board is blinking.


Now, we can also make a test with the JeeLib library to put the Arduino controller in a deep sleep mode when it is not active. Indeed, without specifying anything in the code, the Arduino microcontroller will consume power even if it is not doing anything. We need to declare specific commands in the code to put Arduino into a low-power sleep mode.


Let's now see the code for this part. We are going to see the most important elements of the code. You can find the complete code in the GitHub repository of this blog.


This sketch starts by including the JeeLib library as follows:

#include <JeeLib.h>


To make sure that the Arduino microcontroller is active, we will also make the LED blink. However, between each change of state of the LED, we will put the microcontroller in a deep sleep mode. We first have to define the pin of the LED we want to control:

int led_pin = 13;


We also have to start the watchdog, which is necessary to put Arduino in the sleep mode:

ISR(WDT_vect) { Sleepy::watchdogEvent(); }


In the loop() function of the sketch, we switch the LED on and off, but the important part here is that we use a special function to introduce some delay:



The difference with the delay() function of Arduino is that the Arduino controller is put in the sleep mode during this time, whereas with the delay() function, the chip just waits.


I performed some measurements to show you the difference with and without the library. Without the use of the library, the system was using 6.7 mA when the LED was off. With the use of the library, it was only consuming 43 up, which is a 150x improvement over the first case.


This means that for a system which is not active most of the time (such as a temperature sensor or a motion sensor), it can work for years without changing the battery!


Designing a PCB for your home automation system

Designing a PCB

So far in this blog, we have learned how to prototype an Arduino-based system on a breadboard. We are now going to see how to take an idea from the prototype we built on a breadboard and build our own board from it.


The first step is to design the board on your computer. To do so, I used software called EAGLE, which is widely used to design Arduino-based systems. You can download EAGLE by going to the following page: http://www.cadsoftusa.com/download-eagle/


The first thing you have to do is open the software and create a new schematic. This will take you to a new blank window similar to what is shown in the following screenshot, where you will create your schematics:

In this section of the blog, I want to show you how to build your own board and not build the exact same board I used as an example.


Therefore, I will give you an overview of how to build a board in EAGLE. What you should focus on at this stage is really how to use the most important commands of the software.


The first thing we are going to do is create the schematics of our project. This means choosing the components (called parts) that we want for our project, placing them on the screen, and connecting them together via wires.


The important command you are going to need now is the one to place apart, which is located on the left-hand side menu. Once you click on this icon, you will be taken to a menu where you can select the parts you want to use in your project.


In this menu, you can search for parts you want to use in your project. Whenever you click on a part and click on OK, you will be able to place it on the main screen of your project.


You will also need to draw connections between the different parts of the system. This can be done using the Net function, which you will also find on the left menu.


I placed and connected all the components that I had in the previous section of the project. I also added some connectors (to get access to the pins of the microcontroller, like on the Arduino Uno board) to interface the Arduino controller with the outside world, and also a connector for the battery.


From here, you will be able to do the second step in PCB design: the layout. This is the actual physical representation of your board that will be sent to the manufacturer. You can click on the Layout button on the top menu and EAGLE will ask you if you want to generate the layout automatically. Click on Yes, and you should see the following screen:


From here, your job is to place the different components (that we chose in the previous step when creating the schematic) on the board, arrange them as you want, and route the board. Routing refers to connecting the different components together on the board using copper traces.


This can be done automatically by using the auto-routing functionality of EAGLE. You can see that EAGLE already indicates which components are connected together by displaying thin lines between their pins.


For my example board, I placed all the components first in order to use the least amount of space possible on the board while keeping some space for traces on the board. I then used the auto-routing function of EAGLE to automatically connect all the components on the board according to the schematic.


I also inserted two holes so that the board can be mounted on a case. Finally, I inserted some text in the bottom-left corner of the board. This can be done easily using the integrated Text tool that you can also find inside the menu on the left.


The following is the final result in EAGLE:

You can see that the Arduino controller is located in the middle of the board, surrounded by the IO pins and components that are necessary for the Arduino operation.


The code for this part can be found inside the GitHub repository of the project at the following link: https://github.com/openhomeautomation/arduino-home-automation/tree/master/


Fabricating the board

When the design step is over, it is time to fabricate the board, order the components, and build it. In this section, we are going to see how to do each of these steps.


For the first step, I usually use the services of OSH Park to build my boards in a small series. It's cheap, fast, and you can send your EAGLE design files directly without having to convert them to another format.


You can also use the services from other manufacturers, such as Seeedstudio or Iteadstudio. The link to access the manufacturing services of OSH Park is as follows: https://oshpark.com/


From the main page, it is really easy to get your board fabricated. You just have to upload your EAGLE board file and the website will automatically analyze it. You will then be taken to the following confirmation page:


You will then be asked to enter some more details, and you will be able to order and pay for your board. About two weeks later, you will receive it in your mail.


For the second step, which is ordering the necessary components, I recommend using Newark. They have all the components required for the board I used as an example. The link is as follows: http://www.newark.com/


You have, of course, many alternatives to Newark. You can also use websites such as Mouser, Digikey, Farnell, or SparkFun. On the Newark website, you can easily find the components you need with the main search field.


When you receive the board and components, you can assemble them using a fine soldering iron. For my board, after assembling it, I repeated the same process I used in the previous section. I first programmed the controller using an Arduino Uno board, and then put the controller back on my custom board for testing.


Designing and 3D printing a case for your home automation project

Designing and 3D printing

The third step in designing your own home automation system is to design a custom case for your product. This was a really costly process in the past, as you needed to find a manufacturer for your product and generally produce several thousands of units to have a good price for each unit produced.


Fortunately, 3D printing changed all that. We can now prototype individual systems at a very low cost using this technology. In this section, we are going to see how to make the 3D design of a simple case for our Arduino system. We are also going to see how to send it to a manufacturer so that it can be 3D printed.


And to do so, we are going to use software called OpenSCAD. This is an open source design software where you can actually write code to make your designs.


This is perfect if you are not a designer but more of a coder, and it also allows you to make parametric designs that can easily be modified and shared. You can download OpenSCAD from the following URL: http://www.openscad.org/


When you open a new project in OpenSCAD, the following is what you should get. You can see that there are mainly three parts in the OpenSCAD window. There is some space for code on the left, a 3D view of the object on the right, and a window in the bottom-right corner to print out information about the project.


For example, to make a simple cube of 5 x 5 x 5 mm, you can simply type: cube([5,5,5]);

For the other functions such as the difference between two objects, you can look at the official documentation of the software at the following URL:http://www.openscad.org/documentation.html


For the board I took as an example, I designed a simple case to hold the board still and included a hole for the external connections. It is basically made of the difference between the two cube entities. I added another cube to make the hole on the side, and two cylinders to make the attaches for the board.


The following is one part of the case:

I also designed a cover to be able to close the case using the same principles. It is based on the union of two cube objects, so it fits nicely in the main part of the case.


The following is the result in OpenSCAD:

When your design is finished, you will have to export it to a special file format so that it can be 3D printed. To do so, go to File | Export and export the file as STL, which is the format required by many 3D printers and 3D-printing manufacturers.


The code for this part can be found inside the GitHub repository of the project at the following URL: https://github.com/openhomeautomation/arduino-home-automation/tree/master/blog7


Once your design is ready, you have to produce it. There are many ways to do this. Of course, one option is to print the case using your own 3D printer if you have one. If you don't, you will have to use one of the many 3D-printing services available on the Web.


I recommend using Shapeways. I don't have any commercial dealings with them, it's just that their interface is very user-friendly and their prices are competitive. You can go to the following web address for more information: https://www.shapeways.com/


You will be prompted to create an account and to upload your first file. The Shapeways interface will analyze the file and check whether it can be printed without potential problems. You will also get a price estimate for your design. The following is what I got with the case I uploaded:


You can now choose your material and order; after a few weeks, you will receive your design. You can then assemble everything: the PCB, components, and 3D-printed case. There are also other services you can use to 3D print your own case for the project. Another one I used is Sculpteo: http://www.sculpteo.com/


You can also check out your local fab lab if there is one. They can usually print your designs for you at a much cheaper rate. To find out if there is one around where you live, check the official list at the following URL: http://wiki.fablab.is/wiki/Portal:Labs

Wi-Fi Arduino shield

Arduino Home Automation

This blog is going to be really exciting. "Why?", you ask. You are going to control the lights, fans, and other electrical appliances, using your smartphone. In addition to this, we will also be implementing speech recognition! You can literally control your home using your words. 


For this project, we are going to use a Wi-Fi Arduino shield connected to your home's Wi-Fi network in order to communicate with your smartphone or computer (running speech recognition), with which you will be able to switch appliances on or off. If you have not worked with high voltages before, you need to be very careful while proceeding with this blog. 

Connecting the Wi-Fi module

This project, Home Automation, is split into two blogs to balance the length of each blog. The blog is further split into the following sections:

  • Connecting the Wi-Fi module
  • Using relays to control appliances
  • Communicating through a terminal


You have been promised before that you would learn many new things about the Arduino world. In the previous project, our communication was mainly through Bluetooth. Here, we will utilize a different approach: Wi-Fi.


Wi-Fi is increasingly becoming more popular than Bluetooth when it comes to the Internet of Things or having a centralized network because it has a much greater range than Bluetooth and it can also be used to access the Internet, which ultimately increases its range to the entire planet.


What's the drawback? Well, using Wi-Fi modules in projects such as home automation is a relatively new idea; hence, the modules are more expensive than their Bluetooth counterparts. However, they are much more powerful. Let's move on to the prerequisites.



This topic will cover what parts you need in order to create a good home automation system. Obtaining software will be explained as the blog progresses.

The materials needed are as follows:

1x Arduino UNO board or Arduino MEGA

1x USB cable A to B (also known as the printer cable)

1x CC3000 Wi-Fi shield

1x 5V relay (Arduino compatible)

1x Two-way switch replacement (for your switchboard)

1x Regular type screwdriver

1x Multimeter

1x 9VDC 2A 2.1mm power adapter

1x Wireless router (with accessible settings)

1x Smartphone

1x PC with a microphone

10x Connecting wires

1x 5V 4 Channel relay (optional: Arduino compatible)

4x Two-way switch replacement (depending on the number of relays)

Arduino Channel relay

The software required is as follows:

  • Putty (terminal)
  • cmd (iOS)
  • UDP TCP Server Free (Android)
  • BitVoicer (speech recognition)


If you want to control your home with just your smartphone and not use the physical switches, then you do not require the 'two-way switch', but as you go through this blog, you will understand why a two-way switch is listed here.


The 4 channel relay is used to control four appliances. It is up to you as to how many appliances you want to ultimately control, and by the necessary number of channel relays.


 Here, Arduino MEGA is preferred if you want to control more than five appliances. Everything is the same as UNO, except the MEGA has much more pins. However, in this project, we are going to use an Arduino UNO.


Connecting the Wi-Fi module

In this case, the Wi-Fi module is the CC3000 shield. Shields are basically ready-to-go modules that can be directly attached to the Arduino with any extra wiring. This makes them quite convenient to use. In this section, you will learn about connecting the Arduino to your home Wi-Fi network and linking it to the Internet.


The CC3000 Arduino shield

CC3000 Arduino shield

This shield is a relatively new means of communication for Arduino. The CC3000 chip is made by Texas Instruments, with the goal to simplify internet connectivity for projects such as the one we are going to make in this and the following blog.


Connecting the shield to the Arduino is probably the simplest task in this entire blog. Make sure the male header pins of the shield align with the female header pins of the Arduino board (UNO or MEGA), and then gently mount them together. You will have something like this:


If you would like to know more about how the chip works, you should refer to this page (at http://www.ti.com/product/cc3000) at the Texas Instruments website. When you visit this page, it will tell you that it is recommended to use the newer CC3200 version of the chip. 


However, at the time of writing this blog, there were no easy-to-use Arduino compatible CC3200 modules; hence, we will stick to CC3000 because it has a lot of community support, which really helps if you come across some unprecedented problem.


The thing that you need to be wary about with this particular shield is that your USB cable from the computer will sometimes not be able to completely meet the power demands of the shield.


Hence, we make use of the power adapter when using it for the project. To learn more about this and other frequently asked questions, check out https://learn.adafruit.com/adafruit-cc3000-wifi/faq.


Testing the shield

Since you have already connected the shield, there is no need for any circuit diagrams just yet. However, we do have to install an Arduino library. You have mastered this by now, haven't you?


Before that, you will have to install an older version of Arduino to your computer. This is because the newer versions are not completely compatible with the CC3000. 

Go to http://www.arduino.cc/en/Main/OldSoftwareReleases and install 1.0.6 or a lower version of the Arduino IDE.

Once that is done, as before, go ahead and install the CC3000 library by Adafruit from https://codeload.github.com/adafruit/Adafruit_CC3000_Library/ zip/master. 

As before, extract the contents of the ZIP file to C:\Users\<user>\ Documents\Arduino\libraries.

Rename the folder as Adafruit_CC3000 or CC3000_WIFI, something that is short and recognizable. 

Now, open up the older Arduino IDE. Go to File→Examples→Adafruit_CC3000→buildtest:


This code can be run directly, with only a few changes. Go to line 46 of the code and take a look at the following four lines of code:

The only things that you will have to change in this code to make it work are myNetwork, myPassword and WLAN_SEC_WPA2.


Change network to your Wi-Fi name/SSID and myPassword to your password. Do not forget the double quotation marks because they are string type constants that require quotations so that the software can recognize them as constants.


If you are not using a WPA2 type security WLAN_SEC_WPA2 should be changed. You can check this by going to your network settings. Go to Network and Sharing Center in the control panel or right-click on the Wi-Fi tray icon and select the same:


Then, click on Wireless Network Connection and select Wireless Properties.

Go to the Security tab and you will have something like this:


The Security type field tells you what sort of security access your router is using. It does not matter if it is WPA2-Personal or WPA2-Enterprise. As long as you identify the first segment of the field (WPA2 in this case), you will know what you have to change in your Arduino code.


Once you have changed the parameters for the Wi-Fi in the code, go ahead and connect the Arduino to your computer using the USB cable. If your computer has a USB 3.0 port, use that. This is because the USB 3.0 provides more current than the USB 2.0. If not, don't fret, this program will still run without any external power.


Once the program has been uploaded, open up the Serial Monitor and change the baud rate to 115200. If for some reason the board is acting weird, go ahead and connect the 9V 2A power adapter to power the Arduino.


If everything worked well, you will see something like this:

If you watched your Serial Monitor while doing this, you will have noticed that it takes quite some time to acquire the DHCP settings. For example, IP Address is the unique number given by the router to allow CC3000 to connect to the router. However, what happens sometimes is that the router is restarted (power outage), thus the IP address might change.


Since ultimately we will not be always monitoring the Serial Monitor for IP Address, let us give it a constant, one that solves both the problems, namely, the long time it takes to get DHCP settings and the possibility of the IP address changing. Use the latest driverpatch_X_XX.ino example to update the firmware if it isn't updated already.


Load the buildtest_staticIP.in file that came with this blog. The main difference in this code is that we have uncommented a part of the code (highlighted in the following image) and changed the IP address to match the preceding image:


In this case, (192, 168, 1, 8) has been used because this is the IP address the router allotted to cc3000 when it was first connected. You should use the IP address that your cc3000 was allotted. Do not forget to change myNetwork and myPassword to reflect your router's configuration. If you did it correctly, you will see the following in your Serial Monitor:


Isn't the DHCP so much faster now? You can even try restarting your router, and running the code again will give you the same IP address. If you ever want to go back to the dynamic IP, run the default build test example that comes with the Adafruit CC3000 library.


Note that the antenna of the CC3000 is not as powerful as that of your smartphone or computer. So, it is recommended that the Arduino and CC3000 is placed as close to the Wi-Fi as possible. The build-test program is your go-to code for making sure that the CC3000 shield is working as expected. In a similar fashion, go ahead and try the GeoLocation and InternetTime programs under examples. Pretty neat, huh?


Using relays to control appliances


Here, we learn what relays are and how they can be used to control everyday electrical/electronic appliances. Also, to make them useful, we will connect them to the Arduino and create a Blink.ino program, except this time it will be your lamp that will be turning on and off.


Understanding the basics of the relay

A relay is basically an electrical device, usually consisting of an electromagnet, which is activated by a passing of current in one circuit to open or close another circuit. You could think of it as a switch that requires current to turn on or off.


Why can't we simply connect a pin of the Arduino to the switchboard, and switch the fan on or off like we do with an LED? Well, an Arduino can output only 2-5V, whereas the fan or any other appliance in your house uses around 200-250V that comes from the electricity grid. This number is different depending on where you are from.


Also, we cannot simply connect the Arduino to the switch of the fan because that 200-250V will get fed into the Arduino, which would instantly burn the chip, or worse. Since the relay uses an electromagnet to flip a switch inside it, there is no physical contact between the circuitry of the Arduino and the circuitry of the fan; hence, it is safe and very effective.


Diving deeper into relay functionality

If you have a good look at the relay (preceding image), you will notice that the three male header pins on the left are to be connected to the Arduino and the three 'screws' are to be connected to an electronic appliance.


We need to understand how these two parts work with each other so that we can program the Arduino as we require. The left part will simply be connected to an Arduino OUTPUT pin, which we can control (turn ON and OFF—HIGH and LOW) just like an LED. This, in turn, flips a switch on the right side of the relay.


Imagine wires are connected to each of the three screws (right side) of the relay. This depiction will show how the circuitry will look like on the right side of the relay comprising of its three pins/screws (Arduino LOW → Relay OFF). 


When the relay state is 'OFF', the top screw and the middle screw of the relay form a closed circuit (completed connection), allowing the current to pass through it. Also, as you guessed it when the relay state is 'ON', the bottom two screws will form a closed circuit.


We use a two-way switch instead of a simple switch because a two-way switch enables us to control the appliance through the Arduino and the physical switch independently. This means that you can turn ON a lamp via the Arduino, and physically flip the switch to turn it off.

Next, we will move to actually programme a relay.


Programming a relay

Programming a relay

Programming a relay is almost as easy as programming an LED. You can leave the CC3000 Wi-Fi shield mounted onto the Arduino and use the pins on it to connect to the relay. Go ahead and build the following circuit:


The connections from the Arduino to the relay are as follows:

  • GND → GND
  • 5V → VIN
  • D12 → IN1

Since we are just going to test the relay for now, open Arduino and fire up the blink LED example, and instead of using pin 13 for the LED, just use pin 12 (connected to IN1 of the relay). Also, increase the delay time from 1000 to 3000. Basically, it will look like this:

void setup() {
// initialize digital pin 12 as an output. pinMode(12, OUTPUT);
// the loop function runs over and over again forever void loop() {
digitalWrite(12, HIGH); // turn the LED on (HIGH is the voltage level)
delay(3000); // wait for a second
digitalWrite(12, LOW); // turn the LED off by making the voltage
delay(3000); // wait for a second


Run the program. If the upload is successful and if you are lucky enough to have an LED on the relay board, you will see it go on and off in three-second intervals. You will also hear a clicking sound whenever the LED turns on and off.


This is the sound of the physical motion of a metallic component due to the electromagnetism that completes the circuit. So there you go – this is a simple working example of a relay.


Now, fetch your multimeter and set the parameter measuring knob to resistance 200Ω. See the following image if you are unsure:

Now, holding the two wires of the multimeter touch the uninsulated ends to each other. You should get a reading of 0 Ω. This is because there is virtually no resistance between the two contact points (the two wires). Use the two wires to touch the top and the middle screws of the relay.


You will notice that when the relay is turned off, the resistance between the top two screws will be almost 0 Ω. This implies that the circuit is complete (take a look at the previous images of the relay schematic for a diagrammatic representation).


When you touch the bottom two screws of the relay when the relay is turned ON, the resistance will again be zero and the bottom circuit will be complete.


If you do the same when the relay is turned OFF, the resistance will be infinite, but the multimeter will display 1. If your relay behaves in an opposite manner, make a note of that and we will change the circuit diagram accordingly.


Testing the relay with a light bulb

Testing the relay

"One more test? Seriously?" Yes. Before we begin programming communications into the system, we need to ensure that the relay would actually work in your home or whatever experimental environment you chose.


Remember, I told you that you would be requiring an electrician if you haven't played doctor with your switchboard? This is one of those times where an electrician will be very helpful.


You're not being asked to take help from the electrician just because you will be working with high voltages, but also because if this is your first time messing with electrical circuits, you would want to know what wire goes where. 


We are going to use the relay to switch on and off a light (bulb or tube light) in your house, just like how we turned on and off an LED in Blog 2, Digital Ruler. Firstly, power off your Arduino.


Keep in mind that since this is just a testing phase, this will not be a permanent connection. We are doing this before adding the communication network so that if we come across a bug, it will not be because of the relay connection.


Now, with the electrician's help (unless you know exactly what you are doing), build the following circuit with the two-way switch working as a replacement for a simple switch on your switchboard:


When you are completely sure that the circuit you have created is as described in the preceding image, connect the Arduino with the same program, which we loaded in the previous subsection, to the USB hub or the 9V 2A power adapter, and power it on.


What do you see? The light goes on for three seconds and goes off for three seconds. It is literally a larger LED that goes on and off, controlled by the Arduino.


If this did not work, check the circuit again. Make sure that the connection to the two-way switch is done properly. Also, make sure that the relay is working as it is supposed to. If it still does not work, try unplugging the Arduino from the power supply, remove the CC3000 shield, and then connect it to the relay.


If it worked, isn't that awesome? You just created a setup where an Arduino can control a switch in your house. Next, we will learn how to communicate with the Arduino and, in turn, the relay using the Wi-Fi network.


Communicating through a terminal

Home Automation

There is one more dilemma that we have to solve in order to have complete control over the electronic appliance. If we create a digital ON and OFF switch that when set to ON sends a turn ON signal to the relay, the problem is that if the physical switch is already ON, the ON signal of the digital switch will end up actually turning OFF the appliance.


"If the appliance is already ON, why would I send a turn ON signal?" Okay, think about this. Both the switch and the relay are ON, but the bulb would actually be off if you look at the two-way switch and the relay image previously shown. Now, if you want to turn ON the bulb through the relay, you actually have to send an OFF signal.


Pretty confusing, isn't it? To solve this, we will use a flag or a status variable that stores the current state of the relay. This will help us solve logical issues such as the one stated before. 


Make sure your router is working as expected. Then, plug in the Arduino into the USB port and open the home_automation_simple.ino file that came with this blog. As before, change myNetwork and myPassword to the ones corresponding to your router.


There is also one major change that is made in this code. We have moved the relay (IN1) pin from D12 to A0 and modified the code accordingly. Repeated testing has proven that the setup is much more stable when it uses the analog port because it consumes a lot less power. Change D12 → IN1 to A0 → IN1 before proceeding.


Finally, upload that program to the UNO. Once it is uploaded, open up the Serial Monitor. After some time, your Serial Monitor should look something like this:


Since we are using static IP, connecting to the network will be pretty quick. If it did not connect, try getting the Arduino closer to the Wi-Fi router, run it again, or try powering it through the 9V 2A adapter. Remember the static IP address that you have set for your CC3000. We will need that address pretty soon.


The title of this subsection says Communicating through a terminal. So, we need to use a terminal. In this blog, we will use Putty. Download putty.exe from http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html. 


You could also just copy it from the Files folder of this blog. It is directly executable so you can place it on a desktop or someplace where you can access it easily. Once you have downloaded it, launch it.


Change the Connection type to Telnet. The Port should have automatically changed to 23. If not, change it to 23. Change the Host Name to the one that we have on the Arduino Serial Monitor. It may not be in your case. Type CC3000 Relay Chat in the Saved Sessions field and click on Save.


Now, instead of typing these details over and over again, you can simply load the saved configuration. Make sure your computer is also connected to the same network. Then, select Open.


Here are the commands you can use:

  •  1 – Relay ON
  • 0 – Relay OFF
  • q – quit

You need to hit Enter after each command, for it to be sent. The window will look like this after a couple of tries:


Do not mind the empty spaces between the left edge and the 1s and 0s. Your relay is also turning ON and OFF based on the input, right?


Good! What was unprecedented (and a bit hilarious) when this code was written was that, if you input something like 1010101010101010 to the terminal, you would end up with this (the following image) and a rapid clicking noise:


It is highly recommended to avoid this because it might be a bit too much for the Arduino to handle. Do not do this when the relay is connected to an electric appliance. It could damage both the appliance and the UNO.


Press q to safely close the connection. Speaking of which, go ahead and create the previous circuit, which you created, that connects the Arduino to the bulb (or tube light) and try this code.


Again, it is not a bad idea to get help from your electrician while making the connections. Open the terminal and try turning your bulb on. Works beautifully, doesn't it?

  • "I can only turn one appliance ON and OFF!"
  • "How do I control my home, using my smartphone?"
  • "You also spoke about speech recognition! Where is that?"


Do not worry. We will deal with all of these in the next sections.

However, there is a cheap trick you can use to control the bulb, using your smartphone.


If you are using iOS, download an app called Telnet Lite from the App Store; for Android users, download Simple Telnet Client from the Google Play Store. You can use any Telnet app for this task, but these are the two that have been tested.


Configuring the app is similar to that of Putty and is self-explanatory. Reset the Arduino by pressing its reset button. Use the power adapter to power it this time, and disconnect it from the USB port. Give it sufficient time to connect to the router. Then, launch the app.


So, what are you waiting for? Connect to the corresponding IP address and press 1 or 0! You will see a screen resembling that in the preceding image on your Android device. 


The great thing about the chat server program is that you can control the appliance with both the terminals running on your computer and smartphone at the same time. Go ahead and try it!


Communicating via a smartphone

Communicating via a smartphone

Unfortunately, creating an app for this purpose is too complicated to be within the scope of this blog. However, we will be using apps that are already out there to communicate with our so far mini home automation system.


The following subsections will deal with Android and iOS devices, not necessarily just smartphones. Yes, that means you can even use your tablet to control the appliances.


Android devices

Open the Google Play Store on your Android device, and look for UDP TCP Server:

Download and install it. On opening it. Go to UDPSettings. This is reached by first selecting the three vertical squares icon on the top-right. Change the setting:


Do not forget to use your IP address, which may differ from the one in the preceding image. Go back to the main page and select + New Template. Call it something like Home Automation.


 Just as you did for accessing settings, access the Button Settings. We are now going to redo the main page. We will get rid of all the useless buttons and keep only two.


One button will be to turn ON the light (relay), and another to turn it OFF. Use the following parameters:


Go back to the main page and you will have something.

Restart the app and make sure the Arduino is connected to the router. Then, go on and try pressing the two buttons. Works blissfully, right? If you want to try out other apps, just look for TCP on the Play Store and try them, now that you know how to configure them.


iOS (Apple) devices

iOS (Apple) devices

Go to the App Store and look for an app called .cmd: Download it. Then, open it:

Go to Settings, which is the bottom-right icon: Tap on Manage Destinations and on the top-right icon. Select Add New Connection.Then, fill the page with the following details:


As before, remember to use your Arduino IP, which may not be the same as in the preceding image. Then, tap on Save. Go back to Settings. For the screen title, type something like Home Automation.


Then, press Manage Control Buttons. As you did for creating a new destination, click on the top-right icon and select Add new command. You have to do this twice to add two buttons (one for ON and another for OFF).


For the connection, tap the Assign Selection option and use the connection that we just made. Do not forget to save the button each time. Then, select the Remote icon on the bottom-left. You will have something like the following:


Once you are sure that the Arduino is connected to the router, go ahead and play with the switches. They should work just as expected. If it didn't work in the first try, try again.


For some reason, the app is shy sometimes to work the first time. However, if it worked the first time, it's remarkable, isn't it? This means you didn't have to break a sweat—the same code for Arduino worked for all the cases!


Implementing speech recognition This section deals with using existing, powerful speech recognition tools that will aid us in adding a layer of verbal communication with the Arduino.


The software


There are tons of speech recognition software that can be used for this project. Some are better than the others. The software we will be using for this project is called BitVoicer.


Mind you, the software is not free, but it isn't very expensive. However, after using it, you will understand why this software was chosen. You will also need a good microphone for this project. Most laptops come with inbuilt microphones. You could also use your phone's earphones if they came with a microphone.


Go to http://www.bitsophia.com/BitVoicer.aspx and purchase the program. Download and install it. If the download is a bit slow, be patient and let it finish downloading. Then, run the program as an administrator.


Configuring the software

The default language that is used in BitVoicer is English (US). Even if English is your primary language, go through the following step:


Go to File → Additional Languages…. A new window will open, showing other languages that can be recognized by the BitVoicer software. If it showed you an error message saying 'BitVoicer requires elevated privileges,' restart the program as an administrator. 


You will notice that sometimes there are different varieties of the same language. This refers to the different nature of the language spoken and written in different parts of the world. For example, UK English is quite different from US English.


There is also a change in accent between the two regions. So, pick a region that best suits your language and accent. Then, click on Install.


  • Now, open Preferences via File → Preferences.
  • What are schemas? the schema is a file that is used by BitVoicer. This is similar to .ino associated with Arduino.
  • Move the output folder to someplace that you will remember. You can put it in a new folder named VoiceSchemas in your Arduino directory.
  • Change the language to the one that you had installed. If you didn't, leave the default one as it is. For this project, we will be using TCP/IP communication. Change the settings on the Preferences window.

The only things that will be different for you are the IP address that should match the IP address of the Arduino, the language if you chose a different one and the default output folder.


The key parameters that you need to take note of are as follows:

Acceptable confidence level: Setting this to 100 percent will require a perfect pronunciation of the programmed text. Since we have set this to 60 percent, the software will take it easy on us and understand us better, even with tiny errors in the pronunciation.


Minimum audio level: This sets a threshold for how loud you will have to speak for the program to begin recording you. You might have to change this number, later on, depending on your microphone. Now, hit Save.


Creating a voice schema

voice schema

1. Go to File → New and you will see the following window:

2. Change Default Command Data Type to Char.

3. Click on Add New Sentence two times to create two new programmable sentences. Your window will look like the following:

4. In the first empty sentence field, type switch on the light.


5. In the second empty sentence field, type switch off the light.

6. In the empty Command field at the very bottom (scroll if you cannot see it), which is corresponding to the first sentence, type 1 (without quotations).

7. In the one below this, type 0. We will add more commands later. 


Check everything and make sure everything is in order. Then, go back to your Arduino. Use the same code that we used previously to control the relay through a terminal. Power the Arduino via the power adapter, and wait for it to connect to your network. Again, make sure that your computer is on the same Wi-Fi network.


Testing out the software

When everything is set, press the Start button in BitVoicer. Scroll right and you will see the Activity notification box. If everything worked correctly. If you do not see any green in the Audio Level bar, your microphone isn't working; so, go back and check its connections.


Now try it. Use your beautiful voice to say switch on the light. If it is not loud enough, try again. If you hear a click from the relay, you know that it worked! Now, say switch off the light and you will hear another click.


How cool is that? You used speech to control your Arduino. If you go ahead and complete the circuit with an actual appliance and try the same thing again (in case you had unplugged it from the relay like me), it will work in the same way as it did when you were controlling it via a terminal, except this time your speech is doing the job.


Notice how in the preceding image the speech was rejected the first time because either the speech was inaudible or indistinguishable for the software to comprehend. It was basically not confident about what was said, so it did not send any information to the Arduino.


Making a more reliable schema

Now, we will edit the schema to allow the different ways to say switch on/off the light. Press Stop when done, and save this schema (chat_server_simple.vsc came with this blog, in case you lost the saved file). Then, go to File → New.


The default command data type should now be Char. However, if it is still Int, change it to Char. Follow these steps (or just open chat_server_simple2.vsc):

  • 1. Add one new sentence.
  • 2. Change the radio button from Single to Option.
  • 3. Type turn and click on the + sign.
  • 4. Type switch and click on the + sign.
  • 5. Click on Add New Item.
  • 6. Change the radio button from Single to Option.
  • 7. Type on and click on the + sign.
  • 8. Type off and click on the + sign.
  • 9. Click on Add New Item.
  • 10. Type the light and click on the + sign.
  • 11. Type the bulb and click on the + sign.
  • 12. Check whether your sentence matches the following image:
  • 13. Scroll all the way down to Sentence Anagrams. Change all the data types to Char, if they are not set as Char.
  • 14. Type 1 into the Command field for any sentence that pertains to turn ON the light/bulb.
  • 15. Type 0 into the Command field for any sentence that pertains to turn OFF the light/bulb.


Once this is done, again, make sure your Arduino circuit is complete and that the Arduino is connected to the Wi-Fi. Then, hit Start. Also, try all the new commands that you just created and watch them do wonders. Beautiful, isn't it?


One last aspect of the BitVoicer software is the activation word:

If you would like to use this, click on the check mark and type something that you want to use (Jarvis, Cortana, and so on); set Activated Period to however long you wish.


Suppose you set Activated Period to 300 seconds (5 minutes), this would mean that you have to initially say something like <activation word> + turn on the light.


However, for the next 300 seconds, you don't have to keep using the activation word. Learn to program some AI into it, and watch it blow up your home and free itself from its human masters.


This is slightly beyond the scope of this blog. We have finally finished implementing the communications network. The only thing left to do is expand this to control more devices. This would involve using more relays and tweaking the codes/app layouts/schemas to correspond to it.


Upgrading the home automation system

Arduino Home Automation upgrade

Now that we understand how each means of communication works independently, we will begin controlling more than one device. Let's say, for the sake of this blog, we are going to control the light and fan in your room, and the light and television in the living room. We are going to use only four home appliances for this section.


Once you understand how it works and what we changed from using just one appliance, you will be powerful enough to add more appliances to your home automation system.


Controlling multiple appliances

Controlling four appliances implies that we need four relays. Instead of getting four single 5V relays, buy yourself a 4-channel 5V Arduino-compatible relay as shown in the following image:


Since you have already learned how relays work, there is nothing new here, except that you will be using just one GND pin and one VCC (VIN) pin, which is really convenient. Before creating the entire circuit, let's just connect the Arduino to the 4-channel relay, and ensure that they work and can be controlled independently.


So, create the following circuit:

The connections from the Arduino to the 4-channel relay are as follows:


5V → VCC

A1 → IN1 (your room's light)

A2 → IN2 (your room's fan)

A3 → IN3 (living room's light)

A4 → IN4 (living room's television)

The parentheses represent where each relay is eventually going to be connected. These can, however, be connected to whatever is convenient in your case. 


Launch Arduino IDE, connect the Arduino, and open the home_automation_ complete.ino file. Upload that code to your Arduino.


The fundamental difference between this code and the previous one is the use of a switch function. It is a more condensed form of the multiple if statements, which you are familiar with by now. In the program home_automation_simple, we are going to switch the following if statements to switch statements:


if(ch == '1')
analogWrite(A0, 255);
//digitalWrite(12, HIGH);
chatServer.write("RELAY ON \n");
relay_status = 1;
} else if(ch == '0')
analogWrite(A0, 0);
//digitalWrite(12, LOW);
chatServer.write("RELAY OFF\n");
relay_status = 0;
else if(ch == 'q')
//Serial.println(F("\n\nClosing the connection")); chatServer.write("DISCONNECTED"); cc3000.disconnect();
} }
Following is the new switch statement:
case '1':
analogWrite(light_room, 255);
chatServer.write("ROOM LIGHT ON\n");
case '2':
analogWrite(light_room, 0);
chatServer.write("ROOM LIGHT OFF\n");
case '3':
analogWrite(fan_room, 255);
chatServer.write("ROOM FAN ON\n");
case '4':
analogWrite(fan_room, 0);
chatServer.write("ROOM FAN OFF\n");
case '5':
analogWrite(light_main, 255);
chatServer.write("MAIN LIGHT ON\n");
case '6':
analogWrite(light_main, 0);
chatServer.write("MAIN LIGHT OFF\n");
case '7':
analogWrite(tv_main, 255);
chatServer.write("TV ON\n");
case '8':
analogWrite(tv_main, 0);
chatServer.write("TV OFF\n");
case 'q':
Can you see how it is more condensed and neater? Of course, we could have used more of the if statements, but with this code, it is much easier for you to add another application as follows:
case 'a':
analogWrite(something, 255);
chatServer.write("something ON\n");
case 'b':
analogWrite(something, 0);
chatServer.write("something OFF\n");


Yes, that's right, you don't have to stick to just numbers.

Via the terminal Now, launch Putty. The only thing that is different is the commands, and they are as follows:

1: Light in your room ON

2: Light in your room OFF

3: Fan in your room ON

4: Fan in your room OFF

 5: Light in the living room ON

 6: Light in the living room OFF

7: Television ON

8: Television OFF

q: Disconnect


Go ahead and try it out. You'll find yourself with a screen like the following:

The terminal will probably be the seldom-used mode of communication. Nevertheless, it is the best one for testing and debugging. Of course, now you can hear only the clicking sound of the relays when they go ON and OFF, but when they are finally connected to their electronic counterparts, they will still work the same.


Via the smartphone (Android)

Open the UDP TCP Server free app and create a new template by pressing the + NEW TEMPLATE button. Then, go to Button Settings and change the parameters. Similarly, you need to create buttons 7 and 8 (cut off in the preceding image).


When you go back to the main page, it will look like the following: Go ahead and try the buttons out. Make sure you set the right commands corresponding to the correct relay.


Via the smartphone (iOS)

smartphone Testing

You already know how to do this. Launch .cmd. You just have to add six more buttons with a total of eight (nine if you add a disconnect button). If you are reusing the single relay template, remember to change its OFF button's command from 0 to 2.


Your main page and buttons page after making some changes will look like the following:

Try all the buttons and make sure they work. And there you have it! The smartphone communication phase is complete. Via the speech recognition software (BitVoicer). 


Launch BitVoicer and load the home_automation_complete.vsc schema that came with this blog. You can (and are recommended to) change these sentences to your liking, or add more options as we did in the second BitVoicer example (turn on the lights and switch off the bulb, remember?).


Once you are happy with the control phrases, press Start and test it out. Do the relays obey their master? If so, well we are done with all the tests. Now, we will complete the circuit.


Unplug the UNO. Take a look at it. Do not let the number of wires confuse you. All the wires are insulated.


The only wires that are connected to each other are the ones at the main line and the ground (neutral) line. The relay (connected to the Arduino) needs to be placed in a location close to the router, but it is also convenient enough to connect all the wires.


It is recommended that you keep your Arduino + CC3000 + relay setup close to at least one switchboard (perhaps the one in your room). The following image is just to show you where and how the connections go, but it is not an exact representation of how it will be.


Physically placing the Arduino board close to a switchboard will make the wire-connections to that switchboard and the relays short and neat. All nonground wires from an appliance are connected to one side of the switch on the switchboard. The other wire connected to a simple switch will be the main (power).


Each relay has to be connected to a two-way switch, which would mean that you would have to replace a simple switch with a two-way switch for this setup to work.


As before, be very careful while handling high voltages. Be patient and take your time. If you are controlling a single room, you will not have wires going around, but if you want to control appliances in different rooms, this is the most feasible option.


Alternatively, if your budget allows, you can get another UNO and a CC3000 shield and connect them near another switchboard.


Power the Arduino through the 9V 2A power plug and let it connect to the network. Begin speech recognition and start the app on your smart device. What are you waiting for? Press, tap, and speak away! Feeling Tony Stark-ish yet? If not, you should.


This is a milestone that you have reached! It was a wonderful moment when I first got this to work sometime before working on this blog. It's truly spectacular and you may feel like you can do anything and build anything now.


To take things further, you can buy yourself an 8-channel relay and an Arduino MEGA board, which would allow you to control even more appliances.

Connect it to your computer so that you neither have to be close to your computer nor have to yell, for the speech recognition software to work.