communication entre nodemcu esp8266 et mega2560

Bonjour, depuis le 11 février j'expérimente l'univers Arduino. Je prend un peu d'avance dans mon cursus d'ingenieur en chimie et totalement débutant en la matière me retrouve bloqué depuis le debut car limité dans la compréhension des outils et code utilisés.

J'ai jusqu'a présent mon systeme est composé de:

  • 1 mega2560

  • 1 RTC1302

  • 1 HW125 MicroSD

  • 2 relais 10A (un 3em en prévision)

  • 1 EC meter

  • 1 DHT22 (temp+humy)

  • 1 Sonde db1820 WP

  • 1 module peltier

  • 2 pompe 12v 3w

  • 1 PC fan 120mm

  • 1 panneau led 30x30cm 12v

  • 1 LCD 16x2

  • (2 pompe péristaltique pas encore montée / codé)

  • 1 nodeMCU_WIFI_8266

  • 1 Alim 12v 12A

j'ai trouvé des bouts de code par ci par la et j'ai réussis sans trop comprendre la partie "transfert de données" et générer une page en local et afficher en fond blanc mes 4 valeurs reçu de la mega.
premier problème la page ne se rafraichis pas, deuxième je ne sais pas du tout comment utiliser le code derrière le transfert de donnée et la page web.

j'aimerai ajouté une interface HTML un refresh et controler les relais de la mega

Voici le code sur le nodeMCUESP8266

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>

ESP8266WebServer server;
char* ssid = "Braaap";
char* password = "gratteur";

void setup()
{
  WiFi.begin(ssid, password);
  Serial.begin(9600);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handleIndex);
  server.begin();
}

void loop()
{
  server.handleClient();

}

void handleIndex()
{
  // Send a JSON-formatted request with key "type" and value "request"
  // then parse the JSON-formatted response with keys "gas" and "distance"
  DynamicJsonDocument doc(1024);
  double tair = 0, teau = 0, humi = 0, tds = 0;
  // Sending the request
  doc["type"] = "request";
  serializeJson(doc, Serial);
  // Reading the response
  boolean messageReady = false;
  String message = "";
  while (messageReady == false) { // blocking but that's ok
    if (Serial.available()) {
      message = Serial.readString();
      messageReady = true;
    }
  }
  // Attempt to deserialize the JSON-formatted message
  DeserializationError error = deserializeJson(doc, message);
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }
  teau = doc["teau"];
  tair = doc["tair"];
  humi = doc ["hum"];
  tds = doc ["tds"];
  // Prepare the data for serving it over HTTP
  String output = "Temperature H20: " + String(teau) + "\n" 
  + "Temperature Air " + String(tair) + "\n"
  + "Humidity % " + String(humi)+ "\n"
  + "TDS PPM " + String(tds)+ "\n";
 
  // Serve the data as plain text, for example
  server.send(200, "text/plain", output);

Voila avec hate d'échanger avec vous et d'en apprendre d'avantage merci d'avoir pris le temps de lire et de vous penchez sur mon sujet

Voici le code de la mega2560

et voici le code MEGA2560

int getMedianNum(int bArray[], int iFilterLen)
{
  int bTab[iFilterLen];
  for (byte i = 0; i < iFilterLen; i++)
    bTab[i] = bArray[i];
  int i, j, bTemp;
  for (j = 0; j < iFilterLen - 1; j++)
  {
    for (i = 0; i < iFilterLen - j - 1; i++)
    {
      if (bTab[i] > bTab[i + 1])
      {
        bTemp = bTab[i];
        bTab[i] = bTab[i + 1];
        bTab[i + 1] = bTemp;
      }
    }
  }
  if ((iFilterLen & 1) > 0)
    bTemp = bTab[(iFilterLen - 1) / 2];
  else
    bTemp = (bTab[iFilterLen / 2] + bTab[iFilterLen / 2 - 1]) / 2;
  return bTemp;
}
unsigned long currentMillis = millis();
unsigned long previousMillis = 0; // will store last time sensor was updated
const long interval = 5000; // temps entre mesures
#include <SPI.h>
#include <SD.h>
const int chipSelect = 49;
#include  <virtuabotixRTC.h>  //Library used
#define DS1302_GND_PIN 33
#define DS1302_VCC_PIN 31
#include <ArduinoJson.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display
String message = "";
bool messageReady = false;
#define RELAY1 24

