Chat freely about anything...

User avatar
By GengusKahn
#34249 To use the SPIFFS (SPI Flash File System) follow the instructions below, these are simple put the extracted file in the directory as instructed then an extra tool appears in the IDE "Tools" menu.
The data (files to be loaded to Flash, webpages + pictures etc.) is stored in a "data" folder in the sketch folder.

This is one of mine........
C:\Users\VideoEditor\Documents\Arduino\WLANMonitor\ESP-07-2DHT-BMP180-LCD_FSLOG\data

http://arduino.esp8266.com/versions/1.6.5-1160-gef26c5f/doc/reference.html#uploading-files-to-file-system


Some useful interaction with LCD and SPiffs to get 40 chars on a 16 char screen for both lines.......
This is a bit ugly but the conversion of data type is demonstrated.

Code: Select all/*
  LiquidCrystal Library - scrollDisplayLeft() and scrollDisplayRight()


 http://www.arduino.cc/en/Tutorial/LiquidCrystalScroll

 */

// include the library code:
#include <ESP8266WiFi.h>
#include "FS.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to YOUR LCD ADDRESS !!!
#include <NeoPixelBus.h>

#define pixelCount 40

NeoPixelBus strip = NeoPixelBus(pixelCount, 13);
uint16_t effectState = 0;

// WiFi connection
const char* ssid = "ssid";
const char* password = "Password";
const char* host = "EM-Pixel-LCD";
IPAddress apIP(192, 168, 6, 1);
WiFiServer server(80);
WiFiClient client;
extern "C"
{
#include "user_interface.h"
}
ADC_MODE(ADC_VCC);
#if defined(ARDUINO) && ARDUINO >= 100
#define printByte(args)  write(args);
#else
#define printByte(args)  print(args,BYTE);
#endif
String texttod = "This is a message from the Internet !...";  // 40 Bytes per Line....!!!
String texttod1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:+=|";
uint8_t bell[8]  = {0x4,0xe,0xe,0xe,0x1f,0x0,0x4};
uint8_t note[8]  = {0x2,0x3,0x2,0xe,0x1e,0xc,0x0};
uint8_t clock[8] = {0x0,0xe,0x15,0x17,0x11,0xe,0x0};
uint8_t heart[8] = {0x0,0xa,0x1f,0x1f,0xe,0x4,0x0};
uint8_t duck[8]  = {0x0,0xc,0x1d,0xf,0xf,0x6,0x0};
uint8_t check[8] = {0x0,0x1,0x3,0x16,0x1c,0x8,0x0};
uint8_t cross[8] = {0x0,0x1b,0xe,0x4,0xe,0x1b,0x0};
uint8_t retarrow[8] = {   0x1,0x1,0x5,0x9,0x1f,0x8,0x4};

////////////////////////////////////NTP
char tDigit;
String TiMeS,TMnow,MyNtP;                            // The current TimeStamp from Google....
int tIMeh,tIMem,tIMes,newt,newt1,inChar,SCsa,MNsa,HRsa;
boolean got_text = false;   //Print the Text to LCD if true......
int hr,mn,st,st1;  // Uptime Duration Counter......
String DsTable;             //Discarded parts if the Strings......
String tmtxt1,tmtxt2,DisTeXt0,DisTeXt1;              //Strings from the Web....
String theDate,theDate1,duration1,theDateTr;             // The current TimeStamp Date from Google....
unsigned long ulMeasCount=0;                         // values already measured
unsigned long ulMeasDelta_ms;                        // distance to next meas time
unsigned long ulNextMeas_ms;                         // next meas time
unsigned long ulReqcount;                            // how often has a valid page been requested
unsigned long ulReconncount;                         // how often did we connect to WiFi
String emailbutton = "off";
void setup(){
  strip.Begin();
  strip.Show();
  SetRandomSeed();
  lcd.init();                      // initialize the lcd
  lcd.backlight();
  delay(500);
    // initialize the SPIFFS
  if (!SPIFFS.begin()) {
       lcd.print("SPIFFSinitFailed");
       while(1);
       }
  // clear any old data....
     if (!SPIFFS.format()) {
      lcd.print("format failed");
      while(1);     
    }
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP("DDT-Display http://192.168.6.1");    // Connect to WiFi network
  lcd.clear();
  lcd.print("Connecting to ");
  lcd.setCursor(0, 1);
  lcd.print(ssid); 
  WiFi.begin(ssid, password); 
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1500);
    lcd.print(".");
  }
  server.begin();
    ///////////////////////////////
  // connect to Google and get time
  ///////////////////////////////
  ulMeasDelta_ms = ( (unsigned long) 60 * 1000);  // Sample Interval 60 Seconds, this can be placed above in the declarations....
  ulNextMeas_ms = millis()+ulMeasDelta_ms;
  WiFiClient client;
  while (!!!client.connect("google.com", 80)) {
    lcd.clear();
    lcd.print("connection fail!");
  }
  client.print("HEAD / HTTP/1.1\r\n\r\n");
  while(!!!client.available()) {
     yield();
  }
  while(client.available()){
  client.readStringUntil('\n');
   theDate1 = client.readStringUntil('\r'); //Date: Tue, 10 Nov 2015 19:55:38 GMT
    if (theDate1.startsWith("Date:")) {
      TiMeS=theDate1;
      theDate = theDate1.substring(6,23);
          client.flush();
          client.stop();             
          }
  }
  inChar = TiMeS.charAt(30);
  newt=inChar-48;             // Convert Numerical Char to int.....
  inChar = TiMeS.charAt(29);
  newt1=inChar-48;
  tIMes=(newt1*10)+newt;
 
  inChar = TiMeS.charAt(27);
  newt=inChar-48;
  inChar = TiMeS.charAt(26);
  newt1=inChar-48;
  tIMem=(newt1*10)+newt;
        theDateTr = theDate1.substring(6,35);
  inChar = TiMeS.charAt(24);
  newt=inChar-48;
  inChar = TiMeS.charAt(23);
  newt1=inChar-48;
  tIMeh=(newt1*10)+newt;
  MyNtP=" ";
  MyNtP+=theDate;
  if (tIMeh<10){MyNtP+="0";}
  MyNtP+=tIMeh;
  MyNtP+=":";
  if (tIMem<10){MyNtP+="0";}
  MyNtP+=tIMem;
  MyNtP+=":";
  if (tIMes<10){MyNtP+="0";}
  MyNtP+=tIMes;
  MyNtP+=" GMT";
 duration1 = " ";
   st1 = millis() / 1000;
   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); 
 HRsa=hr+tIMeh;
 MNsa=mn+tIMem;
 SCsa=st+tIMes;
