Home Automation with Google Assistant and Alexa under $10 (PART 1)

Home Automation with Google Assistant and Alexa under $10 (PART 1)

by Ravi Singh
14 comments 8 views
Home Automation Under $10 Compressed

This is going to be one of the most interesting guides I have ever created. It’s about Home Automation and Internet-of-things (IoT). Today in this guide, we are going build a Home Automation device under $10 USD or INR 700. The best part is that this Home Automation device that we are going to build, works well with Google Assistant and Alexa.

I can also control my devices and monitor my room temperature as well as humidity level via a highly intuitive Android app. I am currently controlling 6 devices in my room. What’s more is that you can perform actions based on certain conditions while using sensors. For instance, turn on the Air Conditioner when the temperature reaches 30 C—more on that in the next post.

For now, let’s start building our first IoT home automation device.

Steps to build a Home Automation device that works with Google Assistant & Alexa

Things You Need

Total value: $9.51 or INR 694 (with free shipping worldwide)

For faster delivery, buy from Amazon.com ( US & other countries) or Amazon.in (India)

Step 1. Setting up The PC and the Arduino IDE for ESP8266

In Mac, go to Arduino>Preferences and add the above URL

Preferences

Add URL JSON ESP8266 Arduino IDE

  • Click ‘OK‘ and then go to Tools> Board>Boards Manager

Board Manager

  • Search and install ESP8266 by ESP8266 Community package

Install ESP8266 Board

  • After installation, close the Window and go to Tools>Boards>select ‘NodeMCU 1.0 (ESP 12E-Module)’

Select NodemCU

  • And for now, we are done. Let’s connect the ESP8266 to the system
  • If it isn’t detected, install the driver package
  • Now go to File>New. Press CTRL+S and choose a location where you want to save your project
  • Give your project a name such as Home Automation with Google Assistant & Alexa. Save it

Step 2: Add Libraries

  • In Arduino IDE, go to Sketch>Include Library>Manage Libraries

Manage Libraries

  • In the search bar, type Adafruit MQTT and install Adafruit MQTT Library by Adafruit

Adding Library MQTT

  • Then type DHT and install DHT sensor library by Adafruit

DHT Sensor Library

Step 3: Setup Adafruit Account

  • Visit Adafruit.com and signup for an account. It’s completely free. No strings attached

Create Adafruit Account

  • Then, go to io.adafruit.com and sign in with Adafruit credentials
  • Click ‘Dashboards‘ in the left panel
  • Click Actions drop-down and click ‘Create a New Dashboard
  • Enter a Name such as ‘HomeAutomation‘ and add a description such as, ‘Controlling home devices and appliances with Google Assistant and Alexa.’

Create Dashboard

  • Click ‘Create
  • Now under Dashboards, you will see HomeAutomation. Click on it to open the HomeAutomation Dashboard
  • Click ‘+’ icon at the top

Create New Block

  • Choose a block. For instance, select ‘Toggle’ block for controlling light

Select Toggle Switch

  • Enter Feed Name as Relay1 (you can name it anything you want) and click ‘Create block

Choose feed and click Next Step

  • Then select the feed Relay1 and click ‘Next Step
  • Enter the Block Title such as Light and Enter Button On Text and Button Off Text as 0 and 1 or ON and OFF respectively

Finish Creating Block feed

  • Repeat the Step and add more block for your Lamp and Ceiling Fan or any other device you wish to control. Name the feeds as Relay2 and Relay3
  • Also, enter them appropriate Block Title

Repeat and Create 3 Block Feeds

NOTE: With NodeMCU, you can control up to 13 devices as it has 13 General Purpose Input/Output (GPIO) pins.

Also, to sense temperature, we need to add a block for Temperature and Humidity.

  • Click ‘+’ icon at the top and choose Line Chart

Select Line Graph

  • Create two feeds with name Temperature and Humidity

Create Temp and Humidity and Select both

  • Select both and click ‘Next Step
  • In the Block Settings, enter ‘Block Title‘ and put 0 in Y-axis minimum and 100 in Y-axis maximum and click ‘Create Block

Finish Create Temp and Humid Block

  • Now click ‘key‘ icon at the top right and copy the AIO key. This is the password to connect apps to the Adafruit IO. So keep it safe

Get AIO Secret key

  • Now go back to Arduino Sketch and follow the next step

Step 4: Create a New Project in Arduino IDE

  • Go to File>New
  • Copy the following code and paste it into your project
//Google Assistant Home Automation
#include <ESP8266WiFi.h>π
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>


