Use this forum to chat about hardware specific topics for the ESP8266 (peripherals, memory, clocks, JTAG, programming)

User avatar
By GengusKahn
#61707 The 8 pins are available for pin mapping following the limits on the Info Page...
This has created 2 independent I2C buses....

https://github.com/esp8266/Arduino/blob/master/doc/reference.md#table-of-contents

While I am still playing around with it it is visible here....type a wrong address for the 404 page....

http://82.5.78.180:5070/

The Webserver Sketch will take 2 Arduino Slaves at Address 6 and 8 on I2C, the slave at address 8 must be present but 6 is optional....

Code: Select all/*
 * Copyright (c) 2015, Majenko Technologies
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * * Neither the name of Majenko Technologies nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Wire.h>
#include "ThingSpeak.h"
#include "HTU21D.h"

HTU21D myHTU21D;

char ssid[] = "YourWifi";                        //  your network SSID (name)
char pass[] = "YourPassword";                    //  your network password
int status = WL_IDLE_STATUS;
const char* hostts = "api.thingspeak.com";
unsigned long myChannelNumber = yourchannel;     //  This should be updated to your channel.........
const char * myWriteAPIKey = "YourThingAPIKEY";  //  Uncomment below once channel is set up.....

extern "C"
{
#include "user_interface.h"
}

ADC_MODE(ADC_VCC);

unsigned long ulMeasCount=0;    // values already measured
int *pfTemp;                    // array for temperature measurements to provide svg graph

//ESP8266WebServer server ( 80 );
unsigned long ulReqcount,ulEnd;
const int led = 16;

int I1,y,y2;
float pfVcC,SensF,Hum,Temp;
byte four,three,two,one,four1,three1,two1,one1,four2,three2,two2,one2,four12,three12,two12,one12;
String duration1,New1,New2;
int FCoUnt,ReSet,sensorReading,TSMeasCount,EnD;
unsigned long CoUnt;
unsigned long LooPTimer  = 0;    // Read Timer Set to fire at start...reloads with a value when first triggered
unsigned long LooPTimer1 = 0;    // Write Timer Set to fire at start...reloads with a value when first triggered
          int  RTSDelay  = 65;   // Set this for the response time of Your Arduino Loop......


ESP8266WebServer server(80);
WiFiClient client;
IPAddress ServerIP;

unsigned long ulNextTSMeas_ms=30000;
unsigned long ulNextMeas_ms=5390;
int COAlrm=0;
int SmAlrm=0;
unsigned long sAcnt=0;
unsigned long cAcnt=0;

const char* TestCh="blinkD13";
char hostString[16] = {0};
String hostStringC,hostString2C;

void GetNano(){
int lOop=0;
    New1="";
  delay(70);
  Wire.begin(4,5);            // I2C Bus 0
  delay(70);
  hostStringC="";
  digitalWrite(2, LOW);       // When Set Request To Send Active Slave will refresh data....
  delay(RTSDelay);               
 
  Wire.beginTransmission(8);
  Wire.requestFrom(8, 6);     // request 6 bytes from slave device #8 bus 0 (Arduino Mini Pro costs £8 for 5 from China)
   while (Wire.available()) { // slave may send more Bytes than requested, embedded Respose Bytes - 8:15
    if(lOop>=2){
    one1 = Wire.read();        // receive a raw byte
    two1 = Wire.read();;
    three1 = Wire.read();
    four1 = Wire.read();
     if(Wire.available()>0){
     char c =  Wire.read();
     hostStringC += c;
     }
    }
  lOop++;
  char c = Wire.read();       // receive a byte as character
  New1+=c;
  }
 Wire.endTransmission();
  delay(100);
  lOop=0;
    New2="";
  hostString2C="";
     // Set Request Idle
  Wire.beginTransmission(6);
  Wire.requestFrom(6, 6);     // request 6 bytes from slave device #6 bus 0 (Arduino Mini Pro costs £8 for 5 from China)
   while (Wire.available()) { // slave may send more Bytes than requested, embedded Respose Bytes - 8:15
    if(lOop>=2){
     one12 = Wire.read();        // receive a raw byte
     two12 = Wire.read();;
     three12 = Wire.read();
     four12 = Wire.read();
     if(Wire.available()>0){
     char c =  Wire.read();
     hostString2C += c;
     }
    }
  lOop++;
  char c = Wire.read();       // receive a byte as character
  New2+=c;
  }
 Wire.endTransmission();
New2=New2.substring(0,2);
if(New2=="A2"){// Very Simple error checking - ignored if missing.........
    four2=four12;
    three2=three12;
    two2=two12;
    one2=one12;
}
digitalWrite(2, HIGH);      // Set Request Idle
 delay(75);
 Wire.begin(12,13);           // I2C Bus 1
 delay(75);
 myHTU21D.begin();
 delay(50);
   Hum = myHTU21D.readCompensatedHumidity();
   Temp = myHTU21D.readTemperature();
   CoUnt++;
   ulMeasCount++;
    if(ulMeasCount>309){ulMeasCount=1;}
   pfTemp[ulMeasCount] = Temp;
   New1=New1.substring(0,2);  // Simple error checking.........
if(New1=="A1" && one1!=255 && four1!=255 ){
   pfVcC =  ESP.getVcc();
   duration1 = "";
   int hr,mn,st;
   st = millis() / 1000;
   mn = st / 60;
   hr = st / 3600;
   st = st - mn * 60;
   mn = mn - hr * 60;
   if (hr<10) {duration1 += ("0");}
   duration1 += (hr);
   duration1 += (":");
   if (mn<10) {duration1 += ("0");}
   duration1 += (mn);
   duration1 += (":");
   if (st<10) {duration1 += ("0");}
   duration1 += (st);
   four=four1;
   three=three1;
   two=two1;
   one=one1;
//if(one>=12){SmAlrm=1;sAcnt++;}
//if(two>=200){COAlrm=1;cAcnt++;}

/*
Serial.println("|_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_¬");
Serial.print("\r\n0  Device ID Value : ");
Serial.println(New1);
Serial.print("\r\n1 Arduino A0 Value  ");
Serial.print((float(one*20)));
Serial.print(" MilliVolts\r\n2 Arduino A1 Value  ");
Serial.print((float(two*2)/100)); 
Serial.print(" Volts\r\n3 Arduino A2 Value  ");
Serial.print((float(three*2)/100));
Serial.print(" Volts\r\n4 Arduino A3 Value  ");
Serial.print((float(four*2)/100));
Serial.print(" Volts\r\n5 ESPVcc ADC Value  ");
Serial.print(pfVcC/1000, 2);
Serial.print(" Volts\r\n6    SHT21 Humidity ");
Serial.print(Hum);
Serial.print(" RH %\r\n7 SHT21 Temperature ");
Serial.print(Temp);
Serial.print(" Deg C\r\n     Running Time : ");
Serial.print(duration1);
Serial.print("\r\nLoops ");
Serial.print(CoUnt);
Serial.print("\r\nSingle Errors ");
Serial.print(FCoUnt);
Serial.print("\r\nArduino Resets(+2 errors) ");
Serial.println(ReSet);
*/
}else{
    /*
    Serial.println("\r\nError in IIC Retrying.... ");
    Serial.print("\r\nLoops ");
    Serial.println(CoUnt);
    Serial.print("\r\nSingle Errors ");
    Serial.println(FCoUnt);
    Serial.print("\r\nArduino Resets(+2 errors) ");
    Serial.println(ReSet);
    */
    FCoUnt++;
  }
}