if (SCsa>59){SCsa-=60;MNsa+=1;}
if (MNsa>59){MNsa-=60;HRsa+=1;}
if (HRsa>23){HRsa-=24;}
    TMnow = " ";
    TMnow += theDate;
    if (HRsa<10){TMnow += "0";}
    TMnow += HRsa;
    TMnow += ":";
    if (MNsa<10){TMnow += "0";}
    TMnow += MNsa;
    TMnow += ":";
    if (SCsa<10){TMnow += "0";}
    TMnow += SCsa;   
  // set up the LCD's Byte Memory
  lcd.createChar(0, bell);
  lcd.createChar(1, note);
  lcd.createChar(2, clock);
  lcd.createChar(3, heart);
  lcd.createChar(4, duck);
  lcd.createChar(5, check);
  lcd.createChar(6, cross);
  lcd.createChar(7, retarrow);
  lcd.clear();
  DisTeXt0 = MyNtP;
  DisTeXt1 = theDate1.substring(5,35);
neWTime();
lInE1();
}

///////////////////
// (re-)start WiFi
///////////////////
void WiFiStart()
{
  ulReconncount++;
  delay(1000);
  // Connect to WiFi network
  lcd.clear();
  lcd.print("Connecting to ");
  lcd.setCursor(0, 1);
  lcd.print(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1000);
    lcd.print(".");
  }
  lcd.clear();
  lcd.print("WiFi connected");
 
  // Start the server
  server.begin();
  WiFiClient client; 
  lcd.setCursor(0, 1);
  server.begin();
  lcd.print("Server started");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Network Started ");
  // Print the IP address       
  lcd.setCursor(0, 1);
  lcd.print("IP= "); 
  lcd.print(WiFi.localIP());
  lcd.clear();
  lcd.print("Environment | ");
  lcd.print(ulReconncount);
  lcd.setCursor(0, 1);
  lcd.print("Monitor   ");
  lcd.print(TMnow);
}

void wsysreset()
{
  //Perform challenge to user before getting here to reboot !!!
  //Make an attempt to send mail or other backup of log files then reboot
    ESP.restart();
}


void lInE1(){
int ttdlgt;

  lcd.clear();
  // Print a message to the LCD.
  lcd.print(DisTeXt0);
  lcd.setCursor(0, 1);
  lcd.print(DisTeXt1);     
  int ttdlgt0 = DisTeXt0.length();
  int ttdlgt1 = DisTeXt1.length();
  if (ttdlgt0>ttdlgt1){
   ttdlgt=ttdlgt0;
  }else{
   ttdlgt=ttdlgt1;
  }
  // scroll 16 positions + Extra text (string length - display length) to the left
  for (int positionCounter = 0; positionCounter < ttdlgt-16; positionCounter++) {
    // scroll one position left:
    lcd.scrollDisplayLeft();
    // wait a bit:
    delay(500);
  }
  delay(500);
  lcd.home();
}

void neWTime(){

 duration1 = " ";
   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); 
 HRsa=hr+tIMeh;
 MNsa=mn+tIMem;
 SCsa=st+tIMes;
if (SCsa>59){SCsa-=60;MNsa+=1;}
if (MNsa>59){MNsa-=60;HRsa+=1;}
if (HRsa>23){HRsa-=24;}
    TMnow = " ";
    TMnow += theDate;
    if (HRsa<10){TMnow += "0";}
    TMnow += HRsa;
    TMnow += ":";
    if (MNsa<10){TMnow += "0";}
    TMnow += MNsa;
    TMnow += ":";
    if (SCsa<10){TMnow += "0";}
    TMnow += SCsa;

}

//////////////////////////
// create HTTP 1.1 header
//////////////////////////
String MakeHTTPHeader(unsigned long ulLength)
{
  String sHeader;
 
  sHeader  = F("HTTP/1.1 200 OK\r\nContent-Length: ");
  sHeader += ulLength;
  sHeader += F("\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n");
 
  return(sHeader);
}