#define LAMPES 22
#include <DHT.h>;
#include <DallasTemperature.h>
//Constants
#define DHTPIN 8     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
#define ONE_WIRE_BUS 7
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

//Variables
int chk;
float humi;  //Stores humidity value
float temp; //Stores temperature value
#define TdsSensorPin A3
#define VREF 5.0 // analog reference voltage(Volt) of the ADC
#define SCOUNT 3 // sum of sample point
int analogBuffer[SCOUNT]; // store the analog value in the array, read from ADC
int analogBufferTemp[SCOUNT];
int analogBufferIndex = 0, copyIndex = 0;
float averageVoltage = 0, tdsValue = 0;

virtuabotixRTC myRTC(35, 37, 39); //If you change the wiring change the pins here also


const int OnHour = 00;
const int OnMin = 07;           //set hour and minutes for timer

const int OffHour = 22;
const int OffMin = 26;                                                   //The setup is done only one time and the module will continue counting it automatically

void setup() {
  Serial.begin(9600);
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }


  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");
  dht.begin();
  sensors.begin();
  pinMode(TdsSensorPin, INPUT);
  pinMode(RELAY1, OUTPUT);

  digitalWrite(DS1302_GND_PIN, LOW);
  pinMode(DS1302_GND_PIN, OUTPUT);
  digitalWrite(DS1302_VCC_PIN, HIGH);
  pinMode(DS1302_VCC_PIN, OUTPUT);
  pinMode(LAMPES, OUTPUT);
  lcd.init();

  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Alex's Project");
  lcd.setCursor(2, 1);
  lcd.print("Mars 2020");
  delay(3000);
  lcd.clear();
}