void handleRoot() {
  ulReqcount++;
   digitalWrite ( led, 1 );
   char temp[400];
   int sec = millis() / 1000;
   int min = sec / 60;
   int hr = min / 60;
  int dy = hr / 24;

   snprintf ( temp, 400,

"<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>ESP8266 Demo</title>\
    <style>\
      body { background-color: #A0DFFE; font-family: Arial, Helvetica, Sans-Serif; Color: #0000FF; }\
    </style>\
  </head>\
  <body>\
    <h1>Hello from ESP8266!</h1>\
    <a href=\"/diag\">Basic Diagnostics Page</a>\
    <p>Uptime : %02d Day\'s %02d:%02d:%02d</p>\
    <img src=\"/test.svg\" />\
  </body>\
</html>",
   
      dy, hr % 24, min % 60, sec % 60
   );
   server.send ( 200, "text/html", temp );
   digitalWrite ( led, 0 );
}


void AQS()
  {
    String PageStr="";
    pfVcC = ESP.getVcc();
    digitalWrite ( led, 1 );
    WiFiClient client = server.client();
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 20");        // refresh the page automatically every 10 sec
          client.println();
          PageStr+=("<!DOCTYPE HTML>");
          PageStr+=("<html><title>Environment Monitor AQS</title>");         
          PageStr+=("<div style=\"float:right; \">");
          PageStr+=("<BR><a href=\"/diag\">AQS System Info Page</a></div>");
          client.println(PageStr);
          PageStr="";         
          PageStr+=("<font color=\"#000000\"><body bgcolor=\"#a0dFfe\"><h1><p>Environment Monitor<BR>Air Quality Sensors<br><FONT SIZE=-2>Temperature Trend");
          PageStr+=("<FONT SIZE=+3><BR><img src=\"/test.svg\" /></p><table ><div  style=\"float:left; width:160px; height: 160px;\">");
           client.println(PageStr);
          PageStr="";           
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 2; analogChannel++) {
            if(analogChannel==0){
              int sensorReading1 = one;
              //Serial.println(sensorReading1);
              //if(sensorReading1>=12){SmAlrm=1;sAcnt++;}
              SensF = sensorReading1 * 2;
              PageStr+=("<tr><th>Arduino One<BR>Smoke Sensor Alarm Count = ");
              PageStr+=(sAcnt);
              PageStr+=(" </tr></th>");
              PageStr+=("<tr><th> CH4/Smoke");
             // if(sensorReading1>=30){sensorReading1-=30;}else{sensorReading1=0;}
            }else{
              int sensorReading2 = two;
              //Serial.println(sensorReading2);
              //if(sensorReading2>=200){COAlrm=1;cAcnt++;}
              SensF = sensorReading2 * 2;
              PageStr+=("<tr><th> Carbon Monoxide Alarm Count = ");
              PageStr+=(cAcnt);
              PageStr+=(" </tr></th>");
              PageStr+=("<tr><th> CO");
             // if(sensorReading2>=170){sensorReading2-=170;}else{sensorReading2=0;}
            }
            PageStr+=(" Sensor Value is : ");
            PageStr+=String(SensF/100, 2);
            PageStr+=(" V</tr></th>");
          }
          client.println(PageStr);
          PageStr="";           
          if(New2=="A2"){
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 2; analogChannel++) {
            if(analogChannel==0){
              int sensorReading5 = one2;
              //Serial.println(sensorReading1);
              //if(sensorReading1>=12){SmAlrm=1;sAcnt++;}
              SensF = sensorReading5 * 2;
              PageStr+=("<tr><th>Arduino Two<BR>Smoke Sensor Alarm Count = ");
              PageStr+=(sAcnt);
              PageStr+=(" </tr></th>");
              PageStr+=("<tr><th> CH4/Smoke");
             // if(sensorReading1>=30){sensorReading1-=30;}else{sensorReading1=0;}
            }else{
              int sensorReading6 = two2;
              //Serial.println(sensorReading2);
              //if(sensorReading2>=200){COAlrm=1;cAcnt++;}
              SensF = sensorReading6 * 2;
              PageStr+=("<tr><th> Carbon Monoxide Alarm Count = ");
              PageStr+=(cAcnt);
              PageStr+=(" </tr></th>");
              PageStr+=("<tr><th> CO");
             // if(sensorReading2>=170){sensorReading2-=170;}else{sensorReading2=0;}
            }
            PageStr+=(" Sensor Value is : ");
            PageStr+=String(SensF/100, 2);
            PageStr+=(" V</tr></th>");
          }
       }
          PageStr+=("</table></div></h1></html>");
          client.println(PageStr);
    PageStr="";           
    ulReqcount++;
    digitalWrite ( led, 0 );
  }


