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

User avatar
By martinayotte
#61852
JyotiRajSharma wrote:But as I know, GPIO_0 should be connected to GND while uploading the code that will run on ESP, how will this work ??


As I said :
Grounding GPIO0 for sketch upload isn't not an issue either, because I2C is idle during that moment.
User avatar
By JyotiRajSharma
#61890 I tried simple I2C communication between Arduino and ESP8266

Arduino ESP8266
Pin 4 GPIO_0
Pin 5 GPIO_2

In addition, CH_PD, VCC of ESP8266 connected to VCC (3.3v) and GND of ESP is connected to GND.
It seems that communication is not happening.
Wire.avaialbale() is returning 0 at both master esp and slave Arduino side ?

Any suggestion what mistakes I have done ??

//Slave side code
#include <Wire.h>

// Send variables
int Hint,Tint;
char msg[8];
byte one;


void setup() {
Serial.begin(115200);
Wire.begin(8); // join i2c bus with address #8
delay(100);

}

void loop() {
Wire.beginTransmission(8);
// THIS IS REQUIRED because in Wire.cpp, Wire.begin() does not write if "transmitting" flag is not SET to 1. "transmitting" flag is SET to 1 from begin.Transmission() function.
delay(10);
Wire.write("jyoti");
delay(1000);
Serial.println("starting");
Wire.requestFrom(8, 6);
while (Wire.available())
{
// slave may send less than requested
one = Wire.read();
Serial.println(one);
}
}

//ESP8266 as I2C master

#include <Wire.h>

float pfVcC,SensF,Hum,Temp;
byte four,three,two,one,four1,three1,two1,one1,four2,three2,two2,one2,four12,three12,two12,one12;

void setup() {
Serial.begin(115200); // start serial output

delay(1000); // Arduino Startup delay
Wire.begin(0,2); // start i2c bus
Serial.println("Started I2C Arduino Slave....Requesting Data...\r\n\r\n");
delay(1000);
}

void loop() {

delay(130); // Set this for the response time of Your Arduino Loop......
Wire.beginTransmission(8);
Wire.requestFrom(8, 5); // request 6 bytes from slave device #8
delay(1000);

while (Wire.available())
{
Wire.write("sharma");
// slave may send less than requested
one = Wire.read();
two = Wire.read();;
three = Wire.read();
four = Wire.read();
Hum = Wire.read();
Temp = Wire.read();
}
char c = Wire.read(); // receive a byte as character
}
User avatar
By GengusKahn
#61910 Hi there, for the ESP with 4 IO Pins use 1,3 for I2C and do not use Serial, I have used an Interrupt driven routine on the Arduino and transferring 16Bytes of ADC data in 32byte transfer mode of about 12ms.

The sketch is very stable and is running @
http://82.5.78.180:5070
Thingspeak Channel..
https://thingspeak.com/channels/209159

