Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By jgarridc
#72688 Hi.....(sorry about my english)

I am trying to do an wifi themostat with nodemcu, well, I have finished yet, but know I want to improve it....

I have a problem with the code, you use this like char char Channel_ID[11] = ""; //ThingSpeak Channel ID but thingspeak need this code was unsigned long, how did you fixe the convertion problem?

If I only want to put my apiKey on the mobile or tablet screen its not a problem, but with the code I use, if a want to put the channelnumber too, nodemcu gone crash...

Code: Select all#include <FS.h>
#include<ESP8266WiFi.h>
#include "ThingSpeak.h"
#include <DHT.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
#include <ESP8266mDNS.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
//#include <Adafruit_Sensor.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#define DHTTYPE DHT22
#include <DoubleResetDetector.h>
#include <LiquidCrystal_I2C.h>

#define DRD_TIMEOUT 100
#define DRD_ADDRESS 0

DoubleResetDetector drd(DRD_TIMEOUT, DRD_ADDRESS);

LiquidCrystal_I2C lcd(0x27, 16, 2);

//Thingspeak parametros
const char* serverThingspeak = "api.thingspeak.com";
char  myWriteAPIKey[20] = "myWriteAPIKey";
unsigned long myChannelNumber = 266577;

   
WiFiManagerParameter custom_myWriteAPIKey("API-Key", "myWriteAPIKey", myWriteAPIKey, 20);
//WiFiManagerParameter custom_myChannelNumber("Channel Number", "SmChannelNumber", myChannelNumber, 10);
 
                   
const int releCaldera = 16;
const int DHTpin = D4;
float histeresis = 1;
static unsigned long last_loop;
unsigned long int anteriorRefreshDatos = 0;
float temp= 0;
float humi= 0;
float tempDeseada = 00;
int calderaHabilitada;
int estadoRele = 0;
int contconexion = 0;
bool shouldSaveConfig = false;


DHT dht(DHTpin, DHTTYPE);

WiFiClient client;
WiFiServer server(80);

void Init_SPIFFS() {
  //clean FS, for testing
  //SPIFFS.format();

  //read configuration from FS json
  Serial.println("mounting FS...");

  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\nparsed json");

          strcpy(myWriteAPIKey, json["myWriteAPIKey"]);
          //strcpy(myChannelNumber, json["myChannelNumber"]);
         
        } else {
          Serial.println("failed to load json config");
        }
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  //end read

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
}

void InitWiFiManager() {
  WiFiManager wifiManager;
  WiFi.setAutoConnect(true);
  //wifiManager.setSaveConfigCallback(saveConfigCallback);
  //wifiManager.setAPCallback(configModeCallback);
  wifiManager.addParameter(&custom_myWriteAPIKey);
  //wifiManager.addParameter(&custom_myChannelNumber);
    wifiManager.setConfigPortalTimeout(320);
  wifiManager.setDebugOutput(true);
  //reset settings - for testing
  //wifiManager.resetSettings();
  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.autoConnect("BeetConfig")) {
    delay(3000);
    WiFi.softAPdisconnect(true); //AP Ausschalten
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }
  WiFi.softAPdisconnect(true); //AP Ausschalten
}

void Save_CP_Parameter() {
  strcpy(myWriteAPIKey, custom_myWriteAPIKey.getValue());
  //strcpy(myChannelNumber, custom_myChannelNumber.getValue());
    //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["myWriteAPIKey"] = myWriteAPIKey;
    json["myChannelNumber"] = myChannelNumber;
   
    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
    json.printTo(Serial);
    json.printTo(configFile);
    configFile.close();
    //end save
  }
}

             