void diag()
  {   
     digitalWrite ( led, 1 );
     WiFiClient client = server.client();
     pfVcC = ESP.getVcc();
     long int spdcount = ESP.getCycleCount();
     delay(1);
     long int spdcount1 = ESP.getCycleCount();
     long int speedcnt = spdcount1-spdcount;
     FlashMode_t ideMode = ESP.getFlashChipMode();
     ulReqcount++;
                                String duration1 = " ";
                                int hr,mn,st;
                                st = millis() / 1000;
                                mn = st / 60;
                                hr = st / 3600;
                                st = st - mn * 60;
                                mn = mn - hr * 60;
                                if (hr<10) {duration1 += ("0");}
                                duration1 += (hr);
                                duration1 += (":");
                                if (mn<10) {duration1 += ("0");}
                                duration1 += (mn);
                                duration1 += (":");
                                if (st<10) {duration1 += ("0");}
                                duration1 += (st);     
                                client.println("HTTP/1.1 200 OK");
                                client.println("Content-Type: text/html");
                                client.println("Connection: close");
                                client.println("Refresh: 20");        // refresh the page automatically every 20 sec
                                client.println();
                                client.println("<!DOCTYPE HTML>");
                                client.print("<html><head><title>Environment Monitor AQS</title></head><body>");//
                                client.print("<font color=\"#0000FF\"><body bgcolor=\"#A0DFFE\">");
                                client.print("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
                                client.print("<h2>Environment Monitor AQS<BR>System Information</h2><BR><a href=\"/\">AQS Sensor Page</a>");
                                client.print("<BR><BR>");
                               String PageStr="";
                                PageStr+=(" I2C Arduino ID : ");
                                PageStr+=(New1);
                                PageStr+=("<BR> SHT21 Temperature : ");
                                PageStr+=(Temp);
                                PageStr+=(" C<BR> SHT21 Humidity : ");
                                PageStr+=(Hum);
                                PageStr+=(" %RH<BR> ESP8266 I2C 3V : ");
                                client.println(PageStr);
                                PageStr="";
                                int sensorReading3 = three;
                                SensF = sensorReading3 * 2;
                                PageStr+=String(SensF/100, 2);
                                PageStr+=("V<BR> Arduino I2C 5V : ");
                                int sensorReading4 = four;
                                SensF = sensorReading4 * 2;
                                PageStr+=String(SensF/100, 2);
                                PageStr+=("V<BR> Arduino I2C Requests : ");
                                PageStr+=(CoUnt);
                                PageStr+=("<BR> Arduino I2C Errors : ");
                                PageStr+=(FCoUnt + (ReSet*2) );
                                PageStr+=("<BR> Arduino Resets : ");
                                PageStr+=(ReSet);
                                PageStr+=("<BR> Arduino Response : ");
                                PageStr+=(hostStringC);
                                client.println(PageStr);
                                PageStr="";
                                if(New2=="A2"){
                                PageStr+=("<BR> I2C Arduino ID : ");
                                PageStr+=(New2);
                                PageStr+=("<BR> ESP8266 I2C 3V : ");
                                int sensorReading5 = three2;
                                SensF = sensorReading5 * 2;
                                PageStr+=String(SensF/100, 2);
                                PageStr+=("V<BR> Arduino I2C 5V : ");
                                int sensorReading6 = four2;
                                SensF = sensorReading6 * 2;
                                PageStr+=String(SensF/100, 2);
                                PageStr+=("V");
                                client.println(PageStr);
                                PageStr="";
                                }
                                String diagdat="";
                                diagdat+="<BR>  Web Page Requests = ";
                                diagdat+=ulReqcount;
                                diagdat+="<BR>  WiFi Station Hostname = ";
                                diagdat+=wifi_station_get_hostname();
                                diagdat+="<BR>  Free RAM = ";
                                client.print(diagdat);
                                client.println((uint32_t)system_get_free_heap_size()/1024);
                                diagdat=" KBytes<BR>";                               
                                diagdat+="  SDK Version = ";                                 
                                diagdat+=ESP.getSdkVersion();
                                diagdat+="<BR>  Boot Version = ";
                                diagdat+=ESP.getBootVersion();
                                diagdat+="<BR>  Free Sketch Space  = ";
                                diagdat+=ESP.getFreeSketchSpace()/1024;
                                diagdat+=" KBytes<BR>  Sketch Size  = ";
                                diagdat+=ESP.getSketchSize()/1024;
                                diagdat+=" KBytes<BR>";
                                client.println(diagdat);
                                client.printf("  Flash Chip id = %08X\n", ESP.getFlashChipId());
                                client.print("<BR>");
                                client.printf("  Flash Chip Mode = %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));
                                diagdat="<BR>  Flash Size By ID = ";
                                diagdat+=ESP.getFlashChipRealSize()/1024;
                                diagdat+=" KBytes<BR>  Flash Size (IDE) = ";
                                diagdat+=ESP.getFlashChipSize()/1024;
                                diagdat+=" KBytes<BR>  Flash Speed = ";
                                diagdat+=ESP.getFlashChipSpeed()/1000000;
                                diagdat+=" MHz<BR>  ESP8266 CPU Speed = ";
                                diagdat+=ESP.getCpuFreqMHz();
                                diagdat+=" MHz<BR>";
                                client.println(diagdat);
                                client.printf("  ESP8266 Chip id = %08X\n", ESP.getChipId());
                                diagdat="<BR>  System Instruction Cycles Per Second = ";
                                diagdat+=speedcnt*1000;                                                               
                                diagdat+="<BR>  System VCC = ";
                                diagdat+=pfVcC/1000, 2;
                                diagdat+=" V ";
                                diagdat+="<BR>  System Uptime =";
                                diagdat+=duration1;
                                diagdat+="<BR>  Last System Restart Reason = <FONT SIZE=-1>";
                                diagdat+=ESP.getResetInfo();
                                client.println(diagdat);
                                client.println("<BR><FONT SIZE=-2><a href=\"mailto:environmental.monitor.log@gmail.com\">environmental.monitor.log@gmail.com</a><BR><FONT SIZE=-2>ESP8266 With I2C Arduino ADC Slave<BR><FONT SIZE=-2>Compiled Using ver. 2.3.0-rc1, Jan, 2017<BR>");
                                client.println("<IMG SRC=\"https://raw.githubusercontent.com/genguskahn/ESP8266-For-DUMMIES/master/SoC/DimmerDocs/organicw.gif\" WIDTH=\"250\" HEIGHT=\"151\" BORDER=\"1\"></body></html>");
                                diagdat="";//<p>This is an email link:<a href="mailto:someone@example.com?Subject=Hello%20again" target="_top">Send Mail</a></p>
 
  // and stop the client
  client.stop();
  digitalWrite ( led, 0 );
  }


void handleNotFound() {
  ulReqcount++;
   digitalWrite ( led, 1 );
   String message = "<html><head><title>404 Not Found</title></head><body bgcolor=\"#A0DFFE\"><font color=\"#0000FF\"><h1>";
  message += "<img src=\"http://82.5.78.180:5050/img/flame.gif\" style=\"width:50px;position:relative;top:8px;\">Not";
  message += "<img src=\"http://82.5.78.180:5050/img/flame.gif\" style=\"width:50px;position:relative;top:8px;\">";
  message += "<BR>:-( Here )-:</h1><p>The requested URL was not found on this server, What did you ask for?.</p>";
   message += "<BR>URI (What you typed to end up here...): ";
   message += server.uri();
   message += "<BR>Method (How the access was made...): ";
   message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
   message += "<BR>Arguments (Did you ask a Question?): ";
   message += server.args();
   message += "<BR>";
   for ( uint8_t i = 0; i < server.args(); i++ ) {
      message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
   }
  message += " </body></html>";
   server.send ( 200, "text/html", message );
   digitalWrite ( led, 0 );
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  digitalWrite ( led, 1 );
  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  Serial.begin(115200);
  delay(50);
  Serial.println("\r\n\r\nRe-Starting I2C Arduino Slave.......\r\n");
  digitalWrite(0, HIGH);
  pinMode(2, OUTPUT);     // I2C Request To Send, ESP8266 to Slave, 0 = Request Ready, 1 = idle
  digitalWrite(2, HIGH);
  delay(3000);            // allow all to settle before sending reset to Arduino.....
  pinMode(0, OUTPUT);
  digitalWrite(2, HIGH);  // Using Fash button
  delay(10);
  digitalWrite(2, LOW);
  delay(5);               // 5 millisec pulse to reset Arduino.....
  digitalWrite(2, HIGH);
  delay(3000);            // Arduino Startup delay
  Serial.println("Started I2C Arduino Slave.....\r\n");
  delay(50);
  Serial.println("Starting WfFi...\r\n");
  sprintf(hostString, "ESP_%06X", ESP.getChipId());
  Serial.print("Hostname: ");
  Serial.println(hostString);
  WiFi.hostname(hostString);
  delay(50);
  Serial.print(F("\r\n\r\nConnecting to "));
  Serial.println(ssid);
   WiFi.begin ( ssid, pass );
   Serial.println ( "" );

   // Wait for connection
   while ( WiFi.status() != WL_CONNECTED ) {
      delay ( 500 );
      Serial.print ( "." );
   }

   Serial.println ( "" );
   Serial.print ( "Connected to " );
   Serial.println ( ssid );
   Serial.print ( "IP address: " );
   Serial.println ( WiFi.localIP() );

   if ( MDNS.begin ( "esp8266" ) ) {
      Serial.println ( "MDNS responder started" );
   }

   server.on ( "/", HTTP_GET, AQS );
   server.on ( "/test.svg", drawGraph2 );
   server.on ( "/inline", []() {
       ulReqcount++;
      server.send ( 200, "text/plain", "this works as well" );
   } );
  server.on("/diag", HTTP_GET, diag);
   server.onNotFound ( handleNotFound );
   server.begin();
   Serial.println ( "HTTP server started" );

  pfTemp = new int[320];
 
  if (pfTemp==NULL)
  {
    Serial.println("Error in memory allocation!");
  }

 //Get Local I2C Data on Bus 1
 Wire.begin(12,13);
 delay(75);
 myHTU21D.begin();
 delay(200);
   Hum = myHTU21D.readCompensatedHumidity();
   Temp = myHTU21D.readTemperature();
  Serial.println("\r\nI2C T/H Sensor Data on BUS 1 : " + String(Temp) + " : "+ String(Hum) + "\r\n");
  digitalWrite ( led, 0 );
  Serial.println("I2C Arduino Slave on BUS 0....Requesting Data...\r\n\r\n");
 
}

void loop( void ) {
   server.handleClient();
  if(FCoUnt>1){             // Reset Arduino after 2 errors from I2C......
  FCoUnt=0;
  ReSet++;                 // Reset ESP after 10 Errors......
  if(ReSet==5){ESP.restart();}
  Serial.println("\r\nResetting I2C Arduino Slave.......\r\n\r\n");
  delay(10);
  digitalWrite(2, LOW);
  delay(5);               // 5 millisec pulse to reset Arduino.....
  digitalWrite(2, HIGH);
  delay(3000);            // Arduino Startup delay
  Wire.begin(4,5);
  delay(150);
  Wire.requestFrom(8, 8);
  delay(100);
}

if(SmAlrm==1 || COAlrm==1){

  digitalWrite ( led, 1 );    // turn on the LED
  delay(1000);
  float pinVoltage = one;
  float pinVoltage1 = two;
  if(pinVoltage<=12 && pinVoltage1<=100){
    COAlrm=0;
    SmAlrm=0;
  }
}
if (millis()>=ulNextMeas_ms)
 {
    GetNano();
    ulNextMeas_ms = millis()+2048;
 }
if (millis()>=ulNextTSMeas_ms)
 {
  TSMeasCount++;
    if (TSMeasCount>=720) {// Set the point for reboot....resfresh Timers, DNS, DHCP Etc......
    delay(100);
     ESP.restart();     
  }
  ulNextTSMeas_ms = millis()+120000;
  int pinVltage = one * 2;
  int pinVltage1 = two * 2;
  float pinVltage2 = three * 2;
  float pinVltage3 = four * 2;
//if(pinVltage>=15){pinVltage-=15;}else{pinVltage=0;}
//if(pinVltage1>=150){pinVltage1-=150;}else{pinVltage1=0;}
//Serial.println(pinVltage);
//Serial.println(pinVltage1);
/*
  ThingSpeak.setField(1,pinVltage*10);        // MQ-2 Sensor Value (Arduino A0) - millivolts...
  ThingSpeak.setField(2,pinVltage1*10);       // MQ-7 Sensor Value (Arduino A1) - millivolts...
  ThingSpeak.setField(3,Temp);                // SHT21 Temp Sensor Value - int C
  ThingSpeak.setField(4,Hum);                 // SHT21 Hum Sensor Value - int %RH
  ThingSpeak.setField(5,pfVcC/1000);          // ESP8266 VCC (ADC_READ_VCC) Value - Volts
  ThingSpeak.setField(6,pinVltage2/100);      // 3.3V LDO Output (Arduino A2) - Volts
  ThingSpeak.setField(7,pinVltage3/100);      // 5V Arduino VCC (Arduino A3) - Volts
  ThingSpeak.setField(8,FCoUnt+(ReSet * 2));  // Error counter for last 24hours or since Last ESP8266 Reset
  ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  delay(500);
  */
   
 }

}



void drawGraph2() {
  ulEnd=1;
  String out = "";
  char temp[200];
  out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"310\" height=\"150\">\n";
  out += "<rect width=\"310\" height=\"150\" fill=\"rgb(25, 30, 110)\" stroke-width=\"1\" stroke=\"rgb(255, 255, 255)\" />\n";
  out += "<g stroke=\"white\">\n"; 
  y = pfTemp[ulEnd] * 3;
  for (int x = 0; x < ulMeasCount; x++) {
    y2 = pfTemp[ulEnd++] * 3;
    sprintf(temp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 1, 140 - y2);
    out += temp;
    y = y2;
  }
  out += "</g>\n</svg>\n";
//Serial.print(out);
  server.send ( 200, "image/svg+xml", out);
}




void drawGraph() {
   String out = "";
   char temp[100];
   out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" height=\"150\">\n";
    out += "<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\" />\n";
    out += "<g stroke=\"black\">\n";
    int y = rand() % 130;
    for (int x = 10; x < 390; x+= 10) {
       int y2 = rand() % 130;
       sprintf(temp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 10, 140 - y2);
       out += temp;
       y = y2;
    }
   out += "</g>\n</svg>\n";
//Serial.print(out);
   server.send ( 200, "image/svg+xml", out);
}


The Slave Sketch.....

Code: Select all/* This provides some easy access to the Arduino peripherals and Libraries via an 6 byte transfer
   run any sketch and include this snippet to provide readings to the ESP8266 Via I2C using the array.
   ESP8266 connected to I2C via pins 4(SDA) and 5(SCL)
   Arduino pins A4 and A5 are connected via 5v to 3v converter to the ESP8266 pins 4 and 5.
   The 6 bytes are arranged - bytes 0+1 are a 2 char ID, bytes 2-5 Arduino A0 to A3 reading
   presenting data as byte allows very simple transfer.
   ESP8266 pin0 Used to Reset this Arduino and ESP8266 pin2 to send Request for data (RTS) to this Arduino.....
   Arduino Pin  Esp Pin
   Reset         0
   2             2
   A4            4
   A5            5
   All via 5V to 3V shifter......Arduino 5v side can take more Slaves......
*/
#include <Wire.h>
#include "HTU21D.h"

HTU21D myHTU21D;

// Send variables
char msg[6];

// Recieved variables
String ArdData;

// Measurement timer
unsigned long ulNextMeas_ms=1000;
int RTSState;                        // Current RTS State
int lastRTSState = HIGH;             // Previous RTS State
unsigned long lastResponseTime = 0;  // Last RTS Toggled time
unsigned long ResponseDelay = 25;    // Delay to provide time for pin to settle.....

void ReadSensors() {
  Wire.write(msg);             // Response to Master Request
}


void setup() {
  pinMode(2, INPUT);
  pinMode(8, OUTPUT);
  digitalWrite(8, HIGH);
    pinMode(5, OUTPUT);
  digitalWrite(5, LOW);
 // Serial.begin(115200);
 // Serial.println("\r\n\r\n");
  Wire.begin(8);               // join i2c bus with address #8
  Wire.onRequest(ReadSensors); // register event
  delay(25);
  msg[0]='A';  //  Used to identify which Arduino, Use as many as needed adjust the Address!
  msg[1]='1';  //  These 2 bytes are used to help verify the data in the Master Sketch
  for(int i=0;i<4;i++){
  int sensorValue = analogRead(i)/4;
  if(sensorValue>254){sensorValue=254;}
  //sensorValue=constrain(map(sensorValue, 0, 1020, 0, 254), 0, 254);
  msg[i+2]=sensorValue;
  }
}

void loop() {
  int RTSFlag = digitalRead(2);
  if (RTSFlag != lastRTSState) {
    lastResponseTime = millis();
  }
  if ((millis() - lastResponseTime) > ResponseDelay) {
    if (RTSFlag != RTSState) {
      RTSState = RTSFlag;
      if (RTSState == LOW) {
  msg[0]='A';  //  Used to identify which Arduino, Use as many as needed adjust the Address!
  msg[1]='1';  //  These 2 bytes are used to help verify the data in the Master Sketch
  for(int i=0;i<4;i++){
  int sensorValue = analogRead(i);
  sensorValue=constrain(map(sensorValue, 0, 1020, 0, 254), 0, 254);
  msg[i+2]=sensorValue;
  }
      }
    }
  }
    lastRTSState = RTSFlag;   
    yield();
}

User avatar
By JyotiRajSharma
#61709 Did you use Xbee or not ?? I was wondering how to connwct xbee, arduino and esp8266 together . I am thinking to use uart connecting xbee tx-----esp8266 rx and xbee rx ----esp8266tx