////////////////////
// make html footer
////////////////////
String MakeHTTPFooter()
{
  String sResponse;
 
  sResponse  = F(" ");
  sResponse += F("<BR>environmental.monitor.log@gmail.com<BR><FONT SIZE=-2>ESP8266 With DHT11 & BMP180 Sensors<BR><FONT SIZE=-2>Compiled Using ver. 1.6.5-1160-gef26c5f, built on Sep 30, 2015</body></html>");
  return(sResponse);
}



void loop() {
  neWTime();
  //
  // Check button for email trigger
  //
 int button = 0;           // variable for reading the pushbutton status
 button = digitalRead(0);  // read the state of the pushbutton on gpio 0
  if (button == LOW) {
  emailbutton = "Send";
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(F("Email Button...."));
  lcd.setCursor(0, 1);
  lcd.print(F("......Pressed.!!"));
  delay(1000);
  }
  if (emailbutton == "Send"){
  // There are three fun functions that implement different effects
  // uncomment one at a time and upload to see the effect

  // LoopAround(192, 200); // very interesting on rings of NeoPixels
  PickRandom(128);
  // FadeInFadeOutRinseRepeat(192);
 
  // start animating
  strip.StartAnimating();
  }
  /*
  // wait until no more animations are running
  while (strip.IsAnimating())
  {
    strip.UpdateAnimations();
    strip.Show();
    delay(31); // ~30hz change cycle
  }
  */
 
 
 
 
/////////////
// main loop
/////////////
  if (millis()==(ulNextMeas_ms-(ulMeasDelta_ms/2))){
  if (got_text == true){
   if (tmtxt1!=""){   
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(tmtxt1);
        lcd.setCursor(0, 1);
               if (tmtxt2==""){
         DisTeXt1 = TMnow;
         lcd.print(TMnow);
       }else{
         DisTeXt1 = tmtxt2;
         lcd.print(tmtxt2);
       }
       }
        else{  // Empty String returned CLEAR SCREEN
        got_text == false;
        }
        lInE1();
      }
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(theDateTr);
  lcd.setCursor(0, 1);
  lcd.print(TMnow.substring(18,26));
  // Ping or PIR and check email button Halt/Reboot
  if (TMnow.startsWith("00:04") || emailbutton.startsWith("Sen")) {// Set the time for the Log to be emailed
    lcd.print(F("Got email - data"));
/*     if(sendEmail()) {
     lcd.clear();
     lcd.print(F("mail sent......"));
     wsysreset();
      }
      else {
      lcd.clear();
      lcd.print(F("Email FAILED..!!!"));
      while(1);
      }*/
     
  emailbutton = "off";
  }

  }
  ///////////////////
  // do data logging
  ///////////////////
  if (millis()>=ulNextMeas_ms)
  {   
    ulNextMeas_ms = millis()+ulMeasDelta_ms;
  if (got_text == true){
   if (tmtxt1!=""){   
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(tmtxt1);
        lcd.setCursor(0, 1);
      if (tmtxt2==""){
         DisTeXt1 = TMnow;
         lcd.print(TMnow);
       }else{
         DisTeXt1 = tmtxt2;
         lcd.print(tmtxt2);
        }
        }
        else{  // Empty String returned CLEAR SCREEN
        got_text == false;
        }
      }
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(TMnow.substring(18,26));
  lcd.setCursor(0, 1);
  lcd.print(theDateTr);
  // Ping or PIR and check email button Halt/Reboot
  if (theDate.startsWith("00:04") || emailbutton.startsWith("Sen")) {// Set the time for the Log to be emailed
    lcd.print(F("Got email - data"));
/*     if(sendEmail()) {
     lcd.clear();
     lcd.print(F("mail sent......"));
     wsysreset();
      }
      else {
      lcd.clear();
      lcd.print(F("Email FAILED..!!!"));
      while(1);
      }*/
     
  emailbutton = "off";
  }
  }


     
  //////////////////////////////
  // check if WLAN is connected
  //////////////////////////////
 
  if (WiFi.status() != WL_CONNECTED)
  {
    WiFiStart();
  }
 
  ///////////////////////////////////
  // Check if a client has connected
  ///////////////////////////////////
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }
 
  // Wait until the client sends some data
  unsigned long ultimeout = millis()+250;
  while(!client.available() && (millis()<ultimeout) )
  {
    delay(1);
  }
  if(millis()>ultimeout)
  {
    return;
  }
 
  /////////////////////////////////////
  // Read the first line of the request
  /////////////////////////////////////
  String sRequest = client.readStringUntil('\r');
  client.flush();
 
  // stop client, if request is empty
  if(sRequest=="")
  {
    client.stop();
    return;
  }
 
  // get path; end of path is either space or ?
  // Syntax is e.g. GET /?show=1234 HTTP/1.1
  String sPath="",sParam="", sCmd="";
  String sGetstart="GET ";
  int iStart,iEndSpace,iEndQuest;
  iStart = sRequest.indexOf(sGetstart);
  if (iStart>=0)
  {
    iStart+=+sGetstart.length();
    iEndSpace = sRequest.indexOf(" ",iStart);
    iEndQuest = sRequest.indexOf("?",iStart);
   
    // are there parameters?
    if(iEndSpace>0)
    {
      if(iEndQuest>0)
      {
        // there are parameters
        sPath  = sRequest.substring(iStart,iEndQuest);
        sParam = sRequest.substring(iEndQuest,iEndSpace);
      }
      else
      {
        // NO parameters
        sPath  = sRequest.substring(iStart,iEndSpace);
      }
    }
  }
 
 
  ///////////////////////////
  // format the html response
  ///////////////////////////
  String sResponse,sResponse2,sHeader;
 
  /////////////////////////////////
  //  Update LCD with text from Web
  /////////////////////////////////
  //_________________________________________________________________
  // /ajax_inputs&L1=123456789&L2=abcdefghi&nocache=968337.7823963541
  //  1-9 on Line 1 and a - i on line 2
  //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
