Deploy your home automation application with Ubidots and realize the value that the Internet of Things can bring to your home or office.
In the following tutorial, we describe how you can automate your home or office with an ESP8266 (our project focused on light control) and then incorporate Google Assistant to control devices with voice commands.
Requirements:
DHT11 Sensor Grove (Temperature & Humidity)
Relay Grove
Electrical female connector
Electrical male connector
Electrical cables
Light / AC Powered Device
1. Hardware Assembly
Here at Ubidots, we do not like to cut the cords of our appliances so we recommend that you don't either. To control any device without cutting its AC power cord, we instead recommend creating your extension cable and splicing in a relay as the midpoint between the appliance and the AC wall outlet.
This relay cable will act as the device's ON / OFF switch. This is the relay wiring connection map.Follow the table below to establish the connections between the sensors and the NodeMCU ESP8266:
IMPORTANT NOTE: We recommend protecting your hardware with a case to prevent damage from external factors like dust, heat, and humidity.
Assemble hardware containing extension cable with a spliced in the relay, the NodeMCU Grove Shield, the NodeMCU ESP8266, and the DHT sensor.
Follow the table below to establish the connections between the NodeMCU ESP8266 with the DHT Sensor and Relay: the AC power plug for the wall outlet and its respective socket for the device being controlled.
2. Programming with the Arduino IDE
If not done yet, download the Arduino IDE.
Open the IDE and select Files → Preferences
Add the URL below into the Additional Board Manager URLs field. You can add multiple URLs by separating them with commas.
NOTE: If you're a Mac user, you will notice that the interface is different from Windows; you should install this driver if you cannot install the NodeMCU ESP8266.
2. Open and Install the ESP8266 board in the Boards Manager: Tools -> Board -> Boards Manager and easily find the board by typing “ESP8266” in the search bar.
3. Now select the NodeMCU 1.0 board from Tools -> Board menu
4. Define or double check the Port of your PC which the device is communicating with. Go to Tools -> Port: -> Select the port
Ensure your IDE Upload Speed is 115200 by going to Tools -> Upload Speed → 115200
5. Download the Ubidots MQTT ESP library from our GitHub repository. To download the library, click the "Clone or download" button and select "Download ZIP".
6. Now back in the Arduino IDE and upload the Ubidots MQTT library.
Go to Sketch -> Include library -> Add .ZIP library and choose the Ubidots MQTT ESP library. If properly uploaded, you get the response: "Library added to your libraries.“
8.Repeat the same process to download and install the DHT Sensor Library.
9. Install the library: PubSubClient
Sketch/Program -> Include Library -> Library Manager and install the "PubSubClient" library.
10. Close and open again the Arduino IDE.
3. Programing Time & Ubidots Visualization
Once your ESP8266 is set up, we can post and get data from Ubidots to monitor and control your home appliances.
Copy and paste the following code in the Arduino IDE. Don’t forget to customize the Wi-Fi SSID and password and your Ubidots Token.
/****************************************
* Include Libraries
****************************************/
#include "UbidotsESPMQTT.h"
#include "DHT.h"
/****************************************
* Define Constants
****************************************/
#define TOKEN "xxxx" // Your Ubidots TOKEN
#define WIFINAME "xxxx" //Your SSID
#define WIFIPASS "xxxx" // Your Wifi Pass
#define DEVICE_LABEL "esp8266";
#define DHTPIN D1 // pin we're the sensor connected to
#define RELAY D3 // pin we're the relay connected to
// Uncomment whatever type you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
Ubidots ubiClient(TOKEN);
WiFiClient client;
DHT dht(DHTPIN, DHTTYPE);
/****************************************
* Auxiliar Functions
****************************************/
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i
Serial.print((char)payload[i]);
}
if ((char)payload[0]=='1'){
digitalWrite(RELAY, HIGH);
}
else{
digitalWrite(RELAY, LOW);
}
Serial.println();
}
/****************************************
* Main Functions
****************************************/
void setup() {
// put your setup code here, to run once:
ubiClient.ubidotsSetBroker("industrial.api.ubidots.com"); // Sets the broker properly for the business account
ubiClient.setDebug(true); // Pass a true or false bool value to activate debug messages
Serial.begin(115200);
pinMode(RELAY, OUTPUT);
dht.begin();
ubiClient.wifiConnection(WIFINAME, WIFIPASS);
ubiClient.begin(callback);
if(!ubiClient.connected()){
ubiClient.reconnect();
}
char* deviceStatus = getUbidotsDevice(DEVICE_LABEL);
if (strcmp(deviceStatus, "404") == 0) {
ubiClient.add("light", 0); //Insert your variable Labels and the value to be sent
ubiClient.ubidotsPublish(DEVICE_LABEL);
ubiClient.loop();
}
ubiClient.ubidotsSubscribe(DEVICE_LABEL,"light"); //Insert the Device and Variable's Labels
}
void loop() {
// put your main code here, to run repeatedly:
if(!ubiClient.connected()){
ubiClient.reconnect();
ubiClient.ubidotsSubscribe(DEVICE_LABEL,"light"); //Insert the Device and Variable's Labels
}
// Read humidity
float humValue = dht.readHumidity();
// Read temperature as Celsius (the default)
float tempCValue = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float tempFValue = dht.readTemperature(true);
ubiClient.add("temperature-c", tempCValue); //Insert your variable Labels and the value to be sent
ubiClient.ubidotsPublish(DEVICE_LABEL);
ubiClient.add("temperature-f", tempFValue); //Insert your variable Labels and the value to be sent
ubiClient.ubidotsPublish(DEVICE_LABEL);
ubiClient.add("humidity", humValue); //Insert your variable Labels and the value to be sent
ubiClient.ubidotsPublish(DEVICE_LABEL);
ubiClient.loop();
delay(1000);
}
char* getUbidotsDevice(char* deviceLabel) {
char* data = (char *) malloc(sizeof(char) * 700);
char* response = (char *) malloc(sizeof(char) * 400);
sprintf(data, "GET /api/v1.6/devices/%s/", deviceLabel);
sprintf(data, "%s HTTP/1.1\r\n", data);
sprintf(data, "%sHost: industrial.api.ubidots.com\r\nUser-Agent:esp8266/1.0\r\n", data);
sprintf(data, "%sX-Auth-Token: %s\r\nConnection: close\r\n\r\n", data, TOKEN);
if (client.connect("industrial.api.ubidots.com", 80)) {
client.println(data);
} else {
return "e";
}
free(data);
int timeout = 0;
while(!client.available() && timeout < 5000) {
timeout++;
if (timeout >= 4999){
return "e";
}
delay(1);
}
int i = 0;
while (client.available()) {
response[i++] = (char)client.read();
if (i >= 399){
break;
}
}
char * pch;
char * statusCode;
int j = 0;
pch = strtok (response, " ");
while (pch != NULL) {
if (j == 1 ) {
statusCode = pch;
}
pch = strtok (NULL, " ");
j++;
}
free(response);
return statusCode;
}
Now, verify that your code is correct by clicking the check button in the Arduino IDE above the editor.
Next, upload the code into your NodeMCU. To do this, choose the right-arrow icon beside the check icon.
2. Go to the Device section of your Ubidots account, and visualize the device previously created —ESP8266— receiving temperature and humidity data.
3. As the device is already connected and sending data to Ubidots, let's create a dashboard and widgets to control the lamp’s light from a web or mobile dashboard.
4. Go to your Ubidots account and go to Data->Dashboards and create a new dashboard by clicking the plus icon.
5. Create a control widget to switch on/off the lamp. It is required by our sample code that the variable to control be named "light," or modify the sample code above to reflect your desired variable label.
Now you have a basic control application for turning on and off lights, that you can access from a desktop or a mobile phone by downloading the Ubidots explorer app in the Playstore.
Yet, we can go far beyond this. Ubidots also lets you create custom visualizations such as gauge indicators, line charts, bars, and metrics to extract insights from the conditions of your assets, like your Lamp’s temperature and humidity. If you want to learn more about Ubidots dashboards and these custom visualizations, we recommend the following articles:
For this tutorial, the IoT dashboard looks like this:
5. Set up a recipe in IFTTT to control your system using Google Assistant
Last but not least, you will learn to control lights by using voice commands with IFTTT, a web service that lets you connect applications and automate tasks, and Google Voice Assistant.
Click on the profile avatar and select Create to a new Applet.
3. Click on “+ This” (trigger) and select Google Assistant. Then, select the first option “Say a simple phrase” as the trigger:
4. In the following step, you need to fill the fields with the Google Assistant custom voice commands. For instance:
What do you want to say? “Turn the lamp on”
What's another way to say it? (optional) “Turn on the lamp”
And another way? (optional) “Turn the light on”
What do you want the Assistant to say in response? “Ok, turning on the lamp”
Language English
Click Create Trigger
5. With the Trigger already set, it’s time to create the action “+ that” and search for WebHooks as action service:
6. Fill the fields of the WebHooks setup with the following parameters:
Method: POST
Content-Type: application/json
Body:
{"light": 1}
To finish, just press Create action:
7. Once the trigger and the action are already configured and properly connected, you can go to your Google Assistant and say “Turn the lamp on” and see how your lamp is turned on
8. Now repeat the same process to create the applet to turn off the lamp. All the previous steps provided are the same, the only differences are the ones mentioned below:
Trigger configuration (Google Assistant): switch “on” for “off”
Action configuration (WebHooks): The body should be
{"light": 0}
instead of{"light": 1}
9. Once both applets are created and connected, you’re done!
Now, you have an impressive smart home application for remotely controlling your lights by using Ubidots and Google Assistant!
Other users also found helpful...