// pin connected to DH22 data line


#define Relay1 D0
#define Relay2 D1
#define Relay3 D2
//#define DHTTYPE DHT22
#define DHTPIN D4
#define DHTTYPE DHT11 // DHT 11


//WLAN Details
#define WLAN_SSID "YOURWIFINAME" // Your SSID
#define WLAN_PASS "PASSWORD" // Your password

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER "io.adafruit.com" //Adafruit Server
#define AIO_SERVERPORT 1883 
#define AIO_USERNAME "Replace with Adafruit Username" // Username
#define AIO_KEY "PasteAiokeyHere" // Auth Key

// DHT sensor
DHT dht(DHTPIN, DHTTYPE);

//WIFI CLIENT
WiFiClient client;

Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

Adafruit_MQTT_Publish temperature = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
Adafruit_MQTT_Publish humidity = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");
Adafruit_MQTT_Subscribe Light = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay1"); // Feeds name should be same everywhere
Adafruit_MQTT_Subscribe Lamp = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay2");
Adafruit_MQTT_Subscribe Fan = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay3");

void MQTT_connect();

void setup() {
  
// initialize dht22
dht.begin();
  
Serial.begin(115200);
  

pinMode(Relay1, OUTPUT);
pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT);

  
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();

Serial.println("WiFi connected");
Serial.println("IP address: "); 
Serial.println(WiFi.localIP());
 
mqtt.subscribe(&Light);
mqtt.subscribe(&Lamp);
mqtt.subscribe(&Fan);

}
void temperatureAndHumidity()
{

float humidity_data = (float)dht.readHumidity();
float temperature_data = (float)dht.readTemperature();

// By default, the temperature report is in Celsius, for Fahrenheit uncomment
// following line.
// temperature_data = temperature_data*(9.0/5.0) + 32.0;

// Publish data
if (! temperature.publish(temperature_data))
Serial.println(F("Failed to publish temperature"));
else
Serial.println(F("Temperature published!"));
Serial.print("celsius: ");
Serial.print(temperature_data);
Serial.println("∞C");


if (! humidity.publish(humidity_data))
Serial.println(F("Failed to publish humidity"));
else
Serial.println(F("Humidity published!"));
Serial.print("Humidity: ");
Serial.print(humidity_data);
Serial.println("%");

// Repeat every 10 seconds
delay(5000);
  
}
void loop() {
 
MQTT_connect();


Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(20000))) {
if (subscription == &Light) {
Serial.print(F("Got: "));
Serial.println((char *)Light.lastread);
int Light_State = atoi((char *)Light.lastread);
digitalWrite(Relay1, Light_State);
      
}
if (subscription == &Lamp) {
Serial.print(F("Got: "));
Serial.println((char *)Lamp.lastread);
int Lamp_State = atoi((char *)Lamp.lastread);
digitalWrite(Relay2, Lamp_State);
}
if (subscription == &Fan) {
Serial.print(F("Got: "));
Serial.println((char *)Fan.lastread);
int Fan_State = atoi((char *)Fan.lastread);
digitalWrite(Relay3, Fan_State);
}
    
}
  
}

void MQTT_connect() {
int8_t ret;

if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT... ");

uint8_t retries = 3;
  
while ((ret = mqtt.connect()) != 0) {
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 2 seconds...");
mqtt.disconnect();
delay(2000); 
retries--;
if (retries == 0) {
while (1);
}
}
Serial.println("MQTT Connected!");
  
}
  • Press CTRL+S, enter the project name and choose a save location
  • Click ‘Save
  • After saving the sketch code, enter the Wi-Fi SSID & Password. The SSID is case sensitive so keep it accurate. You can get the help of your Android Wi-Fi scanner. Simply Tap on the Wi-Fi network and the SSID will be displayed
  • Then enter the Adafruit username and AIO key you copied earlier. Our sketch is now ready to flash

Paste Username and AIO key in the code

Step 5: Flashing the Custom Firmware to ESP8266 (NodeMCU)

  • To flash the firmware to the ESP8266, connect the ESP8266 based Nodemcu to the PC using the Micro USB cable and go to ‘Tools>Boards’.
  • Select ‘NodeMCU 1.0 (ESP-12E Module)’ from the Boards and ensure the following options are selected.Select Port and Config
  • Select the Port and then click Upload
  • Wait for a while until the firmware is being flashed.

Step 6: Connecting the Wires

Now that the firmware is flashed, time to wire the hardware. So, we will first connect the relay and then the DHT22 Sensor as per the following schematic

Home Automation Fritzing