The Master Sketch...

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.
 */

 /*
   This provides some easy access to the Arduino peripherals and Libraries via a 16 byte Int->String->Int transfer
   ESP8266 connected to I2C via pins 4(SDA) and 5(SCL), the SHT21 is directly connected to ESP8266 pins
   Arduino pins A4 and A5 are connected via 5v to 3v converter to the ESP8266 pins 4 and 5.
   The 16 bytes are arranged - bytes 0+1 are a 2 char ID, 3 byte blocks 2-4, 5-7, 8-11, 12-14 are Arduino A0 to A3 reading, 15 terminator
   presenting data as byte allows very simple transfer.
   ESP8266 pin0 Used to Reset the Arduino and ESP8266 pin2 to send Request for data (RTS) assigned to Arduino interrupt 0 (D2).....

   Webpages with SVG Charts on / for Sensors and /diag for Temperature, Internals and Counters...........

   The Arduino data fetch routine takes about 12ms to populate msg[] Slave Sketch at the bottom of this Sketch

   The option to use Multiple I2C busses can be used by initialising Each Bus and Device before Use....3 I2C Buses on 5 pins.....

   Wire.begin(4,5);
   Wire.beginTransmission(8);   // Address 8 on Bus 0
   Wire.requestFrom(8, 16);
   Wire.endTransmission();
   delay(50);
   Wire.begin(1,3);             // Use this for ESP8266-01 BUT No Serial !!!!! Use LCD For Wiring/Adaptation Debug......
   Wire.beginTransmission(8);   // Address 8 on Bus 1
   Wire.requestFrom(8, 16);
   Wire.endTransmission();
   delay(50);
   myHTU21D.begin();            // Start Sensor 1 Bus 1
   delay(50);
   Hum = myHTU21D.readCompensatedHumidity(); 
   Temp = myHTU21D.readTemperature();
   delay(50);
   Wire.begin(12,5);            // Option to Share a Clock pin
   Wire.beginTransmission(8);   // Address 8 on Bus 2
   Wire.requestFrom(8, 16);
   Wire.endTransmission();
   delay(50);
   myHTU21D.begin();            // Start Sensor 2 Bus 2
   delay(50);
   Hum = myHTU21D.readCompensatedHumidity();
   Temp = myHTU21D.readTemperature();

   
   Pin Numbers are Arduino interpretation.......
   ================================
   Arduino Pin  Esp Pin  ESP8266 01
   ================================
   Reset         0          0
   D2            2          2
   A4            4          1
   A5            5          3
   
   For ESP8266-01 Serial MUST Be Removed from the ESP8266 Master Sketch !!!
   
   All via 4 way 5V to 3V shifter......Arduino 5v side can take many more Slaves......

   Log the data to Spiffs or SDCard, in the example below I have used 3 SRAM Array's to feed the 3 SVG Charts
   adapt these to feed SPIFFS or SD Recording.........
   Thingspeak Channel........  https://thingspeak.com/channels/209159
*/

#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[] = "yourSSID";    //  your network SSID (name)
char pass[] = "YourPasswd";  // your network password
int status = WL_IDLE_STATUS;



unsigned long myChannelNumber = 209159;
const char * myWriteAPIKey = "YourWriteKey";
unsigned long ulNextTSMeas_ms=30000;

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

ADC_MODE(ADC_VCC);
const int led = 16;
int I1,y,y2,iicdata,SensInt,FCoUnt,ReSet,sensorReading,TSMeasCount,EnD;
int *pfTemp;
int *pfTemp1;
int *pfTemp2;
int *aDcData;
int COAlrm=0;
int SmAlrm=0;
unsigned long sAcnt=0;
unsigned long cAcnt=0;
unsigned long sAcnt2=0;
unsigned long cAcnt2=0;
unsigned long ulMeasCount=0;
unsigned long ulNextMeas_ms=0;
unsigned long ulReqcount,ulEnd,CoUnt;
float pfVcC,SensF,Hum,Temp;
String duration1,New0,New1,New2,New3;
char hostString[16] = {0};



int RTSDelay = 15;   // Set this for the response time of Your Arduino Data Fetch routine......
int ReFresh  = 500;  // Set this for the delay between I2C Requests, min 50ms......Server needs space to run....

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









void GetNano(){
  int lOop=0;
  New0="";
  New2="";
// ================================== Activate Arduino Interrupt, only 1 Interrupt needed, supply to all Slaves ============================

  digitalWrite(2, LOW);       // When Set Request To Send Active(interrupt FALLING) Slave will refresh data....
  delay(RTSDelay);            // This will make sure the Arduino is in the loop with fresh data...... 
  digitalWrite(2, HIGH);      // Set Request idle fresh data now in msg[]....
// ================================== DE-Activate Arduino Interrupt & Start of Arduino 1 I2C transfer ======================================
  Wire.beginTransmission(8);
  Wire.requestFrom(8, 16);    // request 16 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
  char c = Wire.read();       // receive a byte as character
  New0+=c;
  }
  Wire.endTransmission();
