Dhrumil Makadia
Published © CC BY

Monitor Your Room/Office Safe From Fire or Not on Desktop

Using Wemos D1, GSM module, MQ5/MQ6 sensor and IoT platform (ThingsIO.AI). Here it will give message on your phone also when fire detected.

IntermediateProtip1 hour6
Monitor Your Room/Office Safe From Fire or Not on Desktop

Things used in this project

Hardware components

Wemos D1 Mini
Everything ESP Wemos D1 Mini
×1
Arduino GSM shield V2
Arduino GSM shield V2
×1
Grove - Gas Sensor(MQ2)
Seeed Grove - Gas Sensor(MQ2)
×1
Relay (generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1
Water Pump (Spray)
×1

Software apps and online services

ThingsIO.AI

Story

Read more

Schematics

Diagram

Gas leakage veaa6ucboh

Step By Step Process

Code

Code

Arduino
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

int sms_count=0;
int redLed = D5;
int buzzer = D6;
int smokeA0 = A0;
// Your threshold value
int sensorThres = 60;
int openclose = 0;
int redled = 0;

int count=0,i,m,j,k;


//////////////////////////////////////// ALL DECLARATIONS for CLOUD //////////////////////////////
const char* host = "api.thingsio.ai";                                 // OR host = devapi2.thethingscloud.com
const char* post_url = "/devices/deviceData";       // OR /api/v2/thingscloud2/_table/data_ac
const char* time_server = "baas.thethingscloud.com";             //this is to convert timestamp
const int httpPort = 80;

char timestamp[10];

WiFiClient client;
  


/////////////////////////////////////////////////////////////////////////////////////////////////////////
void configModeCallback (WiFiManager *myWiFiManager) 
{
  Serial.println("Entered config mode");             //*-*-*-*-*-*-*-*-*-*-*-*-*-*if control enters this function then net is not connected
  Serial.println(WiFi.softAPIP());                  // "WiFi.softAPIP() is for AP" , "WiFi.localIP() is for STA",
                                                                
  Serial.println(myWiFiManager->getConfigPortalSSID());             //if you used auto generated SSID, print it
}
/////////////////////////////////////// TIMESTAMP CALCULATION function///////////////////////////////////////
int GiveMeTimestamp()
{
  unsigned long timeout = millis();

  while (client.available() == 0)
  {
    if (millis() - timeout > 50000)
    {
      client.stop();
      return 0;
    }
  }

while (client.available())
      {
        String line = client.readStringUntil('\r');                    //indexOf() is a funtion to search for smthng , it returns -1 if not found
        int pos = line.indexOf("\"timestamp\"");                       //search for "\"timestamp\"" from beginning of response got and copy all data after that , it'll be your timestamp
        if (pos >= 0)                                                     
        {
          int j = 0;
          for(j=0;j<10;j++)
          {
            timestamp[j] = line[pos + 12 + j];
          }
        }
      }
}  
////////////////////////////////////////////////////////////////////////////////////////////////////////

void setup() 
{
  Serial.begin(115200);     //(19200,SERIAL_8E1) - data size = 8 bits , parity = Even , stop bit =  1bit
  mySerial.begin(115200);
  WiFiManager wifiManager;
 
  wifiManager.setAPCallback(configModeCallback);
                                                                                                    
  if(!wifiManager.autoConnect("DDIK Makadia","kidd123456789"))                   //wifiManager.autoConnect("AP-NAME", "AP-PASSWORD"); (OR) wifiManager.autoConnect("AP-NAME"); only ID no password (OR) wifiManager.autoConnect(); this will generate a ID by itself
  {
    Serial.println("failed to connect and hit timeout");     //control comes here after long time of creating Access point "NodeMCU" by NodeMCU and still it has not connected
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  } 

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

  pinMode(redLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  delay(500);
 
}

void loop() 
{
  
/////////////////////////////////////// SEND THE QUERY AND RECEIVE THE RESPONSE///////////////////////  
  int analogSensor = analogRead(smokeA0);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor);
  
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    openclose = 1;
    redled=1;
    tone(buzzer, 4000, 400);
    if(sms_count<=1)
    {
      mySerial.println("AT+CMGF=1");    //To send SMS in Text Mode
      delay(1000);
      mySerial.println("AT+CMGS=\"+91xxxxxxxxxxx\"\r"); // change to the phone number you using 
      delay(1000);
      mySerial.println("Gas Leaking!");//the content of the message
      delay(200);
      mySerial.println((char)26);//the stopping character
      delay(1000);
      mySerial.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); // change to the phone number you using 
      delay(1000);
      mySerial.println("Gas Leaking!");//the content of the message
      delay(200);
      mySerial.println((char)26);//the message stopping character
      delay(1000);
      sms_count++;
    }
    else
    {
      mySerial.println("Nothing Happen");
    }
  }
  else
  {
    digitalWrite(redLed, LOW);
    noTone(buzzer);
    openclose = 0;
    redled=0;
  }
  delay(100);
  
  Serial.println("connecting to ");
  Serial.println(host);                          //defined upside :- host = devapi2.thethingscloud.com or 139.59.26.117