void setup() {

lcd.clear();
lcd.begin(16,2);
lcd.init();
lcd.backlight();
dht.begin();
delay(10);

Serial.begin(115200);

  Init_SPIFFS();
  InitWiFiManager();
  Save_CP_Parameter();
 
pinMode(releCaldera, OUTPUT);
digitalWrite(releCaldera, LOW);
pinMode(LED_BUILTIN, OUTPUT);

Serial.println();

if (drd.detectDoubleReset()) {
  Serial.println("Doble reset detectado");
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("INTRODUCIR");
    lcd.setCursor(0,1);
    lcd.print("USUARIO Y PASS");
   
    digitalWrite(LED_BUILTIN, LOW);
   
               
    delay(1000);
   
          } else {
            Serial.println("No se ha detectado doble reset");
            digitalWrite(LED_BUILTIN, LOW);
          }
                       
                    pinMode(releCaldera, OUTPUT);
                    digitalWrite(releCaldera, LOW);

           



IPAddress _ip = IPAddress(192, 168, 1, 10);
IPAddress _gw = IPAddress(192, 168, 1, 1);
IPAddress _sn = IPAddress(255, 255, 255, 0);



          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("CONECTANDO...");
          delay(2000);
          Serial.println("Conectado a la red WIFI :)");
          Serial.println("local ip");
          Serial.println(WiFi.localIP());

          // Start the server
  ThingSpeak.begin(client);
  Serial.println("Cliente thingspeak iniciado");
  server.begin();
  Serial.println("Server iniciado");
  delay(10000);
}


 
void refreshDatos(){

if (millis() > anteriorRefreshDatos + 20000){
anteriorRefreshDatos = millis();
float temp = dht.readTemperature();
float humi = dht.readHumidity();
if (isnan(temp) || isnan(humi)){
    Serial.println("Fallo en lectura de temperatura y humedad");
    return;}
    if (calderaHabilitada = 1){
    if (temp + histeresis >= tempDeseada && temp > 0)  digitalWrite(releCaldera, LOW);
    else if (temp < tempDeseada && temp > 0) digitalWrite(releCaldera, HIGH);
    else digitalWrite(releCaldera, LOW);
         }             
      Serial.println();
      Serial.println("Leyendo datos....");
      Serial.print("Temperatura deseada: ");
      Serial.println(tempDeseada);
      Serial.print("Temperatura: ");
      Serial.println(temp);
      Serial.print("Humedad: ");
      Serial.println(humi);
            lcd.setCursor(0,0);
            lcd.print("Temp: ");
            lcd.print(temp);
            lcd.print(" ");
            lcd.print((char)223);
            lcd.print("C");
            lcd.setCursor(0,1);
            lcd.print("Hum:  ");
            lcd.print(humi);
            lcd.print(" %");
      int estadoRele = digitalRead(releCaldera);
      if (estadoRele == LOW)
        {
        Serial.print("Estado relé caldera: "); 
        Serial.println("LOW");
            lcd.setCursor(15,0);
            lcd.print(" ");       
            } else {
        Serial.print("Estado relé caldera: "); 
        Serial.println("HIGH");
            lcd.setCursor(15,0);
            lcd.print("C");
            }
 // Start the server
  ThingSpeak.begin(client);
  Serial.println("Cliente thingspeak iniciado");
  server.begin();
  Serial.println("Server iniciado");
 
  delay(10000);

              ThingSpeak.setField(1, temp);
              ThingSpeak.setField(2, humi);
              ThingSpeak.setField(3, estadoRele);
              ThingSpeak.setField(4, tempDeseada);

              ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
              //ThingSpeak.writeFields(String(myChannelNumber).toInt(), myWriteAPIKey);   
              delay(15000);

              Serial.println(myChannelNumber);
              Serial.println(myWriteAPIKey);
             
              Serial.println("Enviando datos...");
              Serial.println();
                 }
               }

void loop() {

  refreshDatos();
 
 
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;   
  }
 
  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
 
 int  val;

      if (req.indexOf("/tempDeseada21") != -1){
      tempDeseada = 21;
      val = 1;
      } else if (req.indexOf("/tempDeseada22") != -1){
      tempDeseada = 22;
      val = 1;
      } else if (req.indexOf("/tempDeseada23") != -1){
      tempDeseada = 23;
      val = 1;
      } else if (req.indexOf("/tempDeseada24") != -1){
      tempDeseada = 24;
      val = 1;
      } else if (req.indexOf("/tempDeseada25") != -1){
      tempDeseada = 25;
      val = 1;
      } else if (req.indexOf("/tempDeseada26") != -1){
      tempDeseada = 26;
      val = 1;
      } else if (req.indexOf("/tempDeseada00") != -1){
      tempDeseada = 00;
      val = 0;
      } else {
      Serial.println("peticion invalida");
      client.stop();
      return;     
      }

  // Set GPIO2 according to the request
  calderaHabilitada = val;
  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
  s += (val)?"high":"low";
  s += "</html>\n";

  // Send the response to the client
  client.print(s);
  delay(1);
  client.stop();
  Serial.println("Client disonnected");
  }
User avatar
By freedom2000
#72725 Full code is in post #1.

Yu don't need channelId to update ThingSpeak, APIkey for this channel is enough.
Please stay into the topic and open a new thread for your question.

JP