Smart home for reduced mobility people with oneM2M/ESP8266

We have designed and implemented a domotic system adapted for the needs of Hearing Impaired People.

IntermediateWork in progress365
Smart home for reduced mobility people with oneM2M/ESP8266

Things used in this project

Hardware components

NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
×3
Grove - Temperature Sensor
Seeed Studio Grove - Temperature Sensor
×1
Seeed Studio Grove - Analog Microphone
×1
Seeed Studio Module mini Fan Grove (v1.1)
×1
Grove - 16 x 2 LCD (Black on Red)
Seeed Studio Grove - 16 x 2 LCD (Black on Red)
×1

Software apps and online services

Arduino IDE
Arduino IDE
Node-RED
Node-RED
oneM2M standard

Story

Read more

Code

Code for ESP1

Arduino
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>


String header;
WiFiServer server(80);


const char* ssid = "ENTER-YOUR-WIFI-SSID";     // Configure here the SSID of your WiFi Network
const char* password =  "ENTER-YOUR-WIFI-PASSWORD"; // Configure here the PassWord of your WiFi Network

//Your Domain name with URL path or IP address with path
const char* serverName = "http://172.20.10.2:1880/FFT";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;


// Auxiliar variables to store the current output state
//String output5State = "off";
//String output4State = "off";

// Assign output variables to GPIO pins
//const int output5 = 5;
//const int output4 = 4;
/////////////////////////////////////////////////////////////////////////////////////////////////////////
int data_in[256];
unsigned long t;
float prev_f=0.0;
float tab_f[100];

////////////////////////////////////////////////////////////
float moyenne_glissante (float a){
  float somme =0;

  for (int i=0; i<1>00; i++){
  tab_f[i-1]= tab_f[i];
  somme+=tab_f[i-1];
  }
  tab_f[99] = a;
  somme += tab_f[99];
  return (somme/100); 
  }