///////////////////////////////////// TIMESTAMP CODE SNIPPET /////////////////////////
  Serial.println("inside get timestamp\n");
  if (!client.connect(time_server, httpPort)) 
  {
    return;                                                        //*-*-*-*-*-*-*-*-*-*
  }

  client.println("GET /api/timestamp HTTP/1.1");                            //Whats this part doing, i didnt get
  client.println("Host: baas.thethingscloud.com");
  client.println("Cache-Control: no-cache");
  client.println("Postman-Token: ea3c18c6-09ba-d049-ccf3-369a22a284b8");
  client.println();

  GiveMeTimestamp();                        //it'll call the function which will get the timestamp response from the server
  Serial.println("timestamp receieved");
  Serial.println(timestamp);
///////////////////////////////////////////////////////////////////////////////

// Use WiFiClient class to create TCP connections
  if (!client.connect(host, httpPort))            //host = devapi2.thethingscloud.com , port = 80
  {
    Serial.println("connection failed");                  // *-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-
    return;
  }
  
  client.print("Content-Length: ");
  client.println(); 

  unsigned long timeout = millis();
  while (client.available() == 0) 
  {
    if (millis() - timeout > 50000) 
    {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }
  
  Serial.println("***********************************************");
  Serial.println();
  Serial.println("closing connection");

  Serial.println("inside ThingsCloudPost");
  int timestamp1 =0;
  timestamp1 = 1542800778;
 
  String PostValue = "{\"device_id\":  xxxxxx, \"slave_id\": 1";
  PostValue = PostValue + ",\"dts\":" +timestamp;
  PostValue = PostValue +",\"data\":{\"Water Flow\":" + openclose +",\"Led On=1/Off=0\":" + redled +"}"+"}";
    
  Serial.println(PostValue);

//////////////////////////////// try to connect to server again and POST the data on the cloud //////////////////////////
  if (!client.connect(host, httpPort)) 
  {
    return;
  }

  client.print("POST ");
  client.print(post_url);               /// POST api/device-datas         HTTP/1.1     Host: baas.thethingscloud.com      Content-Type: application/json        Cache-Control: no-cache
  client.println(" HTTP/1.1");           //Authorization:          Content-Length: 
  client.print("Host: ");
  client.println(host);
  client.println("Content-Type: application/json");
  client.println("Cache-Control: no-cache");
  client.print("Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.IjViZTc5ZjRiNDAyYjlkNGI5MDdiZGRmZCI.hBa2XTagbf56p_E83PeMZHaoJO4EUrbwGcmWTU0j0-w");
  client.println();
  client.print("Content-Length: ");
  client.println(PostValue.length());
  client.println();
  client.println(PostValue);
  
//////////////////////////////////POSTING the data on to the cloud is done and now get the response form cloud server//////////////////
  while (client.available() == 0) 
  {
    if (millis() - timeout > 50000) 
    {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }
  
  Serial.println("Response From Server");
  while(client.available())
  { 
    String line2 = client.readStringUntil('\r');   
    Serial.print(line2);
    
  }
    
  Serial.println("//////////////////////    THE END     /////////////////////");
  delay(3000);
  
}

Credits

Dhrumil Makadia

Dhrumil Makadia

10 projects • 6 followers

Comments

Add projectSign up / Login