if (sPath.startsWith("/ajax_inputs&L1="))
   {
     ulReqcount++;
     tmtxt1="";
     tmtxt2="";
    got_text = true;                    // print the received text to the LCD if found
File in = SPIFFS.open("/temp.txt", "w");     
  if (in) {
    in.print(sPath);
    in.close();
      }
    else {
      lcd.clear();
      lcd.print("rOr Temp.TXT");
      while(1);
    }
     in = SPIFFS.open("/temp.txt", "r");
     in.setTimeout(0);
String Dtmtxt = in.readStringUntil('=');
       tmtxt1 += in.readStringUntil('&');
       Dtmtxt = in.readStringUntil('=');
       tmtxt2 += in.readStringUntil('&');
     in.close();
       tmtxt1.replace("%20", " ");
       tmtxt2.replace("%20", " ");
       DisTeXt0 = tmtxt1;
       if (tmtxt2==""){
         neWTime();
         DisTeXt1 = TMnow;
       }else{
         DisTeXt1 = tmtxt2;
       }
       lInE1();
    }
    if (sPath.startsWith("/pixel_inputs&L1="))
   {
     ulReqcount++;
     tmtxt1="";
     tmtxt2="";
    got_text = true;                    // print the received text to the LCD if found
File in = SPIFFS.open("/temp.txt", "w");     
  if (in) {
    in.print(sPath);
    in.close();
      }
    else {
      lcd.clear();
      lcd.print("rOr Temp.TXT");
      while(1);
    }
     in = SPIFFS.open("/temp.txt", "r");
     in.setTimeout(0);
String Dtmtxt = in.readStringUntil('=');
       tmtxt1 += in.readStringUntil('&');
       Dtmtxt = in.readStringUntil('=');
       tmtxt2 += in.readStringUntil('&');
     in.close();
       tmtxt1.replace("%20", " ");
       tmtxt2.replace("%20", " ");
       if (tmtxt1 == "animate"){emailbutton = "Send";}
       DisTeXt0 = tmtxt1;
       DisTeXt1 = tmtxt2;
       lInE1();
    }
  ///////////////////////////////////////
  // format the html page for LCD Input /
  ///////////////////////////////////////
 if(sPath=="/")
  {
    ulReqcount++;
    sResponse  = F("<html>\n<head>\n<title>Environment Monitor Text to LCD</title>\n<script>\n\n");   
    sResponse += F("strLine1 = \"\";\nstrLine2 = \"\";\n\nfunction SendText()\n{\nnocache = \"&nocache=\" + Math.random() * 1000000;\nvar request = new XMLHttpRequest();\n\nstrLine1 = \"&L1=\" + document.getElementById(\"txt_form\").line1LCD.value;\nstrLine2 = \"&L2=\" + document.getElementById(\"txt_form\").line2LCD.value;\n\n");
    sResponse += F("request.open(\"GET\", \"ajax_inputs\" + strLine1 + strLine2 + nocache, true);\nrequest.send(null);\n}\n</script>\n<body>\n<h1>Environment Monitor<BR>LCD Text Input</h1>\n");
    sResponse += F("<BR><a href=\"/graphic2\">Pressure Graph Page</a><BR><a href=\"/pressure\">Pressure Gauge Page</a><BR><a href=\"/monitor\">Sensor Gauge Page</a><BR><a href=\"/graphic\">Sensor Graph Page</a><BR><a href=\"/table\">Sensor Datalog Page</a><BR><a href=\"/diag\">Diagnostics Information Page</a><BR>\n"); 
    sResponse += F("<body onload=\"GetESP8266IO()\">\n<h1><FONT SIZE=-1>Enter text to send to ESP81266 LCD:</h1>\n<form id=\"txt_form\" name=\"frmText\">\n<label>Line 1: <input type=\"text\" name=\"line1LCD\" size=\"40\" maxlength=\"40\" /></label><br /><br />\n<label>Line 2: <input type=\"text\" name=\"line2LCD\" size=\"40\" maxlength=\"40\" /></label>\n");
    sResponse += F("</form>\n<br />\n<input type=\"submit\" value=\"Send Text\" onclick=\"SendText()\" />\n\n");   
    sResponse2 = F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"><BR>LCD Text Input<BR>\n");
    sResponse2 += F("</div>\n<div style=\"clear:both;\"></div><p>");
    sResponse2 += MakeHTTPFooter().c_str();
        // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length()+sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
}

  ///////////////////////////////////////
  // format the html page for LCD Input /
  ///////////////////////////////////////