///////////////////////////////////////////////////////////////
float Q_FFT(int in[],int N,float Frequency)
{ 

unsigned int Pow2[13]={1,2,4,8,16,32,64,128,256,512,1024,2048}; // declaring this as global array will save 1-2 ms of time


int a,c1,f,o,x;         
byte check=0;
a=N;  
                                 
      for(int i=0;i<12;i++)                 //calculating the levels
         { if(Pow2[i]<=a){o=i;} }
      
int out_r[Pow2[o]]={};   //real part of transform
int out_im[Pow2[o]]={};  //imaginory part of transform
           
x=0;  
      for(int b=0;b<o;b++)                     // bit reversal
         {
          c1=Pow2[b];
          f=Pow2[o]/(c1+c1);
                for(int j=0;j<c1;j++)
                    { 
                     x=x+1;
                     out_im[x]=out_im[j]+f;
                    }
         }

 
      for(int i=0;i<Pow2[o];i++)            // update input array as per bit reverse order
         {
          out_r[i]=in[out_im[i]]; 
          out_im[i]=0;
         }


int i10,i11,n1,tr,ti;
float e;
int c,s;
    for(int i=0;i<o;i++)                                    //fft
    {
     i10=Pow2[i];              // overall values of sine/cosine  
     i11=Pow2[o]/Pow2[i+1];    // loop with similar sine cosine
     e=360/Pow2[i+1];
     e=0-e;
     n1=0;

          for(int j=0;j<i10;j++)
          {
            c=e*j;
  while(c<0){c=c+360;}
  while(c>360){c=c-360;}

          n1=j;
          
          for(int k=0;k<i11;k++)
                 {

       if(c==0) { tr=out_r[i10+n1];
                  ti=out_im[i10+n1];}
  else if(c==90){ tr= -out_im[i10+n1];
                  ti=out_r[i10+n1];}
  else if(c==180){tr=-out_r[i10+n1];
                  ti=-out_im[i10+n1];}
  else if(c==270){tr=out_im[i10+n1];
                  ti=-out_r[i10+n1];}
  else if(c==360){tr=out_r[i10+n1];
                  ti=out_im[i10+n1];}
  else if(c>0  && c<90)   {tr=out_r[i10+n1]-out_im[i10+n1];
                           ti=out_im[i10+n1]+out_r[i10+n1];}
  else if(c>90  && c<180) {tr=-out_r[i10+n1]-out_im[i10+n1];
                           ti=-out_im[i10+n1]+out_r[i10+n1];}
  else if(c>180 && c<270) {tr=-out_r[i10+n1]+out_im[i10+n1];
                           ti=-out_im[i10+n1]-out_r[i10+n1];}
  else if(c>270 && c<360) {tr=out_r[i10+n1]+out_im[i10+n1];
                           ti=out_im[i10+n1]-out_r[i10+n1];}
          
                 out_r[n1+i10]=out_r[n1]-tr;
                 out_r[n1]=out_r[n1]+tr;
                 if(out_r[n1]>15000 || out_r[n1]<-15000){check=1;}
          
                 out_im[n1+i10]=out_im[n1]-ti;
                 out_im[n1]=out_im[n1]+ti;
                 if(out_im[n1]>15000 || out_im[n1]<-15000){check=1;}          
          
                 n1=n1+i10+i10;
                  }       
             }

    if(check==1){                                             // scale the matrics if value higher than 15000 to prevent varible from overloading
                for(int i=0;i<Pow2[o];i++)
                    {
                     out_r[i]=out_r[i]/100;
                     out_im[i]=out_im[i]/100;    
                    }
                     check=0;  
                }           

     }

/*
for(int i=0;i<Pow2[o];i++)
{
Serial.print(out_r[i]);
Serial.print("\t");                                     // un comment to print RAW o/p    
Serial.print(out_im[i]); Serial.println("i");      
}
*/

//---> here onward out_r contains amplitude and our_in conntains frequency (Hz)
int fout,fm,fstp;
float fstep;
fstep=Frequency/N;
fstp=fstep;
fout=0;fm=0;

    for(int i=1;i<Pow2[o-1];i++)               // getting amplitude from compex number
        {
        if((out_r[i]>=0) && (out_im[i]>=0)){out_r[i]=out_r[i]+out_im[i];}
   else if((out_r[i]<=0) && (out_im[i]<=0)){out_r[i]=-out_r[i]-out_im[i];}
   else if((out_r[i]>=0) && (out_im[i]<=0)){out_r[i]=out_r[i]-out_im[i];}
   else if((out_r[i]<=0) && (out_im[i]>=0)){out_r[i]=-out_r[i]+out_im[i];}
   // to find peak sum of mod of real and imaginery part are considered to increase speed
        
out_im[i]=out_im[i-1]+fstp;
if (fout<out_r[i]){fm=i; fout=out_r[i];}
         /*
         Serial.print(out_im[i]);Serial.print("Hz");
         Serial.print("\t");                            // un comment to print freuency bin    
         Serial.println(out_r[i]); 
          */
        }


float fa,fb,fc;
fa=out_r[fm-1];
fb=out_r[fm]; 
fc=out_r[fm+1];
fstep=(fa*(fm-1)+fb*fm+fc*(fm+1))/(fa+fb+fc);

return(fstep*Frequency/N);
}
float fft() {
  t=micros();
  //float somme = 0.0;
  float f=0.0;
  //for (int j=0; j<10; j++) {
    for(int i=0;i<256;i++)
    {
    data_in[i]=analogRead(A0); // Set you analog pin
    delayMicroseconds(1); // depending on your application
    }
    t=micros()-t;
    t=256000000/t;
    f = Q_FFT(data_in,256,t);
    //somme =somme+f;
 // }

// f = somme/10.0;
 
return f;
}



///////////////////////////////////

void setup() {
  Serial.begin(115200);
    
      for (int i=0;i<=100;i++){
        tab_f[i]=0;
        }
////////////////////////////////////////////////////////////////////////////////////////////////////////


  // Initialize the output variables as outputs
//  pinMode(output5, OUTPUT);
//  pinMode(output4, OUTPUT);
//  // Set outputs to LOW
//  digitalWrite(output5, LOW);
//  digitalWrite(output4, LOW);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");

  server.begin();

}