// ================================== End of Arduino 1 Transfer - Start of Arduino 2 transfer ==========================================
  Wire.beginTransmission(6);
  Wire.requestFrom(6, 16);    // request 16 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
   char c = Wire.read();      // receive a byte as character
    New2+=c;
  }
  Wire.endTransmission();
// =============================================== End of Arduino 2 I2C Transfer =======================================================

lOop=0;
New1=New0.substring(0,2);    // Very Simple error checking - error if not detected........
if(New1=="A1"){   
iicdata=4;
for(int i=2;i<12;i+=3){
char inChar = New0.charAt(i+2);
 int newt=inChar-48;        // Convert Numerical Char to int.....
     inChar = New0.charAt(i+1);
 int newt1=inChar-48;
     inChar = New0.charAt(i);
 int newt2=inChar-48;
 int newt3=(newt2*100)+(newt1*10)+newt;
 if(newt3==998){newt3+=2;}
 aDcData[iicdata]=newt3;
 iicdata++;
 }
}else{ FCoUnt++; }
New3=New2.substring(0,2);
if(New3=="A2"){             // Very Simple error checking - ignored if missing.........
iicdata=0;
for(int i=2;i<12;i+=3){
char inChar = New2.charAt(i+2);
 int newt=inChar-48;
     inChar = New2.charAt(i+1);
 int newt1=inChar-48;
     inChar = New2.charAt(i);
 int newt2=inChar-48;
 int newt3=(newt2*100)+(newt1*10)+newt;
 if(newt3==998){newt3+=2;}
 aDcData[iicdata]=newt3;
 iicdata++;
 }
}
   Hum = myHTU21D.readCompensatedHumidity();
   Temp = myHTU21D.readTemperature();
   CoUnt++;
   ulMeasCount++;
   if(ulMeasCount>250){ulMeasCount=1;}
   pfTemp[ulMeasCount] = Temp;
   pfTemp1[ulMeasCount] = aDcData[0];
   pfTemp2[ulMeasCount] = aDcData[4];
   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);
}





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 30 sec
          client.println();
          PageStr+=("<!DOCTYPE HTML>");
          PageStr+=("<html><title>Environment Monitor AQS</title>");         
          PageStr+=("<div style=\"float:right; \"><p>MQ-2 (Arduino 1) Trend<BR><img src=\"/test1.svg\" />");
          if(New3=="A2"){
            PageStr+=("<BR>MQ-2 (Arduino 2) Trend<BR><img src=\"/test2.svg\" />");
            client.println(PageStr);
            PageStr="";
          }
          PageStr+=("<BR><a href=\"/diag\">AQS System Info Page</a></p></div>");
          client.println(PageStr);
          PageStr="";         
          PageStr+=("<font color=\"#000000\"><body bgcolor=\"#a0dFfe\"><h1><p>Environment Monitor<BR>Air Quality Sensors<br>");
          PageStr+=("</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){
              float sensorReading1 = aDcData[4]*10;
              SensInt = sensorReading1/2;
              PageStr+=("<tr><th> Smoke Sensor Alarm Count = ");
              PageStr+=(sAcnt);
              PageStr+=(" </tr></th>");
              PageStr+=("<tr><th> CH4/Smoke");
            }else{
              float sensorReading1 = aDcData[5]*10;
              SensInt = sensorReading1/2;
              PageStr+=("<tr><th> Carbon Monoxide Alarm Count = ");
              PageStr+=(cAcnt);
              PageStr+=(" </tr></th>");
              PageStr+=("<tr><th> CO");
            }
            PageStr+=(" Sensor Value is : ");
            PageStr+=String(SensInt);
            PageStr+=(" mV</tr></th>");
          }
          client.println(PageStr);
          PageStr="";           
          if(New3=="A2"){
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 2; analogChannel++) {
            if(analogChannel==0){
              float sensorReading1 = aDcData[0]*10;
              SensInt = sensorReading1/2;
              PageStr+=("<tr><th>Arduino Two<BR>Smoke Sensor Alarm Count = ");
              PageStr+=(sAcnt2);
              PageStr+=(" </tr></th>");
              PageStr+=("<tr><th> CH4/Smoke");
            }else{
              float sensorReading1 = aDcData[1]*10;
              SensInt = sensorReading1/2;
              PageStr+=("<tr><th> Carbon Monoxide Alarm Count = ");
              PageStr+=(cAcnt2);
              PageStr+=(" </tr></th>");
              PageStr+=("<tr><th> CO");
            }
            PageStr+=(" Sensor Value is : ");
            PageStr+=String(SensInt);
            PageStr+=(" mV</tr></th>");
          }
       }

          PageStr+=("</div></h1></html>");
          client.println(PageStr);
   
    PageStr="";           
    ulReqcount++;
    // and stop the client
    delay(1);
    client.stop();   
    digitalWrite ( led, 0 );
    client.flush();
  }


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++;
                                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();
                                String PageStr="";
                                PageStr+=("<!DOCTYPE HTML>");
                                PageStr+=("<html><head><title>Environment Monitor AQS</title></head><body>");//
                                PageStr+=("<div style=\"float:right; \">");
                                PageStr+=("<p>Temperature Trend<BR><img src=\"/test.svg\" /><BR><a href=\"/\">Gas Sensor Page</a></p></div>");
                                PageStr+=("<font color=\"#0000FF\"><body bgcolor=\"#A0DFFE\">");
                                PageStr+=("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
                                PageStr+=("<h2>Environment Monitor AQS<BR>System Information</h2><BR>");
                                client.println(PageStr);
                                PageStr="";                               
                                PageStr+=(" I2C Arduino ID : ");
                                PageStr+=(New1);
                                PageStr+=("<BR> SHT21 Temperature : ");
                                PageStr+=(Temp);
                                PageStr+=(" C<BR> SHT21 Humidity : ");
                                PageStr+=(Hum);
                                PageStr+=(" %RH<BR> Arduino MQ-2 (A0) :  ");
                                float sensorReading1 = aDcData[4]*10;
                                int Sens0 = sensorReading1/2;
                                PageStr+=Sens0;// millivots
                                PageStr+=("mV<BR> Arduino MQ-7 (A1) : ");
                                float sensorReading2 = aDcData[5]/2;
                                SensF = sensorReading2 / 100;
                                PageStr+=SensF;
                                PageStr+=("V<BR> Arduino I2C 3V (A2) : ");
                                float sensorReading3 = aDcData[6]/2;
                                SensF = sensorReading3 / 100;
                                PageStr+=SensF;
                                PageStr+=("V<BR> Arduino I2C 5V (A3) : ");
                                float sensorReading4 = aDcData[7]/2;
                                SensF = sensorReading4 / 100;
                                PageStr+=SensF;
                                PageStr+=("V<BR> Arduino I2C Requests : ");
                                PageStr+=(CoUnt);
                                PageStr+=("<BR> Arduino I2C Errors : ");
                                PageStr+=(FCoUnt + (ReSet*10) );
                                PageStr+=("<BR> Arduino Resets : ");
                                PageStr+=(ReSet);
                                client.println(PageStr);
                                PageStr="";
                              if(New3=="A2"){
                                PageStr+=("<BR> I2C Arduino ID : ");
                                PageStr+=(New3);
                                PageStr+=("<BR> Arduino MQ-2 (A0) :  ");
                                float sensorReading1 = aDcData[0]*10;
                                int Sens0 = sensorReading1/2;
                                PageStr+=Sens0;// millivots
                                PageStr+=("mV<BR> Arduino MQ-7 (A1) : ");
                                float sensorReading2 = aDcData[1]/2;
                                SensF = sensorReading2 / 100;
                                PageStr+=SensF;
                                PageStr+=("V<BR> Arduino I2C 3V (A2) : ");
                                float sensorReading3 = aDcData[2]/2;
                                SensF = sensorReading3 / 100;
                                PageStr+=SensF;
                                PageStr+=("V<BR> Arduino I2C 5V (A3) : ");
                                float sensorReading4 = aDcData[3]/2;
                                SensF = sensorReading4 / 100;
                                PageStr+=SensF;
                                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>");
  PageStr="";
  diagdat="";
  // and stop the client
  delay(10);
  client.stop();
  digitalWrite ( led, 0 );
  client.flush();
  }


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(0, HIGH);  // Using Fash button
  delay(10);
  digitalWrite(0, LOW);
  delay(5);               // 5 millisec pulse to reset Arduino.....
  digitalWrite(0, HIGH);
  delay(3000);            // Arduino Startup delay
  Wire.begin(4,5);            // I2C Bus 0
  delay(70);
  digitalWrite(2, LOW);       // When Set Request To Send Active Slave will refresh data....
  delay(RTSDelay);               
  digitalWrite(2, HIGH);      // Set Request idle
  Wire.beginTransmission(8);
  Wire.requestFrom(8, 6);
  Wire.endTransmission();
  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 ( "/test2.svg", drawGraph1 );
  server.on ( "/test1.svg", drawGraph );
   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" );
  aDcData = new int[16];
  pfTemp = new int[251];
  pfTemp1 = new int[251];
  pfTemp2 = new int[251];   
  if (pfTemp==NULL || pfTemp2==NULL || aDcData==NULL)
  {
    Serial.println("Error in memory allocation!");
  }

 //Get Local I2C Data
 Wire.begin(4,5);
 delay(75);
 myHTU21D.begin();
 delay(200);
  Hum = myHTU21D.readCompensatedHumidity();
  Temp = myHTU21D.readTemperature();
  Serial.println("\r\nI2C T/H Sensor Data on BUS 0 : " + String(Temp) + " : "+ String(Hum) + "\r\n");
  ThingSpeak.begin(client);
  delay(10000);
  Serial.println("I2C Arduino Slave on BUS 0....Requesting Data...\r\n\r\n");
  //delay(100);
 // Wire.begin(4,5);            // I2C Bus 0
  delay(70);
  digitalWrite(2, LOW);       // When Set Request To Send Active Slave will refresh data....
  delay(RTSDelay);               
  digitalWrite(2, HIGH);      // Set Request idle
  Wire.beginTransmission(8);
  Wire.requestFrom(8, 16);
  Wire.endTransmission();
  digitalWrite ( led, 0 );
}