Explanation: So basically we have connected the Relay input to D0, which we named Relay1 in the code. We defined D4 as the DHT22 data input pin and connected it to Data pin of DHT22

Similarly, D1 and D2 to Relay2, and Relay3. Adding Relay2 and Reay3 is optional.

We also connected the power to DHT22 taken from the 3V output and GND of Nodemcu. There are two 3v and GND terminals in NodeMCU and you need to connect them as shown in the diagram

Once done, turn on the power and make sure Wi-Fi is working

Open the com/serial port and check if the NodeMCU is able to connect to the configured Wi-Fi and able to communicate with our Adafruit MQTT server

Testing and it works

Then we connected the relay outputs to our Electric appliances existing switched as shown in the below illustration. We haven’t modified anything in our existing switch controls, just connected the relay switch terminals to them.

Relay Connections

Now we can turn off mechanical switch and power on our the HomeAutomation device to control the appliances.

The good thing about the setup is that your existing mechanical switches will work as intended.

Click Here to continue with PART 2 of DIY Home Automation With Alexa and Google Assistant

It covers setting up Google Assistant, Alexa, and Android app.

DISCLAIMER: *The post contains affiliate links and when you buy using those links, we may get some commission. This will help us pay for our servers and maintenance cost.

14 comments

massimo December 26, 2018 - 3:49 pm

I have done all, but dont work.
First, It is necessary install “adafruit_sensor.h” too.
the nodemcu is connected to adafruit account, but dont appear “got…” etc..
And the command on adafruit dont work.
Can you give me any suggest?
thanks you

Reply
Henry Kane January 11, 2019 - 8:33 am

Check WiFi credentials and WiFi signal strength should be decent. Then, open the COM port at baud rate 115200 and check if the NodeMCU is connected to WIFi. Alternatively, log in to your WiFi router and check if a new device is connected to the router.
And yes, adafruit_sensor.h is important to include. I think there is an issue with connectivity with one of the channels i.e WiFi or Adafruit. Check credentials you entered and also, the firmware is uploaded successfully.

Reply
Daniel Serban January 25, 2019 - 1:01 am

Hello. I’ve followed the tutorial, all works great, i have managed to connect alexa with adafruit and esp but the command to the relay doest work.
It seems that on both ON and OFF command the result is 0 at this line:
int Light_State = atoi((char *)Light.lastread);
Thanks in advance.

Reply
Ravi Singh January 27, 2019 - 11:22 am

Check Adadfruit setup. And if there’s 0 in both, you will get 0 in the COM

Reply
nishant February 11, 2019 - 9:55 pm

when i am compiling the code it shows this(down)

Arduino: 1.8.7 (Windows Store 1.8.15.0) (Windows 10), Board: “NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200”

home_automation:9:29: error: Adafruit_Sensor.h: No such file or directory

#include

^

compilation terminated.

exit status 1
Adafruit_Sensor.h: No such file or directory

This report would have more information with
“Show verbose output during compilation”
option enabled in File -> Preferences.

someone please help me

Reply
Ravi Singh February 12, 2019 - 9:13 am

Make sure you have install Adafruit Unified Sensor library. Go to library manager and search ‘unified’ and install the library. Then compile the code.

Reply
nishant February 12, 2019 - 3:34 pm

nodemcu is not connecting to my wifi. i have given correct ssid and password. what to do ??

Reply
Ravi Singh February 15, 2019 - 8:27 am

Sorry for the delayed response. Here’s the code that you can use.
When the device will turn on, it will try to connect to last remembered WiFi. And if not connected, it will create a Access Point. Open your device WiFi settings and connect to ‘AutoConnectAP’ SSID. Password is password
Then open Chrome or any web browser on your phone or PC and enter 192.168.4.1 in the address bar
There, you have to tap on ‘Configure WiFi’
Select the available WiFi and enter the correct password
Tap on ‘Save’. That’s it.
Your IoT device will connect to the selected WiFi if the entered password is correct.
This is smart as you can connect it to any wifi network and don’t need to hard code the WiFi credentials.

I will update the guide as well.

/Google Assistant Home Automation
#include π
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include
#include
#include
#include
#include
#include

// pin connected to DH22 data line

#define Relay1 D0
#define Relay2 D1
#define Relay3 D2
//#define DHTTYPE DHT22
#define DHTPIN D4
#define DHTTYPE DHT11 // DHT 11