void loop() {

  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();         
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            /*/ turns the GPIOs on and off
            if (header.indexOf("GET /CAMARCHE") >= 0) {
              Serial.println("LETS GOOOOO");
              output5State = "on";
              digitalWrite(output5, HIGH);
            } else if (header.indexOf("GET /5/off") >= 0) {
              Serial.println("GPIO 5 off");
              output5State = "off";
              digitalWrite(output5, LOW);
            } else if (header.indexOf("GET /4/on") >= 0) {
              Serial.println("GPIO 4 on");
              output4State = "on";
              digitalWrite(output4, HIGH);
            } else if (header.indexOf("GET /4/off") >= 0) {
              Serial.println("GPIO 4 off");
              output4State = "off";
              digitalWrite(output4, LOW);
            }*/
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP8266 Web Server</h1>");
            
            /*/ Display current state, and ON/OFF buttons for GPIO 5  
            client.println("<p>GPIO 5 - State " + output5State + "</p>");
            // If the output5State is off, it displays the ON button       
            if (output5State=="off") {
              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 4  
            client.println("<p>GPIO 4 - State " + output4State + "</p>");
            // If the output4State is off, it displays the ON button       
            if (output4State=="off") {
              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");*/
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }


  
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      WiFiClient client2;
      HTTPClient http;


      String webPage;

      
      StaticJsonBuffer<1000> jsonBuffer;
     
     float f = fft();

      // Build your own object tree in memory to store the data you want to send in the request
      JsonObject& root = jsonBuffer.createObject();
      root["sensor"] = "FFT";
     // root["Light"] = analogRead(A0); //Put Sensor value
      //root["Push_Button"] = digitalRead(D7); //Reads Flash Button Status
      
      
      
      root["FFT"] = f; //Reads Flash Button Status
      JsonObject& data = root.createNestedObject("data");
     // data.set("temperature", "30.1");   //METTRE EN FLOAT PAS EN CHIFFRE COMME CA ou bien convertir sur Nodered comme jai fait avec les nodes fonctions
     // data.set("humidity", "70.1");
      
      // Generate the JSON string
      root.printTo(Serial);
      root.printTo(webPage);
      
      
      
      // Your Domain name with URL path or IP address with path
      http.begin(client2, serverName);

      // Specify content-type header
      //http.addHeader("Content-Type", "application/x-www-form-urlencoded");
      // Data to send with HTTP POST
      //String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&value1=24.25&value2=49.54&value3=1005.14";           
      // Send HTTP POST request
      //int httpResponseCode = http.POST(httpRequestData);
      
      // If you need an HTTP request with a content type: application/json, use the following:
      http.addHeader("Content-Type", "application/json");
      int httpResponseCode = http.POST(webPage);
      //root.printTo(http);
      // If you need an HTTP request with a content type: text/plain
      //http.addHeader("Content-Type", "text/plain");
      //int httpResponseCode = http.POST("Hello, World!");
     
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
        
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

Code for ESP2

Arduino
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include "rgb_lcd.h"
#include <string>


String header;
WiFiServer server(80);


const char* ssid = "ENTER-YOUR-WIFI-SSID";     // Configure here the SSID of your WiFi Network
const char* password =  "ENTER-YOUR-WIFI-PASSWORD"; // Configure here the PassWord of your WiFi Network

//Your Domain name with URL path or IP address with path
const char* serverName = "http://172.20.10.2:1880/temperature";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;


//// Auxiliar variables to store the current output state
//String output5State = "off";
//String output4State = "off";
//
//// Assign output variables to GPIO pins
//const int output5 = 5;
//const int output4 = 4;

//Temperature Constant
const int B = 4275;               // B value of the thermistor
const int R0 = 100000;            // R0 = 100k
const int pinTempSensor = A0;     // Grove - Temperature Sensor connect to A0

//Lcd
rgb_lcd lcd;