else if(sPath=="/lights")
  {
    ulReqcount++;
    sResponse  = F("<html>\n<head>\n<title>Environment Monitor Text to LCD</title>\n<script>\n\n");   
    sResponse += F("strLine1 = \"\";\nstrLine2 = \"\";\n\nfunction SendText()\n{\nnocache = \"&nocache=\" + Math.random() * 1000000;\nvar request = new XMLHttpRequest();\n\nstrLine1 = \"&L1=\" + document.getElementById(\"txt_form\").line1LCD.value;\nstrLine2 = \"&L2=\" + document.getElementById(\"txt_form\").line2LCD.value;\n\n");
    sResponse += F("request.open(\"GET\", \"pixel_inputs\" + strLine1 + strLine2 + nocache, true);\nrequest.send(null);\n}\n</script>\n<body>\n<h1>Environment Monitor<BR>LCD Text Input</h1>\n");
    sResponse += F("<BR><a href=\"/graphic2\">Pressure Graph Page</a><BR><a href=\"/pressure\">Pressure Gauge Page</a><BR><a href=\"/monitor\">Sensor Gauge Page</a><BR><a href=\"/graphic\">Sensor Graph Page</a><BR><a href=\"/table\">Sensor Datalog Page</a><BR><a href=\"/diag\">Diagnostics Information Page</a><BR>\n"); 
    sResponse += F("<body onload=\"GetESP8266IO()\">\n<h1><FONT SIZE=-1>Enter text to send to ESP81266 LCD:</h1>\n<form id=\"txt_form\" name=\"frmText\">\n<label>Line 1: <input type=\"text\" name=\"line1LCD\" size=\"40\" maxlength=\"40\" /></label><br /><br />\n<label>Line 2: <input type=\"text\" name=\"line2LCD\" size=\"40\" maxlength=\"40\" /></label>\n");
    sResponse += F("</form>\n<br />\n<input type=\"submit\" value=\"Send Text\" onclick=\"SendText()\" />\n\n");   
    sResponse2 = F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"><BR>LCD Text Input<BR>\n");
    sResponse2 += F("</div>\n<div style=\"clear:both;\"></div><p>");
    sResponse2 += MakeHTTPFooter().c_str();
        // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length()+sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
}