void loop( void ) {
   server.handleClient();
  if(FCoUnt>10){           // Reset Arduino after 10 errors from I2C......
  FCoUnt=0;
  ReSet++;                 // Reset ESP after 50 Errors......
  if(ReSet==5){ESP.restart();}
  Serial.println("\r\nResetting I2C Arduino Slave.......Time : " + duration1 + " Uptime\r\n");
  delay(10);
  digitalWrite(0, LOW);
  delay(5);               // 5 millisec pulse to reset Arduino.....
  digitalWrite(0, HIGH);
  delay(3000);            // Arduino Startup delay

}

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

  digitalWrite ( led, 1 );    // turn on the LED
  delay(1000);
  float pinVoltage = aDcData[4] / 2;
  float pinVoltage1 = aDcData[5 / 2];
  if(pinVoltage<=30 && pinVoltage1<=150){
    COAlrm=0;
    SmAlrm=0;
  }
}
if (millis()>=ulNextMeas_ms)
 {
    ulNextMeas_ms = millis()+ReFresh;
    GetNano();
 }
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 = aDcData[4] / 2;
  int pinVltage1 = aDcData[5] / 2;
  float pinVltage2 = aDcData[6] / 2;
  float pinVltage3 = aDcData[7] / 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 - float C
  ThingSpeak.setField(4,Hum);                 // SHT21 Hum Sensor Value - float %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 * 10)); // Error counter for last 24hours or since Last ESP8266 Reset
  ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  delay(500);
  */
   
 }

}