float get_temperature() {
  int a = analogRead(pinTempSensor);
  float R = 1023.0/a-1.0;
  R = R0*R;
  float temperature = 1.0/(log(R/R0)/B+1/298.15)-273.15; // convert to temperature via datasheet
  
  return temperature;
}


void printLcdBacklight(String line1, String line2, String color, int blinkScreen) {
  lcd.display();
  lcd.clear();
  int colorR = 0;
  int colorG = 0;
  int colorB = 0;
  if (color.equals("RED")) {
    colorR = 255;
    colorG = 0;
    colorB = 0;
  } else if (color.equals("GREEN")) {
    colorR = 0;
    colorG = 255;
    colorB = 0;
  } else if (color.equals("BLUE")) {
    colorR = 0;
    colorB = 255;
    colorG = 0;
  } else if (color.equals("WHITE")) {
    colorR = 255;
    colorB = 255;
    colorG = 255;
  } else if (color.equals("BLACK")) {
    colorR = 0;
    colorB = 0;
    colorG = 0;
  }

  if (line1 != NULL) {
    lcd.setRGB(colorR, colorG, colorB);
    lcd.setCursor(0, 0);
    lcd.print(line1);
    if (blinkScreen == 1) {
      lcd.blinkLED();
    } else {
      lcd.noBlinkLED();
    }
    if (line2 != NULL) {
      lcd.setCursor(0, 1);
      lcd.print(line2);
    }
  }
}

void setup() {
  Serial.begin(115200);
  //LCD
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  lcd.noBlinkLED();
  lcd.noDisplay();

//  // Initialize the output variables as outputs
//  pinMode(output5, OUTPUT);
//  pinMode(output4, OUTPUT);
//  // Set outputs to LOW
//  digitalWrite(output5, LOW);
//  digitalWrite(output4, LOW);



  

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");

  server.begin();

}

void loop() {

  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();         
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /ESP2") >= 0) {
              Serial.println("LETS GOOOOO");
            } else if (header.indexOf("GET /BABY") >= 0) {
              Serial.println("Baby detected");
              printLcdBacklight("Baby Detected !", "Code Blue", "BLUE", 1);
            } else if (header.indexOf("GET /ALARM") >= 0) {
              Serial.println("Alarm detected");
              printLcdBacklight("Alarm Detected !", "Code Red !", "RED", 1);
            } else if (header.indexOf("GET /ALLGOOD") >= 0) {
              Serial.println("We're all good");
              printLcdBacklight("We're all good !", "", "GREEN", 0);
            } else if (header.indexOf("GET /SCREENON") >= 0) {
              Serial.println("Low light");
              printLcdBacklight(" ", " ", "WHITE", 0);
            } else if (header.indexOf("GET /SCREENOFF") >= 0) {
              Serial.println("Screen off");
              printLcdBacklight(" ", " ", "BLACK", 0);
            }
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP8266 Web Server</h1>");
            
//            // Display current state, and ON/OFF buttons for GPIO 5  
//            client.println("<p>GPIO 5 - State " + output5State + "</p>");
//            // If the output5State is off, it displays the ON button       
//            if (output5State=="off") {
//              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");
//            } else {
//              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");
//            } 
//               
//            // Display current state, and ON/OFF buttons for GPIO 4  
//            client.println("<p>GPIO 4 - State " + output4State + "</p>");
//            // If the output4State is off, it displays the ON button       
//            if (output4State=="off") {
//              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");
//            } else {
//              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
//            }
//            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }


  
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      WiFiClient client2;
      HTTPClient http;


      String webPage;

      
      StaticJsonBuffer<1000> jsonBuffer;
      
  
      // Build your own object tree in memory to store the data you want to send in the request
      JsonObject& root = jsonBuffer.createObject();
      root["sensor"] = "Temperature";
      float temp = get_temperature();
      root["Temp"] = temp; //Put Sensor value
      
      JsonObject& data = root.createNestedObject("data");
      data.set("temperature", temp);   //METTRE EN FLOAT PAS EN CHIFFRE COMME CA ou bien convertir sur Nodered comme jai fait avec les nodes fonctions
      
      // Generate the JSON string
      root.printTo(Serial);
      root.printTo(webPage);
      
      
      
      // Your Domain name with URL path or IP address with path
      http.begin(client2, serverName);

      // Specify content-type header
      //http.addHeader("Content-Type", "application/x-www-form-urlencoded");
      // Data to send with HTTP POST
      //String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&value1=24.25&value2=49.54&value3=1005.14";           
      // Send HTTP POST request
      //int httpResponseCode = http.POST(httpRequestData);
      
      // If you need an HTTP request with a content type: application/json, use the following:
      http.addHeader("Content-Type", "application/json");
      int httpResponseCode = http.POST(webPage);
      //root.printTo(http);
      // If you need an HTTP request with a content type: text/plain
      //http.addHeader("Content-Type", "text/plain");
      //int httpResponseCode = http.POST("Hello, World!");
     
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
        
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

