ESP8266 + spiffs+ webserver + Sr04
Posted: Fri Feb 08, 2019 12:30 pm
Can someone help me with this,its supposed to write the logs of the sr04 into history.json . which is can call in the associated web page , It does not seem to work on the ESP8266. I am using an sr04 ultra-sonic sensor.
the same code works on the lolin nodemcu v3
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <FS.h>
#include <TimeLib.h>
#include <NtpClientLib.h>
#include <ArduinoJson.h>
#define ssid "XXXXXXXX" // WiFi SSID
#define password "XXXXXXXXX" // WiFi password
#define trig 0
#define echo 2
#define HISTORY_FILE "/history.json"
float t = 0 ;
int sizeHist = 26800 ; // (7h x 12pts) - History size
const long intervalHist = 1000 * 60 * 60; // 5 measures / hours
ESP8266WebServer server ( 80 );
StaticJsonBuffer<10000> jsonBuffer; // Current JSON static buffer
JsonObject& root = jsonBuffer.createObject();
JsonArray& timestamp = root.createNestedArray("timestamp");
JsonArray& hist_t = root.createNestedArray("t");
char json[10000]; // JSON export buffer
void sendMesures() {
String json = "{\"t\":\"" + String(t) + "\"}";
server.send(200, "application/json", json);
Serial.println("Send measures");
}
void sendTabMesures() {
double temp = root["t"][0];
String json = "[";
json += "{\"mesure\":\"Température\",\"valeur\":\"" + String(t) + "\",\"unite\":\"°C\",\"glyph\":\"glyphicon-indent-left\",\"precedente\":\"" + String(temp) + "\"}";
json += "]";
server.send(200, "application/json", json);
Serial.println("Send data tab");
}
void sendHistory(){
root.printTo(json, sizeof(json));
server.send(200, "application/json", json);
Serial.println("Send History");
}
void loadHistory(){
File file = SPIFFS.open(HISTORY_FILE, "r");
if (!file){
Serial.println("Aucun historique existe - No History Exist");
} else {
size_t size = file.size();
if ( size == 0 ) {
Serial.println("Fichier historique vide - History file empty !");
} else {
std::unique_ptr<char[]> buf (new char[size]);
file.readBytes(buf.get(), size);
JsonObject& root = jsonBuffer.parseObject(buf.get());
if (!root.success()) {
Serial.println(" Impossible to read JSON file");
} else {
Serial.println(" History loaded");
root.prettyPrintTo(Serial);
}
}
file.close();
}
}
void saveHistory(){
Serial.println("Save History");
File historyFile = SPIFFS.open(HISTORY_FILE, "w");
root.printTo(historyFile); // Export and save JSON object to SPIFFS area
Serial.println("History save");
historyFile.close();
}
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
NTP.onNTPSyncEvent([](NTPSyncEvent_t error) {
if (error) {
Serial.print("Time Sync error: ");
if (error == noResponse)
Serial.println("NTP server not reachable");
else if (error == invalidAddress)
Serial.println("Invalid NTP server address");
}
else {
Serial.print("Got NTP time: ");
Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync()));
}
});
//
NTP.begin("pool.ntp.org", 0, true);
NTP.setInterval(60000);
delay(500);
Serial.begin ( 115200 );
WiFi.begin ( ssid, password );
int tentativeWiFi = 0;
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 ); Serial.print ( "." );
tentativeWiFi++;
if ( tentativeWiFi > 20 ) {
ESP.reset();
while(true)
delay(1);
}
}
// Connexion WiFi établie / WiFi connexion is OK
Serial.println ( "" );
Serial.print ( "Connected to " ); Serial.println ( ssid );
Serial.print ( "IP address: " ); Serial.println ( WiFi.localIP() );
if (!SPIFFS.begin()) {
Serial.println("SPIFFS Mount failed");
} else {
Serial.println("SPIFFS Mount succesfull");
loadHistory();
}
delay(50);
server.on("/tabmesures.json", sendTabMesures);
server.on("/mesures.json", sendMesures);
//server.on("/gpio", updateGpio);
server.on("/graph_temp.json", sendHistory);
server.serveStatic("/js", SPIFFS, "/js");
server.serveStatic("/css", SPIFFS, "/css");
server.serveStatic("/img", SPIFFS, "/img");
server.serveStatic("/", SPIFFS, "/index.html");
server.begin();
Serial.println ( "HTTP server started" );
Serial.print("Uptime :");
Serial.println(NTP.getUptime());
Serial.print("LastBootTime :");
Serial.println(NTP.getLastBootTime());
}
void loop() {
// put your main code here, to run repeatedly:
server.handleClient();
float duration, distance;
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = duration / 58;
Serial.print(distance);
Serial.println(" cm");
t = duration / 58;
//t=34+t;
if ( isnan(t) ) {
} else {
addPtToHist();
}
delay(100);
//delay(5);
}
void addPtToHist(){
//Serial.println(currentMillis - previousMillis);
long int tps = NTP.getTime();
//Serial.println(NTP.getTime());
if ( tps > 0 ) {
timestamp.add(tps);
hist_t.add(double_with_n_digits(t, 1));
//root.printTo(Serial);
if ( hist_t.size() > sizeHist ) {
//Serial.println("efface anciennes mesures");
timestamp.removeAt(0);
hist_t.removeAt(0);
;
}
//Serial.print("size hist_t ");Serial.println(hist_t.size());
// calcStat();
delay(100);
saveHistory();
//root.printTo(Serial);
}
}
the same code works on the lolin nodemcu v3
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <FS.h>
#include <TimeLib.h>
#include <NtpClientLib.h>
#include <ArduinoJson.h>
#define ssid "XXXXXXXX" // WiFi SSID
#define password "XXXXXXXXX" // WiFi password
#define trig 0
#define echo 2
#define HISTORY_FILE "/history.json"
float t = 0 ;
int sizeHist = 26800 ; // (7h x 12pts) - History size
const long intervalHist = 1000 * 60 * 60; // 5 measures / hours
ESP8266WebServer server ( 80 );
StaticJsonBuffer<10000> jsonBuffer; // Current JSON static buffer
JsonObject& root = jsonBuffer.createObject();
JsonArray& timestamp = root.createNestedArray("timestamp");
JsonArray& hist_t = root.createNestedArray("t");
char json[10000]; // JSON export buffer
void sendMesures() {
String json = "{\"t\":\"" + String(t) + "\"}";
server.send(200, "application/json", json);
Serial.println("Send measures");
}
void sendTabMesures() {
double temp = root["t"][0];
String json = "[";
json += "{\"mesure\":\"Température\",\"valeur\":\"" + String(t) + "\",\"unite\":\"°C\",\"glyph\":\"glyphicon-indent-left\",\"precedente\":\"" + String(temp) + "\"}";
json += "]";
server.send(200, "application/json", json);
Serial.println("Send data tab");
}
void sendHistory(){
root.printTo(json, sizeof(json));
server.send(200, "application/json", json);
Serial.println("Send History");
}
void loadHistory(){
File file = SPIFFS.open(HISTORY_FILE, "r");
if (!file){
Serial.println("Aucun historique existe - No History Exist");
} else {
size_t size = file.size();
if ( size == 0 ) {
Serial.println("Fichier historique vide - History file empty !");
} else {
std::unique_ptr<char[]> buf (new char[size]);
file.readBytes(buf.get(), size);
JsonObject& root = jsonBuffer.parseObject(buf.get());
if (!root.success()) {
Serial.println(" Impossible to read JSON file");
} else {
Serial.println(" History loaded");
root.prettyPrintTo(Serial);
}
}
file.close();
}
}
void saveHistory(){
Serial.println("Save History");
File historyFile = SPIFFS.open(HISTORY_FILE, "w");
root.printTo(historyFile); // Export and save JSON object to SPIFFS area
Serial.println("History save");
historyFile.close();
}
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
NTP.onNTPSyncEvent([](NTPSyncEvent_t error) {
if (error) {
Serial.print("Time Sync error: ");
if (error == noResponse)
Serial.println("NTP server not reachable");
else if (error == invalidAddress)
Serial.println("Invalid NTP server address");
}
else {
Serial.print("Got NTP time: ");
Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync()));
}
});
//
NTP.begin("pool.ntp.org", 0, true);
NTP.setInterval(60000);
delay(500);
Serial.begin ( 115200 );
WiFi.begin ( ssid, password );
int tentativeWiFi = 0;
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 ); Serial.print ( "." );
tentativeWiFi++;
if ( tentativeWiFi > 20 ) {
ESP.reset();
while(true)
delay(1);
}
}
// Connexion WiFi établie / WiFi connexion is OK
Serial.println ( "" );
Serial.print ( "Connected to " ); Serial.println ( ssid );
Serial.print ( "IP address: " ); Serial.println ( WiFi.localIP() );
if (!SPIFFS.begin()) {
Serial.println("SPIFFS Mount failed");
} else {
Serial.println("SPIFFS Mount succesfull");
loadHistory();
}
delay(50);
server.on("/tabmesures.json", sendTabMesures);
server.on("/mesures.json", sendMesures);
//server.on("/gpio", updateGpio);
server.on("/graph_temp.json", sendHistory);
server.serveStatic("/js", SPIFFS, "/js");
server.serveStatic("/css", SPIFFS, "/css");
server.serveStatic("/img", SPIFFS, "/img");
server.serveStatic("/", SPIFFS, "/index.html");
server.begin();
Serial.println ( "HTTP server started" );
Serial.print("Uptime :");
Serial.println(NTP.getUptime());
Serial.print("LastBootTime :");
Serial.println(NTP.getLastBootTime());
}
void loop() {
// put your main code here, to run repeatedly:
server.handleClient();
float duration, distance;
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = duration / 58;
Serial.print(distance);
Serial.println(" cm");
t = duration / 58;
//t=34+t;
if ( isnan(t) ) {
} else {
addPtToHist();
}
delay(100);
//delay(5);
}
void addPtToHist(){
//Serial.println(currentMillis - previousMillis);
long int tps = NTP.getTime();
//Serial.println(NTP.getTime());
if ( tps > 0 ) {
timestamp.add(tps);
hist_t.add(double_with_n_digits(t, 1));
//root.printTo(Serial);
if ( hist_t.size() > sizeHist ) {
//Serial.println("efface anciennes mesures");
timestamp.removeAt(0);
hist_t.removeAt(0);
;
}
//Serial.print("size hist_t ");Serial.println(hist_t.size());
// calcStat();
delay(100);
saveHistory();
//root.printTo(Serial);
}
}