else if(sPath=="/yfireset")
  {
    ulReqcount++;
   
                                client.println("HTTP/1.1 200 OK");
                                client.println("Content-Type: text/html");
                                client.println("Connection: close");
                                client.println();
                                client.println("<!DOCTYPE HTML>");
                                client.print("<html><head><title>Environment Monitor</title></head><body>");
                                client.print("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
                                client.print("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
                                client.print("<h1>Environment Monitor<BR>WiFi Reset Page </h1><BR><a href=\"/graphic2\">Pressure Graph Page</a><BR><a href=\"/pressure\">Pressure Gauge Page</a>");
                                client.print("<BR><a href=\"/monitor\">Sensor Gauges Page</a><BR><a href=\"/graphic\">Sensor Graph Page</a><BR><a href=\"/table\">Sensor Datalog Page</a><BR><BR><BR><BR>Restarted WiFiConnections = ");
                                client.print(ulReconncount);
                                client.print("<BR><FONT SIZE=-2>environmental.monitor.log@gmail.com<BR><FONT SIZE=-2>ESP8266 With DHT11 & BMP180 Sensors<BR>");
                                client.print("<FONT SIZE=-2>Compiled Using ver. 1.6.5-1160-gef26c5f, built on Sep 30, 2015<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>");

  WiFiStart();
  }
  else if(sPath=="/diag")
  {   
     float   servolt1 = 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();
                                client.println("<!DOCTYPE HTML>");
                                client.print("<html><head><title>Environment Monitor</title></head><body>");
                                client.print("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
                                client.print("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
                                client.print("<h1>Environment Monitor<BR>SDK Diagnostic Information</h1><BR><a href=\"/graphic2\">Pressure Graph Page</a><BR><a href=\"/pressure\">Pressure Gauge Page</a>");
                                client.print("<BR><a href=\"/monitor\">Sensor Gauges Page</a><BR><a href=\"/graphic\">Sensor Graph Page</a><BR><a href=\"/table\">Sensor Datalog Page</a><BR><a href=\"/\">Monitor LCD Text Input Page</a><BR>Restarted WiFiConnections = ");
                               String diagdat="";
                                diagdat+=ulReconncount;
                                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.print((uint32_t)system_get_free_heap_size()/1024);
                                diagdat=" KBytes<BR>  Logged Sample Count = ";
                                diagdat+=ulMeasCount;
                                diagdat+="<BR>  Total Sample points in 24 Hours = 1440<BR>  Minimum Sample Logging Interval = 1 Minutes<BR>  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.print(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.print(diagdat);
                                client.printf("  ESP8266 Chip id = %08X\n", ESP.getChipId());
                                diagdat="<BR>  System Instruction Cycles Per Second = ";
                                diagdat+=speedcnt*1000; 
                                diagdat+="<BR>  Last System Restart Time = ";
                                diagdat+=MyNtP;
                                diagdat+="<BR>  Last System Restart Reason = ";
                                diagdat+=ESP.getResetInfo();                               
                                diagdat+="<BR>  System Time = ";
                                diagdat+=TMnow;                               
                                diagdat+=" (Last Recorded Sample Time)<BR>  System VCC = ";
                                diagdat+=servolt1/1000, 3;
                                diagdat+=" V <BR>  Datalog File Size in Bytes = N/A";
                                //diagdat+=Dfsize;
                                diagdat+="<BR>  System Uptime =";
                                diagdat+=duration1;
                                client.print(diagdat);
                                client.print("<BR><FONT SIZE=-2>environmental.monitor.log@gmail.com<BR><FONT SIZE=-2>ESP8266 With DHT11 & BMP180 Sensors<BR><FONT SIZE=-2>Compiled Using ver. 1.6.5-1160-gef26c5f, built on Sep 30, 2015<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="";
  }
   else if(sPath=="/srestart")
  {
                                client.println("HTTP/1.1 200 OK");
                                client.println("Content-Type: text/html");
                                client.println("Connection: close");
                                client.println();
                                client.println("<!DOCTYPE HTML>");
                                client.print("<html><head><title>Environment Monitor</title></head><body>");
                                client.print("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
                                client.print("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
                                client.print("<h1>Environment Monitor<BR>Please wait 10 Seconds......<BR><FONT SIZE=+2>System Reset Page !!!! </h1><BR><a href=\"/graphic2\">Pressure Graph Page</a><BR><a href=\"/pressure\">Pressure Gauge Page</a>");
                                client.print("<BR><a href=\"/monitor\">Sensor Gauges Page</a><BR><a href=\"/graphic\">Sensor Graph Page</a><BR><a href=\"/table\">Sensor Datalog Page</a><BR><a href=\"/diag\">Diagnostics Information Page</a><BR><a href=\"/\">Monitor LCD Text Input Page</a><BR><BR><BR><BR>Restarted WiFiConnections = ");
                                client.print(ulReconncount);
                                client.print("<BR><BR><BR><FONT SIZE=-2>environmental.monitor.log@gmail.com<BR><FONT SIZE=-2>ESP8266 With DHT11 & BMP180 Sensors<BR>");
                                client.print("<FONT SIZE=-2>Compiled Using ver. 1.6.5-1160-gef26c5f, built on Sep 30, 2015<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>");
client.stop();
wsysreset();
  }
  else
////////////////////////////
// 404 for non-matching path
////////////////////////////
  {
    sResponse="<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server, What did you sk for?.</p></body></html>";
    ulReqcount++;
    sHeader  = F("HTTP/1.1 404 Not found\r\nContent-Length: ");
    sHeader += sResponse.length();
    sHeader += F("\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n");
   
    // Send the response to the client
    client.print(sHeader);
    client.print(sResponse);
  }
 
  // and stop the client
  client.stop();

}

void FadeInFadeOutRinseRepeat(uint8_t peak)
{
  if (effectState == 0)
  {
    for (uint8_t pixel = 0; pixel < pixelCount; pixel++)
    {
      uint16_t time = random(800,1000);
      strip.LinearFadePixelColor(time, pixel, RgbColor(random(peak), random(peak), random(peak)));
    }
  }
  else if (effectState == 1)
  {
    for (uint8_t pixel = 0; pixel < pixelCount; pixel++)
    {
      uint16_t time = random(600,700);
      strip.LinearFadePixelColor(time, pixel, RgbColor(0, 0, 0));
    }
  }
  effectState = (effectState + 1) % 2; // next effectState and keep within the number of effectStates
 
}

void PickRandom(uint8_t peak)
{

  // pick random set of pixels to animate
  uint8_t count = random(pixelCount);
  while (count > 0)
  {
    uint8_t pixel = random(pixelCount);
   
    // configure the animations
    RgbColor color; // = strip.getPixelColor(pixel);

    color = RgbColor(random(peak), random(peak), random(peak));

   
    uint16_t time = random(100,400);
    strip.LinearFadePixelColor( time, pixel, color);
   
    count--;
  }
}

void LoopAround(uint8_t peak, uint16_t speed)
{
  // Looping around the ring sample
  uint16_t prevPixel;
  RgbColor prevColor;
 
  // fade previous one dark
  prevPixel = (effectState + (pixelCount - 5)) % pixelCount;
  strip.LinearFadePixelColor(speed, prevPixel, RgbColor(0, 0, 0));
 
  // fade previous one dark
  prevPixel = (effectState + (pixelCount - 4)) % pixelCount;
  prevColor = strip.GetPixelColor( prevPixel );
  prevColor.Darken(prevColor.CalculateBrightness() / 2);
  strip.LinearFadePixelColor(speed, prevPixel, prevColor);
 
  // fade previous one dark
  prevPixel = (effectState + (pixelCount - 3)) % pixelCount;
  prevColor = strip.GetPixelColor( prevPixel );
  prevColor.Darken(prevColor.CalculateBrightness() / 2);
  strip.LinearFadePixelColor(speed, prevPixel, prevColor);
 
  // fade previous one dark
  prevPixel = (effectState + (pixelCount - 2)) % pixelCount;
  prevColor = strip.GetPixelColor( prevPixel );
  prevColor.Darken(prevColor.CalculateBrightness() / 2);
  strip.LinearFadePixelColor(speed, prevPixel, prevColor);
 
  // fade previous one dark
  prevPixel = (effectState + (pixelCount - 1)) % pixelCount;
  prevColor = strip.GetPixelColor( prevPixel );
  prevColor.Darken(prevColor.CalculateBrightness() / 2);
  strip.LinearFadePixelColor(speed, prevPixel, prevColor);
 
  // fade current one light
  strip.LinearFadePixelColor(speed, effectState, RgbColor(random(peak), random(peak), random(peak)));
  effectState = (effectState + 1) % pixelCount;
}

void SetRandomSeed()
{
  uint32_t seed;
 
  // random works best with a seed that can use 31 bits
  // analogRead on a unconnected pin tends toward less than four bits
  seed = analogRead(0);
  delay(1);
 
  for (int shifts = 3; shifts < 31; shifts += 3)
  {
    seed ^= analogRead(0) << shifts;
    delay(1);
  }
 
  // Serial.println(seed);
  randomSeed(seed);
}
User avatar
By danbicks
#34649 Hi @GengusKahn,

I cant seem to find the example I think you posted for NTP time in to variables, wanted to check NTP to see if a date and time has passed and then to trigger an event.

Did you post something like this?

Cheers mate

Dans
User avatar
By GengusKahn
#34658 The NTP can be retrieved at alternate segments to the data gathering......

Code: Select all  ///////////////////////////////
  // connect to NTP and get time
  ///////////////////////////////
  WiFiClient client;
  while (!!!client.connect("google.com", 80)) {
    lcd.clear();
    lcd.print("connection fail!");
  }
  client.print("HEAD / HTTP/1.1\r\n\r\n");
  while(!!!client.available()) {
     yield();
  }
  while(client.available()){
  client.readStringUntil('\n');
  String theDate1 = client.readStringUntil('\r'); //Date: Tue, 10 Nov 2015 19:55:38 GMT
    if (theDate1.startsWith("Date:")) {
      TiMeS=theDate1;
      theDate = theDate1.substring(11,17);
          client.flush();
          client.stop();             
          }
  inChar = TiMeS.charAt(30);
  newt=inChar-48;             // Convert Numerical Char to int.....
  inChar = TiMeS.charAt(29);
  newt1=inChar-48;
  tIMes=(newt1*10)+newt;
 
  inChar = TiMeS.charAt(27);
  newt=inChar-48;
  inChar = TiMeS.charAt(26);
  newt1=inChar-48;
  tIMem=(newt1*10)+newt;
 
  inChar = TiMeS.charAt(24);
  newt=inChar-48;
  inChar = TiMeS.charAt(23);
  newt1=inChar-48;
  tIMeh=(newt1*10)+newt;
  MyNtP=" ";
  MyNtP+=theDate;
  MyNtP+=" ";
  if (tIMeh<10){MyNtP+="0";}
  MyNtP+=tIMeh;
  MyNtP+=":";
  if (tIMem<10){MyNtP+="0";}
  MyNtP+=tIMem;
  MyNtP+=":";
  if (tIMes<10){MyNtP+="0";}
  MyNtP+=tIMes;
  MyNtP+=" GMT";
  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); 
int HRsa=hr+tIMeh;
int MNsa=mn+tIMem;
int SCsa=st+tIMes;
if (SCsa>59){SCsa-=60;MNsa+=1;}
if (MNsa>59){MNsa-=60;HRsa+=1;}
if (HRsa>23){HRsa-=24;}
    TMnow="";
    if (HRsa<10){TMnow += "0";}
    TMnow += HRsa;
    TMnow += ":";
    if (MNsa<10){TMnow += "0";}
    TMnow += MNsa;
    TMnow += ":";
    if (SCsa<10){TMnow += "0";}
    TMnow += SCsa; 
}



Code: Select all  ///////////////////
  // do data logging
  ///////////////////
  if (millis()>=ulNextMeas_ms)
  {   
    ulNextMeas_ms = millis()+ulMeasDelta_ms;   
    char status;
  status = pressure.startTemperature();
  if (status != 0)
  {
    // Wait for the measurement to complete:

    delay(status);

    // Retrieve the completed temperature measurement:
    // Note that the measurement is stored in the variable T.
    // Use '&T' to provide the address of T to the function.
    // Function returns 1 if successful, 0 if failure.
  }
    status = pressure.getTemperature(T);
          status = pressure.startPressure(3);
      if (status != 0)
      {
        // Wait for the measurement to complete:
        delay(status);

        // Retrieve the completed pressure measurement:
        // Note that the measurement is stored in the variable P.           http://bbc.in/1HIlwwK
        // Use '&P' to provide the address of P.
        // Note also that the function requires the previous temperature measurement (T).
        // (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)
        // Function returns 1 if successful, 0 if failure.
      }
        status = pressure.getPressure(P,T);
String  theDatet = theDate;
    theDatet.replace("2015 ", "- ");   
if (theDatet==""){theDatet="Missed        NTP";}
    pfHum1 = dht1.readHumidity();
    pfTemp1 = dht1.readTemperature();
    pfTemp = dht.readTemperature();
    pfHum = dht.readHumidity();   
for (int lc=0;lc<6;lc++){
 if (pfTemp==11.11){   // Modified DHT Library to produce this instead of "String nan" as it messes with Data Types....
    delay(2000);
    pfTemp = dht.readTemperature();
    pfHum = dht.readHumidity();   
    }
}
for (int lc=0;lc<6;lc++){
 if (pfTemp1==11.11){
    delay(2000);
    pfTemp1 = dht1.readTemperature();
    pfHum1 = dht1.readHumidity();   
    }
}
    //pfTemp = pfTemp-=2;  // Calibrated with DHT22 !!!! Cheap Sensors.....use this to calibrate
    //pfHum = pfHum-=10;   // Calibrated with DHT22 !!!!
    lastdata="";
    lastdata += pfTemp;
    lastdata += ",hum=";
    lastdata += pfHum;
    lastdata += ",temp1=";
    lastdata += pfTemp1;
    lastdata += ",hum1=";
    lastdata += pfHum1;
 String logdata = "[";
  logdata += "'"; 
  logdata += theDatet;
  logdata += "'";
  logdata += ",";
  logdata += pfTemp;
  if(pfTemp<10){logdata += "0";}   // Keep 64 Byte Record Size
  logdata += ",";
  logdata += pfHum; 
  logdata += ",";
  logdata += pfTemp1;
  if(pfTemp1<10){logdata += "0";}   // Keep 64 Byte Record Size
  logdata += ",";
  logdata += pfHum1;
  logdata += ",";
  logdata += pfVcC/1000;
  logdata += ",";
  logdata += T;   
  logdata += "]";
  logdata += P;
  if(P<1000){logdata += "0";}   // Keep 64 Byte Record Size
  logdata += ",";
 lastpres = P;
File logF = SPIFFS.open("/humidlog.CSV", "a");     
  if (logF) {
    logF.print(logdata);
    logF.close();
    ulMeasCount++;   
      }
    else {
      lcd.clear();
      lcd.print("rOr humidlog.CSV");
      while(1);
    } 
  }

if (millis()==(ulNextMeas_ms-(ulMeasDelta_ms/2))){
  if (got_text == true){
   if (tmtxt1!=""){     
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(tmtxt1);
        lcd.setCursor(0, 1);
        lcd.print(tmtxt2);
        delay(5000);
        }
        else{  // Empty String returned CLEAR SCREEN
        got_text == false;
        }
      }
  //
  // Check button for email trigger
  //
 int button = 0;           // variable for reading the pushbutton status
 button = digitalRead(0);  // read the state of the pushbutton on gpio 0
  if (button == LOW) {
  emailbutton = "Send";
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(F("Email Button...."));
  lcd.setCursor(0, 1);
  lcd.print(F("......Pressed.!!"));
  delay(1000);
  }   

  WiFiClient client;
 while (!!!client.connect("google.com", 80)) {
  }
  client.print("HEAD / HTTP/1.1\r\n\r\n");
 while(!!!client.available()) {
  yield();
  }
 while(client.available()){
  client.readStringUntil('\n');
  String theDate1 = client.readStringUntil('\r'); // this returns, Date: Tue, 10 Nov 2015 19:55:38 GMT
    if (theDate1.startsWith("Date:")) {   
         theDate = theDate1.substring(11,31);
         client.stop(); 
        }
  }
//  Use this instead of ESP.getVcc() for modules with LDR Fitted, Alter Display Text from Volts!!!
//  This is the Start of the LDR Sensor Measurement Percent/10 Saturation of LDR
//  Keep the Scale relavant for Line Graph or select Different Axis.....
/*
delay(25);
int pfVcC = 10-(constrain(map((analogRead(A0)), 40, 900, 1, 10), 1, 10)) ;
delay(25);
//
//  This is the End of the LDR Sensor Measurement
//
 

*/
 emailtime = theDate.substring(12,17);  // Create the Time trigger.............
  delay(50);
  pfVcC =  ESP.getVcc();   // Only use this if Nothing connected to TOUT / ADC
  delay(150);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(pfTemp);
  lcd.setCursor(2, 0);
  lcd.print(F("C "));
  lcd.print(pfHum);
  lcd.setCursor(6, 0);
  lcd.print(F("% "));
  lcd.print(pfTemp1);
  lcd.setCursor(10, 0);
  lcd.print(F("C "));
  lcd.print(pfHum1);
  lcd.setCursor(14, 0);
  lcd.print(F("% ")); 
  lcd.setCursor(0, 1);
  lcd.print(P);
  lcd.print(F("mb")); 
  lcd.setCursor(11, 1);
  lcd.print(emailtime);
  delay(1000);
  // Ping or PIR and check email button Halt/Reboot
// Compare the time trigger...............
  if (emailtime.startsWith("08:11") || emailbutton.startsWith("Sen")) {// Set the time for the Log to be emailed
    lcd.print(F("Got email - data"));
     if(sendEmail()) {
     lcd.clear();
     lcd.print(F("mail sent......"));
     wsysreset();
      }
      else {
      lcd.clear();
      lcd.print(F("Email FAILED..!!!"));
      while(1);
      }
     
  emailbutton = "off";
  }
  }
User avatar
By danbicks
#34686 @GengusKahn,

Thank you buddy, I have hacked your code a little and can extract the hour/min and second in to int variables from google awesome. This alleviates NTP dedicated library etc.

Many thanks for this It will be a breeze now to schedule events based on time and day. I will post a simple example for others once I have a tidy version :)

Cheers mate, keep publishing your great work.

Dans