void drawGraph2() {
  String out = "";
  ulEnd=1;
  char temp[200];
  out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"260\" height=\"150\">\n";
  out += "<rect width=\"260\" 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);
  out = "";
}

void drawGraph1() {
  String out = "";
   ulEnd=1;
  char temp[200];
  out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"260\" height=\"150\">\n";
  out += "<rect width=\"260\" height=\"150\" fill=\"rgb(25, 30, 110)\" stroke-width=\"1\" stroke=\"rgb(255, 255, 255)\" />\n";
  out += "<g stroke=\"white\">\n"; 
  y = pfTemp1[ulEnd] * 3;
  for (int x = 0; x < ulMeasCount; x++) {
    y2 = pfTemp1[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";
  server.send ( 200, "image/svg+xml", out);
  out = "";
}


void drawGraph() {
  String out = "";
  ulEnd=1;
   char temp[200];
  out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"260\" height=\"150\">\n";
  out += "<rect width=\"260\" height=\"150\" fill=\"rgb(25, 30, 110)\" stroke-width=\"1\" stroke=\"rgb(255, 255, 255)\" />\n";
  out += "<g stroke=\"white\">\n"; 
    y = pfTemp2[ulEnd] * 3;
    for (int x = 0; x < ulMeasCount; x++) {
       y2 = pfTemp2[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";
   server.send ( 200, "image/svg+xml", out);
  out = "";
}


/*  ******************************************************  *
 *  Use this as the Slave sketch for uplaod to any arduino  *
 *  ******************************************************  *
#include <Wire.h>

String StRingV;
String ArduinoID = "A1";  //  A1 Primary slave needs to be present @ address 8 !!!
byte   ArduinoAD = 8;
char msg[16];
volatile boolean RuN = false;



void GetData(){
    StRingV=ArduinoID;
    for(int i=0;i<4;i++){  //A2177077120105A
     delay(1);
     unsigned int sensorValue = analogRead(i);
     delay(1);
     sensorValue=constrain(map(sensorValue, 0, 1023, 0, 999), 0, 999);
     if(sensorValue>=999){sensorValue=998;}
     //Serial.println(sensorValue);
     if(sensorValue<100){StRingV+="0";}
     if(sensorValue<10){StRingV+="0";}
     StRingV+=sensorValue;
     }
  StRingV+="A"; // Close array, these chars are only written not read.....
  StRingV.toCharArray(msg, 16);
  //Serial.println(StRingV);
}

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

void StaRt() {
  RuN = true;
}

void setup() {
  Wire.begin(ArduinoAD);               // join i2c bus with address #8
  Wire.onRequest(ReadSensors); // register event
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), StaRt, FALLING);
  //Serial.begin(115200);
  //Serial.println("\r\n\r\n");

}

void loop() {
  if (RuN == true) {
  GetData();
  RuN = false;
  }
}

*/


Slave Sketch

Code: Select all#include <Wire.h>

String StRingV;
String ArduinoID = "A1";  //  A1 Primary slave needs to be present @ address 8 !!!
byte   ArduinoAD = 8;
char msg[16];
volatile boolean RuN = false;



void GetData(){
    StRingV=ArduinoID;
    for(int i=0;i<4;i++){  //A2177077120105A
     delay(1);
     unsigned int sensorValue = analogRead(i);
     delay(1);
     sensorValue=constrain(map(sensorValue, 0, 1023, 0, 999), 0, 999);
     if(sensorValue>=999){sensorValue=998;}
     //Serial.println(sensorValue);
     if(sensorValue<100){StRingV+="0";}
     if(sensorValue<10){StRingV+="0";}
     StRingV+=sensorValue;
     }
  StRingV+="A"; // Close array, these chars are only written not read.....
  StRingV.toCharArray(msg, 16);
  //Serial.println(StRingV);
}

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

void StaRt() {
  RuN = true;
}

void setup() {
  Wire.begin(ArduinoAD);               // join i2c bus with address #8
  Wire.onRequest(ReadSensors); // register event
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), StaRt, FALLING);
  //Serial.begin(115200);
  //Serial.println("\r\n\r\n");

}

void loop() {
  if (RuN == true) {
  GetData();
  RuN = false;
  }
}