//WLAN Details
//#define WLAN_SSID "YOURWIFINAME" // Your SSID
//#define WLAN_PASS "PASSWORD" // Your password

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER "io.adafruit.com" //Adafruit Server
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "Replace with Adafruit Username" // Username
#define AIO_KEY "PasteAiokeyHere" // Auth Key

// DHT sensor
DHT dht(DHTPIN, DHTTYPE);

//WIFI CLIENT
WiFiClient client;

Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

Adafruit_MQTT_Publish temperature = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
Adafruit_MQTT_Publish humidity = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");
Adafruit_MQTT_Subscribe Light = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay1"); // Feeds name should be same everywhere
Adafruit_MQTT_Subscribe Lamp = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay2");
Adafruit_MQTT_Subscribe Fan = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay3");

void MQTT_connect();

void setup() {

// initialize dht22
dht.begin();

Serial.begin(115200);

pinMode(Relay1, OUTPUT);
pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT);

//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//reset saved settings
//wifiManager.resetSettings();

//set custom ip for portal
//wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

//fetches ssid and pass from eeprom and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
wifiManager.autoConnect("AutoConnectAP");
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();

//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");

// Connect to WiFi access point.
/*Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();

Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());*/

mqtt.subscribe(&Light);
mqtt.subscribe(&Lamp);
mqtt.subscribe(&Fan);

}
void temperatureAndHumidity()
{

float humidity_data = (float)dht.readHumidity();
float temperature_data = (float)dht.readTemperature();

// By default, the temperature report is in Celsius, for Fahrenheit uncomment
// following line.
// temperature_data = temperature_data*(9.0/5.0) + 32.0;

// Publish data
if (! temperature.publish(temperature_data))
Serial.println(F("Failed to publish temperature"));
else
Serial.println(F("Temperature published!"));
Serial.print("celsius: ");
Serial.print(temperature_data);
Serial.println("∞C");

if (! humidity.publish(humidity_data))
Serial.println(F("Failed to publish humidity"));
else
Serial.println(F("Humidity published!"));
Serial.print("Humidity: ");
Serial.print(humidity_data);
Serial.println("%");

// Repeat every 10 seconds
delay(5000);

}
void loop() {

MQTT_connect();

Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(20000))) {
if (subscription == &Light) {
Serial.print(F("Got: "));
Serial.println((char *)Light.lastread);
int Light_State = atoi((char *)Light.lastread);
digitalWrite(Relay1, Light_State);

}
if (subscription == &Lamp) {
Serial.print(F("Got: "));
Serial.println((char *)Lamp.lastread);
int Lamp_State = atoi((char *)Lamp.lastread);
digitalWrite(Relay2, Lamp_State);
}
if (subscription == &Fan) {
Serial.print(F("Got: "));
Serial.println((char *)Fan.lastread);
int Fan_State = atoi((char *)Fan.lastread);
digitalWrite(Relay3, Fan_State);
}

}

}

void MQTT_connect() {
int8_t ret;

if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT... ");

uint8_t retries = 3;

while ((ret = mqtt.connect()) != 0) {
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 2 seconds...");
mqtt.disconnect();
delay(2000);
retries--;
if (retries == 0) {
while (1);
}
}
Serial.println("MQTT Connected!");

}

Reply
Ravi Singh February 15, 2019 - 8:31 am

If code in comment is not clear, follow this link: https://pastebin.com/1GcpNTMq

Reply
priti February 13, 2019 - 4:52 pm

my relay is not switching channels. what can i do ??
please help me
thanks in advance

Reply
Ravi Singh February 15, 2019 - 8:28 am

Please help me understand the exact issue. Did you mean your relays are not turning ON?
Do you see any info on the COM port. Please check and revert.

Reply
yon mudi August 7, 2019 - 5:32 am

hello,, i have problem ‘” Arduino: 1.8.3 (Windows 7), Board: “NodeMCU 0.9 (ESP-12 Module), 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200”

Board nodemcu (platform esp8266, package esp8266) is unknown

Error compiling for board NodeMCU 0.9 (ESP-12 Module).

This report would have more information with
“Show verbose output during compilation”
option enabled in File -> Preferences.

help please

Reply
Ravi Singh August 7, 2019 - 6:54 am

Choose NodeMCU 1.0

Reply
yon mudi August 7, 2019 - 1:21 pm

now programmable.
however the wifi name hasn’t changed and the password isn’t saved.
Likewise the wifi connection is not connected to the mobile & MQTT DASH

Reply

Leave a Reply

[script_25]

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You may also like

TechPosts Media, A Technology Media Company – All Right Reserved. Designed and Developed by PenciDesign

DigitalOcean Referral Badge

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.