Tuesday, August 8, 2017

IOT- weather station with NodeMCU and deep sleep mode

In this tutorial, we are going to monitor the temperature and humidity level and send to thingspeak interface for analysing. In this process, we are going to use NodeMCU as a hardware and thingspeak interface for data collection with addition of the DeepSleep feature. 
(Deepsleep feature puts controller(ESP8266) in the sleep mode to reduce the power consumption)
Interface with Thingspeak is easy to work with, You need thingspeak API key to get an access of server and data transfer. On the hardware side, you required DTH11 connected to NodeMCU.  

Basic you need to know,
A) NodeMCU integration with Arduino IDE
B) Basic hardware
a.      NodeMCU
b.      Breadboard
c.       DTH11 sensor
d.      Battery (for standalone device)
e.      Internet connection 😉
       C) Thingspeak – open source IOT platform to store and retrieve data over HTTP protocol. It enables the creation of sensor logging applications, location tracking applications and a social network of things with status updates.

To start with thingspeak, visit: https://thingspeak.com/, and creat your account to start with.


Create an account and log in,


Go to create a channel from top left menu and click on new channel.



Add a channel name and description, field1 is temperature and field2 is humidity (It will be defined by Arduino code, so please make sure we keep a same field name as above).
Save this setting and make a channel.



After you finish, Go to channel name and channel setting.


You will see a channel ID, Percentage of complete (Used) and other information as defined.





Click on API key to collect your write API key number, It will allow NodeMCU to write on this page.

Hardware design


Connect NodeMCU to the breadboard with DTH sensor and resistor as shown above.

DTH11 sensor: Pin number D1 with 10K resistor to VCC.

Breadboard connection:

Software:
ESP8266 chip provides 3 configurable sleep modes. We can choose and configure the sleep mode as required.
The 3 sleep modes are:
Modem-sleep
Light-sleep
Deep-sleep



To enable a deepsleep mode, We can call the interface function system_deep_sleep to immediately enable Deep-sleep. In this mode, the chip will turn off Wi-Fi connectivity and data connection; only the RTC module is still working, responsible for periodic wake-ups. but to awake a chip from deepsleep we need to do some modification in a hardware like.



You need to connect D0 pin (Ping number 16) to reset, so whenever you counter reach out deepsleep time, it will enable a reset. Meaning it will reset a chip and code will work in normal mode.

Code:
Before you start, make sure your Arduino IDE has installed ESP8266 board with thingspeak library.
Thingspeak library for Arduino and ESP compatible:

Arduino Code:
#include <DHT.h>
#include <ESP8266WiFi.h>

// replace with your channel’s thingspeak API key,
String apiKey = "your API";
const char* ssid = "Wifi network name";
const char* password = "password";

const char* server = "api.thingspeak.com";
#define DHTPIN 5 // what pin we’re connected to
const int sleepTimeS = 900; // second 15min (60*15) connect reset with 16 number pin for wake upcall

DHT dht(DHTPIN, DHT11,15);
WiFiClient client;

void setup() {
Serial.begin(115200);
delay(10);
dht.begin();

WiFi.begin(ssid, password);

Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

}

void loop() {

float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

if (client.connect(server,80)) { 
String postStr = apiKey;
postStr +="&field1="; // As field1 is temperature at thingspeak site
postStr += String(t);
postStr +="&field2="; // As field2 is humidity at thingspeak site
postStr += String(h);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius Humidity: ");
Serial.print(h);
Serial.println("% send to Thingspeak");

Serial.println("deepsleep");
ESP.deepSleep(sleepTimeS * 1000000);  //deepsleep defination 

}
client.stop();
Serial.println("Waiting…");

}

.................................................................................................................................................................................


After some days. A screen shot from Thingspeak.



Test results 
Before Deepsleep feature, device was taking current around  84.1 mA (Including NodeMCU circuits with DTH11)


After DeepSleep mode (almost 5.5 time less than normal mode)


Final Circuit with battery connection, As a stand alone device.





Wednesday, June 28, 2017

IFTTT notification with Temperature and humidity value_DTH11

Switch works as a trigger to send data. it could be motion sensor, vibration sensor, moisture sensor, etc. we can send three values using IFTTT trigger, name as Value1, Value2, Value3.

Ingredient you need during this tutorial,
1) NodeMCU integration with Arduino IDE
2) Basic hardware
a.    NodeMCU
b.    Breadboard
c.    Switch
d.    10K resistor x2
e.    Jumper wires.
f.     DTH 11 sensor (Or module)
g.     Internet connection 😉
3) Thinger.io – open source IOT platform  
4) IFTTT 
IFTTT is free platform that helps you do more interaction with all your apps and devices. To accomplish multiple task, please sign up in a free service called IFTTT, which stands for “If This Then That”
You can cross connect your IOT device with notification, Email, tweet, Facebook, etc…

To start with IFTTT,
Create a free IFTTT account.
Go the official site: https://ifttt.com/ and click the “Sign Up” button in top of the page.



Once you "Sign-up", you see…



In the top raw, select the "My applets" or create one.

Click on "this" to make trigger activity.
In our case we want to use a NodeMCU with button to make a trigger.

Select "Maker webhooks" It will allow you to make the IOT hardware integration.



I created an event name "Temp_sensor" (you need in Arduino code) written in the box. Do remember this name you will need this in future for the testing.


So It will show you if button pressed (On NodeMCU)  then what…!!!



It has multiple action services, which will allow you to connect through possible services with simple selection. In our-case we are sending notification in this tutorial. (You need to download an app for notification service)