Code for ESP3

Arduino
/*
  
  Code compatible with ESP8266 Boards Version 3.0.0 or above 
  (see in Tools > Boards > Boards Manager > ESP8266)
*/

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>

//fan
#define ON 1
#define OFF 0

String header;
WiFiServer server(80);

const char* ssid = "ENTER-YOUR-WIFI-SSID";     // Configure here the SSID of your WiFi Network
const char* password =  "ENTER-YOUR-WIFI-PASSWORD"; // Configure here the PassWord of your WiFi Network


//Your Domain name with URL path or IP address with path
const char* serverName = "http://172.20.10.2:1880/temperature";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;


// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";

// Assign output variables to GPIO pins
const int output5 = 5;
const int output4 = 4;



  void switch_fan(int state) { //1 turn on fan //0 turn off fan
  if (state == 1) {
    analogWrite(A0, 180);
  } else {
    analogWrite(A0, 0);
  }
}


void setup() {
  Serial.begin(115200);


  // Initialize the output variables as outputs
  pinMode(output5, OUTPUT);
  pinMode(output4, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output5, LOW);
  digitalWrite(output4, LOW);

  //Fan
  pinMode(A0, OUTPUT);
  

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");

  server.begin();

}

void loop() {

  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();         
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /CHAUD") >= 0) {
              Serial.println("ventilo on !!!");
              switch_fan(ON);
            } else if (header.indexOf("GET /FROID") >= 0) {
              Serial.println("ventilo of !!!");
              switch_fan(OFF);
              digitalWrite(output5, LOW);
            } 
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP8266 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 5  
            client.println("<p>GPIO 5 - State " + output5State + "</p>");
            // If the output5State is off, it displays the ON button       
            if (output5State=="off") {
              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 4  
            client.println("<p>GPIO 4 - State " + output4State + "</p>");
            // If the output4State is off, it displays the ON button       
            if (output4State=="off") {
              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }

}

Credits

Rami Karaoud

Rami Karaoud

1 project • 1 follower
Teo Geneau

Teo Geneau

1 project • 0 followers
Yosra ZEYRI NEMRI

Yosra ZEYRI NEMRI

1 project • 0 followers
Andreas Kraft

Andreas Kraft

34 projects • 12 followers
IoT & connected home architect and developer. Ask me about oneM2M.
SeungMyeong Jeong

SeungMyeong Jeong

34 projects • 12 followers
Bob Flynn

Bob Flynn

32 projects • 13 followers
Bob Flynn

Bob Flynn

2 projects • 0 followers
Miguel Angel Reina Ortega

Miguel Angel Reina Ortega

35 projects • 7 followers
Laurent Velez

Laurent Velez

18 projects • 6 followers
Samir Medjiah

Samir Medjiah

21 projects • 14 followers
Xavier Piednoir

Xavier Piednoir

26 projects • 6 followers
Wonbae Son

Wonbae Son

32 projects • 5 followers
안일엽

안일엽

17 projects • 1 follower
monteil

monteil

4 projects • 1 follower
mrduino

mrduino

0 projects • 0 followers

Comments