void loop() {
  sensors.requestTemperatures();
  float temperature = sensors.getTempCByIndex(0);

  if (temperature < 19)
  {

    digitalWrite(RELAY1, 0);

  }
  else if (temperature > 20)
  {
    digitalWrite(RELAY1, 1);
  }

  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  if (currentMillis - previousMillis >= interval) {

    // save the last time you blinked the LED
    previousMillis = currentMillis;
    dataFile.println(temperature);
    dataFile.close();

  }

  myRTC.updateTime();

  // Start printing elements as individuals
  Serial.print("Current Date / Time: ");
  Serial.print(myRTC.dayofmonth);             //You can switch between day and month if you're using American system && myRTC.minutes == OnMin
  Serial.print("/");
  Serial.print(myRTC.month);
  Serial.print("/");
  Serial.print(myRTC.year);
  Serial.print(" ");
  Serial.print(myRTC.hours);
  Serial.print(":");
  Serial.print(myRTC.minutes);
  Serial.print(":");
  Serial.println(myRTC.seconds);
  delay (3000);

  if (myRTC.hours == OnHour && myRTC.minutes == OnMin ) {   // add && myRTC.minutes == OnMin   ;    (myRTC.hours == OffHour && myRTC.minutes == OffMin){
    digitalWrite(LAMPES, HIGH);
    Serial.println("LIGHT ON");
    delay(250);
  }
  else if (myRTC.hours == OffHour && myRTC.minutes == OffMin ) {  // add && myRTC.minutes == OnMin   ;    (myRTC.hours == OffHour && myRTC.minutes == OffMin){
    digitalWrite(LAMPES, LOW);
    Serial.println("LIGHT Off");
  }

  float  humi = dht.readHumidity();
  float temp = dht.readTemperature();


  {
    static unsigned long analogSampleTimepoint = millis();
    if (millis() - analogSampleTimepoint > 40U) //every 40 milliseconds,read the analog value from the ADC
    {
      analogSampleTimepoint = millis();
      analogBuffer[analogBufferIndex] = analogRead(TdsSensorPin); //read the analog value and store into the buffer
      analogBufferIndex++;
      if (analogBufferIndex == SCOUNT)
        analogBufferIndex = 0;
    }
    static unsigned long printTimepoint = millis();
    if (millis() - printTimepoint > 800U)
    {
      printTimepoint = millis();
      for (copyIndex = 0; copyIndex < SCOUNT; copyIndex++)
        analogBufferTemp[copyIndex] = analogBuffer[copyIndex];
      averageVoltage = getMedianNum(analogBufferTemp, SCOUNT) * (float)VREF / 1024.0; // read the analog value more stable by the median filtering algorithm, and convert to voltage value
      float compensationCoefficient = 1.0 + 0.02 * (temperature - 25.0); //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.02*(fTP-25.0));
      float compensationVolatge = averageVoltage / compensationCoefficient; //temperature compensation
      tdsValue = (133.42 * compensationVolatge * compensationVolatge * compensationVolatge - 255.86 * compensationVolatge * compensationVolatge + 857.39 * compensationVolatge) * 0.5; //convert voltage value to tds value
      //Serial.print("voltage:");
      //Serial.print(averageVoltage,2);
      //Serial.print("V ");

    }
  }
  while (Serial.available()) {
    message = Serial.readString();
    messageReady = true;
  }
  // Only process message if there's one
  if (messageReady) {
    // The only messages we'll parse will be formatted in JSON
    DynamicJsonDocument doc(1024); // ArduinoJson version 6+
    // Attempt to deserialize the message
    DeserializationError error = deserializeJson(doc, message);
    if (error) {
      Serial.print(F("deserializeJson() failed: "));
      Serial.println(error.c_str());
      messageReady = false;
      return;
    }
    if (doc["type"] == "request") {
      doc["type"] = "response";
      // Get data from analog sensors
      doc["teau"] = sensors.getTempCByIndex(0);
      doc["tair"] = dht.readTemperature();
      doc["hum"] = dht.readHumidity();
      doc["tds"] = tdsValue ;
      serializeJson(doc, Serial);
    }
    messageReady = false;
  }
  Serial.print("Humidity: ");
  Serial.print(humi);
  Serial.println(" %");
  Serial.print("Temp air: ");
  Serial.print(temp);
  Serial.println(" Celsius");

  Serial.print("Temp H2O ;");
  Serial.print(temperature);
  Serial.println(" Celsius");
  Serial.print("TDS Value:");
  Serial.print(tdsValue, 0);
  Serial.println("ppm");
  delay(2000); //Delay 2 sec.
  lcd.setCursor(0, 0);
  lcd.print("Eau ");
  lcd.print(temperature, 1);
  lcd.setCursor(9, 0);
  lcd.print("Hum ");
  lcd.print(humi, 0);
  lcd.print("%");
  lcd.setCursor(0, 1);
  lcd.print("Air ");
  lcd.print(temp, 1);
  lcd.setCursor(9, 1);
  lcd.print("TDS ");
  lcd.print(tdsValue, 0);

}

And what is the question ?

Cordialement,
bidouilleelec

Bonsoir et bien il y a plusieurs points que je ne sais pas aborder

-Comment rafraichir automatiquement "la page web" pour voir les données évoluer en live?

-Comment ajouter une interface sur ma page web et proposer d'afficher les valeurs differement du "plain-text"m sous quel autre format, avec une mise en page et possibilité de généré un graphique?

-Comment piloter depuis l'interface web avec un bouton le mode des relais on/off (par conséquent le pin data des relais sur la mega ici le pin digital 22 et 24 sur ma board comment dire depuis la page web low state pin 22 ? ou high state)

Merci