In this Notification dialog, please add the message you want to see. Also please add ingredient call "value1", "value2",
"Value 1" stands for the temperature, and "Value 2" stands for the Humidity in our case.



Compete with the action by a click "create action".



So once it is finished, Check by clicking a "check now" button, It should not give you any error during this.

Now, Go back to search on the top, write "Maker Webhooks", It will show you below options.

Now go in to "setting", and copy a "URL" and past in the internet browser. It will show you your active key with event box.



Write an "event name" in the box Temp_sensor in our case and click on the test button at bottom.
This will work as a trigger in absents of a trigger hardware and gives you an indication of system working. (you should receive a notification by doing this)

Now IFTTT will not get the value directly from the Hardware, So we required one more interface call thinger.io, which will support us to transfer DTH value to IFTTT. (It works as inter-mediator)

To configure thinger.io interface. Go to https://thinger.io/ and register yourself.



Once you sign in, you see.


You need to add device and endpoints to make this work with nodeMCU.
click on the Device and add Device ID (Required in Arduino Code) and Device Credentials could be any name (Required in Arduino Code).

Once you click “Add device” it will add this device in the thinger.io platform. Now go to endpoints and add required details as below.



Select IFTTT maker channel trigger and add IFTTT details like event name and IFTTT key.



So Internet configuration over, Now let finish hardware connection and Arduino Coding.

Hardware design:




Connect NodeMCU to the breadboard with switch and resistor as shown above.
Switch: Pin number -D2
DTH11 sensor : Pin number D1

Breadboard connection:



Software:

Before you start, make sure your Arduino IDE has installed ESP8266 board with thinger.io library.

You can download thinger.io library from:
https://github.com/thinger-io/Arduino-Library

Arduino Code 1:
It will send you a notification with Temperature and Humidity data when you press a button.
------------------------------------------------------------------------------------------------------------------------------------------------------
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <ThingerWifi.h>
#include "DHT.h"

#define USERNAME "User name" // Your login name from thiner.io
#define DEVICE_ID "NodeMCU_DTH11" // Your device ID from thinger.io
#define DEVICE_CREDENTIAL "lorem_ipsum" // your crefential from thinger.io

#define SSID "WIFI network"
#define SSID_PASSWORD "WIFI password"

int pin = 4;

#define DHTPIN D1
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

ThingerWifi thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

void PINStatus() {
  digitalWrite(BUILTIN_LED, LOW);
  pson DTH_value;
  DTH_value["value1"] = dht.readTemperature();
  DTH_value["value2"] = dht.readHumidity();
  thing.call_endpoint("DTH_post", DTH_value);
  digitalWrite(BUILTIN_LED, HIGH); /// it will be on untill data gets on the thinger.io site
            
}


void setup() {
   
 dht.begin();
 pinMode(pin, OUTPUT);
 attachInterrupt(digitalPinToInterrupt(pin), PINStatus, FALLING);

 pinMode(BUILTIN_LED, OUTPUT);
 digitalWrite(BUILTIN_LED, HIGH);
 
 thing.add_wifi(SSID, SSID_PASSWORD);

  // resource for reading sensor temperature from API
 thing["dht11"] >> [](pson& out){
 out["humidity"] = dht.readHumidity();
 out["celsius"] = dht.readTemperature();
 out["fahrenheit"] = dht.readTemperature(true);
 };
}

void loop() { 
  thing.handle();
}

------------------------------------------------------------------------------------------------------------------------------------------------------ 

Arduino Code 2:

It will give you a notification at every hour with temperature and humidity data, also works when you press a button.

#include <SPI.h>
#include <ESP8266WiFi.h>
#include <ThingerWifi.h>
#include "DHT.h"

#define USERNAME "User name" // Your login name from thiner.io
#define DEVICE_ID "NodeMCU_DTH11" // Your device ID from thinger.io
#define DEVICE_CREDENTIAL "lorem_ipsum" // your crefential from thinger.io

#define SSID "WIFI network"
#define SSID_PASSWORD "WIFI password"

int pin = 4;

#define DHTPIN D1
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

ThingerWifi thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

unsigned long previousMillis = 0;      // to know when to post the temperature
unsigned int minutes_interval = 60;              // variable in minutes for posting the temperature

void PINStatus() { 
  digitalWrite(BUILTIN_LED, LOW);
  pson DTH_value;
  DTH_value["value1"] = dht.readTemperature();
  DTH_value["value2"] = dht.readHumidity();
  thing.call_endpoint("DTH_post", DTH_value);
  digitalWrite(BUILTIN_LED, HIGH);
             
}


void setup() {
    
 dht.begin();
 pinMode(pin, OUTPUT);
 attachInterrupt(digitalPinToInterrupt(pin), PINStatus, FALLING);

 pinMode(BUILTIN_LED, OUTPUT);
 digitalWrite(BUILTIN_LED, HIGH);
  
 thing.add_wifi(SSID, SSID_PASSWORD);

  // resource for reading sensor temperature from API
 thing["dht11"] >> [](pson& out){
 out["humidity"] = dht.readHumidity();
 out["celsius"] = dht.readTemperature();
 out["fahrenheit"] = dht.readTemperature(true);
 }; 
}

void loop() {  
  thing.handle();
  unsigned long currentMillis = millis();
  if(minutes_interval>0 && currentMillis - previousMillis >= minutes_interval * 60000) 
  {
    previousMillis = currentMillis;   
    PINStatus();
  }
  
}

-----------------------------------------------------------------------------------------------------------------------------------------------------


Please make sure you customize the highlighted area in CODE

So when ever you press a button, it will send an notification with temperature and humidity value or every hour

Execution video: