[Solved]Need help with ESP8266 to display Analog Read Data A0 on my web page

Hi everyone,

I am not a programmer just know some arduino and html code :slight_smile:

I am using ESP8266 Nodemcu, I upload in the SPIFFS my html files, png and css.
after multiples search on google I coming to your help.

I use the <ESP8266WebServer.h> librarie and search the correct way to display the analog data reading from A0 on my web page.
I found some Xlm code but it's note working.

I asking for your help to use the correct code.

I post just the appropriate code for the moment.

The JS I found

<script>
   function obtenirVariables()
   {
      var uniqueURL = "reqEtatVariables" + "&aleatoire=" + Math.trunc(Math.random() * 1000000);
      var request = new XMLHttpRequest(); // http://www.toutjavascript.com/reference/ref-xmlhttprequest.php
      // la fonction à appeler lors d'un changement d'avancement de la requête AJAX
      request.onreadystatechange = function()
      {
         if (this.readyState == 4) {
            // Indicateur de l'avancement de l'appel AJAX == 4 => Données complètement accessibles 
            if (this.status == 200) {
               // Code retour du serveur après l'appel AJAX == 200 => OK, tout s'est bien passé
               if (this.responseXML != null) {
                  // si on a bien obtenu une réponse non nulle
                  // alors on va extraire du XML les éléments qui nous intéressent
                  /*document.getElementById("boutonID").innerHTML =
                  this.responseXML.getElementsByTagName('bouton')[0].childNodes[0].nodeValue;
                  
				  document.getElementById("digital1ID").innerHTML =
                  this.responseXML.getElementsByTagName('digital1')[0].childNodes[0].nodeValue;*/
                  
				  document.getElementById("analog1ID").innerHTML =
                  this.responseXML.getElementsByTagName('sendsensor1')[0].childNodes[0].nodeValue;
				  document.getElementById("analog2ID").innerHTML =
                  this.responseXML.getElementsByTagName('sendsensor2')[0].childNodes[0].nodeValue;
				  document.getElementById("analog3ID").innerHTML =
                  this.responseXML.getElementsByTagName('sendsensor3')[0].childNodes[0].nodeValue;
				  document.getElementById("analog4ID").innerHTML =
                  this.responseXML.getElementsByTagName('sendsensor4')[0].childNodes[0].nodeValue;
               }
            }
         }
      }
      request.open("GET", uniqueURL , true); // ici on envoie la requête GET sur l'URL /reqEtatVariables
      request.send(null);
      setTimeout("obtenirVariables()", 1000); // on rappelle obtenirVariables() dans 1s
   }
   </script>

the HTML code I try

<p>la pin D4 vaut <span id="digital1ID">...</span></p> -->
   <p>Plant Soil Humidity Sensor1 <span id="analog1ID">...</span></p>
   <p>Plant Soil Humidity Sensor2 <span id="analog2ID">...</span></p>
   <p>Plant Soil Humidity Sensor3 <span id="analog3ID">...</span></p>
   <p>Plant Soil Humidity Sensor4 <span id="analog4ID">...</span></p>

The esp code I have,

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <FS.h>
const char* ssid = "****";
const char* password = "****";
const String DISPLAY_DATA_HTML = "/html/display_data.html";

ESP8266WebServer server(80);

#define Sensor1 A0

the function to display my html page

void DisplayData()
{
 String form = "";
 File f = SPIFFS.open(DISPLAY_DATA_HTML, "r");
 if (!f){
  Serial.println("Can't open update html file"); 
  server.send(404, "text/html", "File not found");    
  }
  else{
   char buf[1024];
   int siz = f.size();
   while(siz > 0) {
    size_t len = std::min((int)(sizeof(buf) - 1), siz);
    f.read((uint8_t *)buf, len);
    buf[len] = 0;
    form += buf;
    siz -= sizeof(buf) - 1;
   }
   f.close();
   server.send(200, "text/html", form);
  }
}

my setup code

void setup(void){
 Serial.begin(115200);

 if (!SPIFFS.begin()) {
  Serial.println("Failed to mount file system");
  return;
  }

 WiFi.begin(ssid, password);
 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("/display_data",DisplayData);

 server.on("/reqEtatVariables", [&](){
 server.send(200, "text/XML", String((int)Web_Soil_Sensor1)); // send to someones browser when asked
  });

server.serveStatic("/css", SPIFFS, "/html/css");
server.serveStatic("/display_data.html", SPIFFS, "/html/display_data.html");

server.begin();
  Serial.println("HTTP server started");

  if (!MDNS.begin(host)) {
    Serial.println("Error setting up MDNS responder!");
    while(1){ 
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");

  // Add service to MDNS-SD
  MDNS.addService("http", "tcp", 80);
}

finaly the loop code

void loop(void){
 server.handleClient();
}

How can help me to adjust my code ?

    size_t len = std::min((int)(sizeof(buf) - 1), siz);
    f.read((uint8_t *)buf, len);

You can ask read() to read sizeof(buf) - 1 bytes. It will return the number of bytes that it read.

   size_t len = f.read((uint8_t *)buf, sizeof(buf)-1);

How can help me to adjust my code ?

Based on those snippets? Not a chance. Post ALL of your code.

Where do you actually read the analog pin(s)? I'd expect you to do that in the anonymous lambda expression that is invoked when the URL contains "/reqEtatVariables".

What type is Web_Soil_Sensor1? Why is it necessary to cast it to an int? Why is it necessary to wrap it in a String? Where does it get a value?

Thanks for your quick reply,

PaulS:
Where do you actually read the analog pin(s)? I'd expect you to do that in the anonymous lambda expression that is invoked when the URL contains "/reqEtatVariables".

I don't post the reading code from A0, I just montionned it, I have some Soil Humidity.
I will post here my complete code.

PaulS:
What type is Web_Soil_Sensor1? Why is it necessary to cast it to an int? Why is it necessary to wrap it in a String? Where does it get a value?

The Web_Soil_Sensor1 is an int value, I convert it to string for sending the value to my web page.

PaulS:
Post ALL of your code.

Here is my code, I thinks not all is necessary.
The config.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta property="og:site_name" content="Irrigation System" />
  <meta property="og:title" content="Irrigation System Home Plants" />
  <meta property="og:type" content="website" />
  <meta name="description" content="Irrigation System Home Plants">  
  <title>Irrigation System for Plants</title>
  <link href="css/style.css" rel="stylesheet">
</head>
<body>
<header>
  <div id="header">
  <div id="header-top">
   <h2>Welcome to your Irrigation System for Plants</h2>
  </div> <!-- close div header-top -->
  <div id="header-bottom">
   <nav id="menu">
    <ul>
    <li class="selected"><a href="/config">Home</a></li>
    <li><a href="/display_data">Display Data Sensor</a></li>
    <li><a href="">jQuery</a></li>
    <li><a href="">PHP</a></li>
    <li><a href="">System</a></li>
    <li><a href="">Design</a></li>
    <li><a href="/update">System</a></li>
    <div class="current">
     <div class="ctoparr"></div>   
     <div class="cback"></div>
     <div class="cbotarr"></div>
    </div>
    </ul>
   </nav>
  </div> <!-- close div header-bottom -->
  </div> <!-- close div header -->
</header>
<!--
 <div class="container">
  <form action="/save" method="POST">
   <fieldset>
   <input type="text" name="fname" required><input type="submit" value="submit">
   </fieldset>
  </form> -->
 <div class="form-style-10">
<h1>Setup Your Irrigation Sensor<!-- <span>Sign up and tell us what you think of the site!</span> --></h1>
<form action="/postindex" method="POST">
    <div class="section"><span>1</span>Select sensor 1 sensitivity for Your Plant</div>
    <div class="inner-wrap">
        <div class="select">
      <select name="sensor1" id="slct" required>
        <option disabled selected value>Plant Sensor 1</option>
 <option value="0">NONE</option>
        <option value="1">Mint</option>
 <option value="2">Parsley</option>
 <option value="3">Basil</option>
        <option value="4">Coriander</option>
        <option value="5">Dill</option>
 <option value="6">Sage</option>
 <option value="7">rosemary</option> 
      </select>
    </div>
    </div>

    <div class="section"><span>2</span>Select sensor 2 sensitivity for Your Plant</div>
    <div class="inner-wrap">
        <div class="select">
      <select name="sensor2" id="slct" required>
        <option disabled selected value>Plant Sensor 2</option>
 <option value="0">NONE</option>
        <option value="1">Mint</option>
 <option value="2">Parsley</option>
 <option value="3">Basil</option>
        <option value="4">Coriander</option>
        <option value="5">Dill</option>
 <option value="6">Sage</option>
 <option value="7">rosemary</option> 
      </select>
    </div>
    </div>

    <div class="section"><span>3</span>Select sensor 3 sensitivity for Your Plant</div>
        <div class="inner-wrap">
 <div class="select">
      <select name="sensor3" id="slct" required>
        <option disabled selected value>Plant Sensor 3</option>
 <option value="0">NONE</option>
        <option value="1">Mint</option>
 <option value="2">Parsley</option>
 <option value="3">Basil</option>
        <option value="4">Coriander</option>
        <option value="5">Dill</option>
 <option value="6">Sage</option>
 <option value="7">rosemary</option> 
      </select>
    </div>
    </div>
 
 <div class="section"><span>4</span>Select sensor 4 sensitivity for Your Plant</div>
 <div class="inner-wrap">
 <div class="select">
    <select name="sensor4" id="slct" required>
      <option disabled selected value>Plant Sensor 5</option>
 <option value="0">NONE</option>
        <option value="1">Mint</option>
 <option value="2">Parsley</option>
 <option value="3">Basil</option>
        <option value="4">Coriander</option>
        <option value="5">Dill</option>
 <option value="6">Sage</option>
 <option value="7">rosemary</option> 
    </select>
  </div>
  </div>
  
    <div class="button-section">
     <input type="submit" name="Sign Up" />
     <!-- <span class="privacy-policy">
     <input type="checkbox" name="field7">You agree to our Terms and Policy.
     </span> -->
    </div>
</form>
</div>
 </div> <!-- close div container -->
</body>
</html>

The display_data.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta property="og:site_name" content="Script Tutorials" />
  <meta property="og:title" content="Sliding single-level menu | Script Tutorials" />
  <meta property="og:type" content="website" />
  <meta name="description" content="Sliding single-level menu - Script Tutorials">
  
    <script>
   function obtenirVariables()
   {
      var uniqueURL = "reqEtatVariables" + "&aleatoire=" + Math.trunc(Math.random() * 1000000);
      var request = new XMLHttpRequest(); // http://www.toutjavascript.com/reference/ref-xmlhttprequest.php
      // la fonction à appeler lors d'un changement d'avancement de la requête AJAX
      request.onreadystatechange = function()
      {
         if (this.readyState == 4) {
            // Indicateur de l'avancement de l'appel AJAX == 4 => Données complètement accessibles 
            if (this.status == 200) {
               // Code retour du serveur après l'appel AJAX == 200 => OK, tout s'est bien passé
               if (this.responseXML != null) {
                  // si on a bien obtenu une réponse non nulle
                  // alors on va extraire du XML les éléments qui nous intéressent
                  /*document.getElementById("boutonID").innerHTML =
                  this.responseXML.getElementsByTagName('bouton')[0].childNodes[0].nodeValue;
                  
  document.getElementById("digital1ID").innerHTML =
                  this.responseXML.getElementsByTagName('digital1')[0].childNodes[0].nodeValue;*/
                  
  document.getElementById("analog1ID").innerHTML =
                  this.responseXML.getElementsByTagName('sendsensor1')[0].childNodes[0].nodeValue;
  document.getElementById("analog2ID").innerHTML =
                  this.responseXML.getElementsByTagName('sendsensor2')[0].childNodes[0].nodeValue;
  document.getElementById("analog3ID").innerHTML =
                  this.responseXML.getElementsByTagName('sendsensor3')[0].childNodes[0].nodeValue;
  document.getElementById("analog4ID").innerHTML =
                  this.responseXML.getElementsByTagName('sendsensor4')[0].childNodes[0].nodeValue;
               }
            }
         }
      }
      request.open("GET", uniqueURL , true); // ici on envoie la requête GET sur l'URL /reqEtatVariables
      request.send(null);
      setTimeout("obtenirVariables()", 1000); // on rappelle obtenirVariables() dans 1s
   }
   </script>
  
  <title>Irrigation System for Plants</title>
  <link href="css/style.css" rel="stylesheet">
</head>
<body onload="obtenirVariables()">
<header>
  <div id="header">
  <div id="header-top">
   <h2>Welcome to your Irrigation System for Plants</h2>
  </div> <!-- close div header-top -->
  <div id="header-bottom">
   <nav id="menu">
    <ul>
    <li><a href="/config">Home</a></li>
    <li class="selected"><a href="/display_data">Display Data Sensor</a></li>
    <li><a href="">jQuery</a></li>
    <li><a href="">PHP</a></li>
    <li><a href="">System</a></li>
    <li><a href="">Design</a></li>
    <li><a href="/update">System</a></li>
    <div class="current">
     <div class="ctoparr"></div>   
     <div class="cback"></div>
     <div class="cbotarr"></div>
    </div>
    </ul>
   </nav>
  </div> <!-- close div header-bottom -->
  </div> <!-- close div header -->
</header>

 <div class="container">
 <div class="form-style-10">
<h1>Display Soil Sensors Datas<!-- <span>Sign up and tell us what you think of the site!</span> --></h1>

    <div class="section"><span>F</span>Display Soil Sensors Datas of your Plants</div>
    <div class="inner-wrap">
   <!-- <p>le bouton est <span id="boutonID">...</span> maintenant</p>
   <p>la pin D4 vaut <span id="digital1ID">...</span></p> -->
   <p>Plant Soil Humidity Sensor1 <span id="analog1ID">...</span></p>
   <p>Plant Soil Humidity Sensor2 <span id="analog2ID">...</span></p>
   <p>Plant Soil Humidity Sensor3 <span id="analog3ID">...</span></p>
   <p>Plant Soil Humidity Sensor4 <span id="analog4ID">...</span></p>
    </div>
 </div>
 </div> <!-- close div container -->
</body>
</html>

ESP8266 code

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <FS.h>

const char *host = "serverweb1";
const char* ssid = "****";
const char* password = "****";
const String CONFIG_HTML = "/html/config.html";
const String UPDATE_HTML = "/html/Update.html";
const String DISPLAY_DATA_HTML = "/html/display_data.html";
const char *configUsername = "admin";
const char *configPwd = "admin";
ESP8266WebServer server(80);

#define SoilSensor1 A0
#define SoilSensorEnablePin1 6
#define SoilSensorEnablePin2 5
#define SoilSensorEnablePin3 4
#define SoilSensorEnablePin4 3
#define PumpPin 2

//Configure the soil moisture
const int MintSoilMoisture = 250;//Menth
const int ParsleySoilMoisture = 250;//Persil
const int BasilSoilMoisture = 250;//Basilic
const int CorianderSoilMoisture = 250;//Coriande, Cousbara
const int DillSoilMoisture = 250;//Aneth, shamir
const int SageSoilMoisture = 250;//Sauge, Marva
const int rosemarySoilMoisture = 250;//Romarin

String PlantSensor1,PlantSensor2,PlantSensor3,PlantSensor4; //Read from the Web Form
int NewPlantSensor1,NewPlantSensor2,NewPlantSensor3,NewPlantSensor4; //Convert string receive from web to int
int Web_Soil_Sensor1,Web_Soil_Sensor2,Web_Soil_Sensor3,Web_Soil_Sensor4; //Convert to the correct target Soil Sensor
int electric_tap_motor1=7,electric_tap_motor2=8,electric_tap_motor3=9,electric_tap_motor4=10; //pin to drive the motor's electric tap

/**
* racine du site.
*/
void handleRoot() {
  server.send(200, "text/plain", "Welcome to my Irrigation System!");
}

/**
* display configuration page.
*/
void handleConfig()
{
 String form = "";
 File f = SPIFFS.open(CONFIG_HTML, "r");
 if (!f){
  Serial.println("Can't open config html file"); 
  server.send(404, "text/html", "File not found");    
  }
  else{
   char buf[1024];
   int siz = f.size();
   while(siz > 0) {
    size_t len = std::min((int)(sizeof(buf) - 1), siz);
    f.read((uint8_t *)buf, len);
    buf[len] = 0;
    form += buf;
    siz -= sizeof(buf) - 1;
   }
   f.close();
   server.send(200, "text/html", form);
  }
}

/**
* Display Update.html
*/
void handleUpdate()
{
 String form = "";
 File f = SPIFFS.open(UPDATE_HTML, "r");
 if (!f){
  Serial.println("Can't open update html file"); 
  server.send(404, "text/html", "File not found");    
  }
  else{
   char buf[1024];
   int siz = f.size();
   while(siz > 0) {
    size_t len = std::min((int)(sizeof(buf) - 1), siz);
    f.read((uint8_t *)buf, len);
    buf[len] = 0;
    form += buf;
    siz -= sizeof(buf) - 1;
   }
   f.close();
   server.send(200, "text/html", form);
  }
}

void handleReadUserPlantSelected(){
 PlantSensor1 = server.arg("sensor1");
 PlantSensor2 = server.arg("sensor2");
 PlantSensor3 = server.arg("sensor3");
 PlantSensor4 = server.arg("sensor4");

 // converting the reading String from WebForm to Int
 NewPlantSensor1 = StringToInt(PlantSensor1);
 NewPlantSensor2 = StringToInt(PlantSensor2);
 NewPlantSensor3 = StringToInt(PlantSensor3);
 NewPlantSensor4 = StringToInt(PlantSensor4);
 
 // Assign the correct Soil Target
 Web_Soil_Sensor1 =  SoilSensorWebUser(NewPlantSensor1);
 Web_Soil_Sensor2 =  SoilSensorWebUser(NewPlantSensor2);
 Web_Soil_Sensor3 =  SoilSensorWebUser(NewPlantSensor3);
 Web_Soil_Sensor4 =  SoilSensorWebUser(NewPlantSensor4);
 
  server.sendHeader("Location","/config");
  server.send(303);
}

int StringToInt(String PlantSensorResult)
{
 if(PlantSensorResult == ""){
  uint8_t SensorConverted  = atoi (PlantSensorResult.c_str ());
  // Serial.println(SensorConverted);
  Serial.println("No text");
  server.sendHeader("Location","/update");
  // server.send(200, "text/html","<p>No text selected</p>");
  return(SensorConverted);
 }
 else{
  uint8_t SensorConverted  = atoi (PlantSensorResult.c_str ());
  // Serial.println(SensorConverted);
  return(SensorConverted);
 }
}

int SoilSensorWebUser(int WebSoilSensor)
{
 switch(WebSoilSensor)
 {
  case 0:
    return(0);
  break;
  case 1:
    return(MintSoilMoisture);
  break;
  case 2:
    return(ParsleySoilMoisture);
  break;
  case 3:
    return(BasilSoilMoisture);
  break;
  case 4:
    return(CorianderSoilMoisture);
  break;
  case 5:
    return(DillSoilMoisture);
  break;
  case 6:
    return(SageSoilMoisture);
  break;
  case 7:
    return(rosemarySoilMoisture);
  break;
 }
}

/**
* Display display_data.hmtl
*/
void DisplayData()
{
 String form = "";
 File f = SPIFFS.open(DISPLAY_DATA_HTML, "r");
 if (!f){
  Serial.println("Can't open update html file"); 
  server.send(404, "text/html", "File not found");    
  }
  else{
   char buf[1024];
   int siz = f.size();
   while(siz > 0) {
    size_t len = std::min((int)(sizeof(buf) - 1), siz);
    f.read((uint8_t *)buf, len);
    buf[len] = 0;
    form += buf;
    siz -= sizeof(buf) - 1;
   }
   f.close();
   server.send(200, "text/html", form);
  }
}

void initWebserver()
{
 server.on("/", handleRoot);

 /* --- configure the config page, main page --- */
 server.on("/config", [&](){
 if(!server.authenticate(configUsername, configPwd)){
  return server.requestAuthentication();
 }else{
  handleConfig(); // display the page
 }
});

/* --- configure the update page --- */
  server.on("/update", [&](){
    if(!server.authenticate(configUsername, configPwd)){
      return server.requestAuthentication();
  } else {
    handleUpdate(); // display the page
  }
  });

  /* --- After press submit button for sensor --- */
 server.on("/postindex", [&](){
  handleReadUserPlantSelected(); // receive form's data from the form tag where action=postindex
 });

 server.on("/display_data", [&](){
    if(!server.authenticate(configUsername, configPwd)){
      return server.requestAuthentication();
  } else {
    DisplayData(); // display the page
  }
  });

  server.on("/reqEtatVariables", [&](){  // if you add this subdirectory to your webserver call, you get text below :)
    server.send(200, "text/plain", String((int)Web_Soil_Sensor1)); // send to someones browser when asked
  });
 server.serveStatic("/css", SPIFFS, "/html/css");
 server.serveStatic("/Update.html", SPIFFS, "/html/Update.html");
 server.serveStatic("/display_data.html", SPIFFS, "/html/display_data.html");
 server.serveStatic("/images/1.png", SPIFFS, "/html/images/1.png");
 server.serveStatic("/images/2.png", SPIFFS, "/html/images/2.png");
 server.serveStatic("/images/3.png", SPIFFS, "/html/images/3.png");
 server.serveStatic("/images/4.png", SPIFFS, "/html/images/4.png");
 server.serveStatic("/images/5.png", SPIFFS, "/html/images/5.png");
 server.serveStatic("/images/bg.png", SPIFFS, "/html/images/bg.png");
}

void WaterController(int sensor_pin, int UserWebSoilSensor, int electric_tap_motor)
{
 int output_value;
 for(int SensorReading = 0;SensorReading < 5;SensorReading++)
 {
  output_value = analogRead(sensor_pin);
 }
 output_value = map(output_value,550,10,0,100);
 
 if (output_value < UserWebSoilSensor)
 {
  digitalWrite(electric_tap_motor,HIGH);//turn on the tap
 }
 else {digitalWrite(electric_tap_motor,LOW);}
}

void PumpController()
{
 if(digitalRead(electric_tap_motor1 == HIGH) || digitalRead(electric_tap_motor2 == HIGH) || digitalRead(electric_tap_motor3 == HIGH) || digitalRead(electric_tap_motor4 == HIGH))
 {
  digitalWrite(PumpPin,HIGH);
 }
 else{digitalWrite(PumpPin,LOW);}
}

void setup(void){
 Serial.begin(115200);
 pinMode(PumpPin, INPUT);
 
 Serial.println("..."); 
 Serial.println("Mounting FS...");
 if (!SPIFFS.begin()) {
  Serial.println("Failed to mount file system");
  return;
  } 
 WiFi.begin(ssid, password);
 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");
  }
 initWebserver();
  
  server.begin();
  Serial.println("HTTP server started");
  if (!MDNS.begin(host)) {
    Serial.println("Error setting up MDNS responder!");
    while(1){ 
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  MDNS.addService("http", "tcp", 80);
}

void loop(void){
 server.handleClient();
 WaterController(SoilSensorEnablePin1, Web_Soil_Sensor1, electric_tap_motor1);
 WaterController(SoilSensorEnablePin2, Web_Soil_Sensor2, electric_tap_motor2);
 WaterController(SoilSensorEnablePin3, Web_Soil_Sensor3, electric_tap_motor3);
 WaterController(SoilSensorEnablePin4, Web_Soil_Sensor4, electric_tap_motor4);
}
  uint8_t SensorConverted  = atoi (PlantSensorResult.c_str ());

atoi() returns an int, not an unsigned int. atoi() does NOT expect the string it is passed to contain anything other than digits, at least none before the digits.

The String class HAS a toInt() method.

I'm still looking for the place in your code where you read some analog pins to get the data you want to display on your web page.

I'm still trying to determine where on the page the data is to be displayed.

PaulS:
I'm still looking for the place in your code where you read some analog pins to get the data you want to display on your web page.

void WaterController(int sensor_pin, int UserWebSoilSensor, int electric_tap_motor)
{
 digitalWrite(sensor_pin,HIGH); // I forget to add this to activate the appropriate sensor 
 int output_value;
 for(int SensorReading = 0;SensorReading < 5;SensorReading++)
 {
  output_value = analogRead(sensor_pin); /***** ANALOG READ *****/
 }
 output_value = map(output_value,550,10,0,100);
 
 if (output_value < UserWebSoilSensor)
 {
  digitalWrite(electric_tap_motor,HIGH);//turn on the tap
 }
 else
 {
  digitalWrite(electric_tap_motor,LOW);//turn off the tap
 }
 digitalWrite(sensor_pin,HIGH);// I forget to add this to deactivate the appropriate sensor
}

I have multiple sensor and only one analog Pin, I activate it before reading and deactivate it after reading.

PaulS:
I'm still trying to determine where on the page the data is to be displayed.

in the html file I have those line, and the
I don't know if it's correct.

<p>Plant Soil Humidity Sensor1 <span id="analog1ID">...</span></p>
<p>Plant Soil Humidity Sensor2 <span id="analog2ID">...</span></p>
<p>Plant Soil Humidity Sensor3 <span id="analog3ID">...</span></p>
<p>Plant Soil Humidity Sensor4 <span id="analog4ID">...</span></p>

in the arduino code I have this code to send the data, maybe it's not the correct way.

server.on("/reqEtatVariables", [&](){
server.send(200, "text/plain", String((int)Web_Soil_Sensor1));
  });

PaulS:

  uint8_t SensorConverted  = atoi (PlantSensorResult.c_str ());

atoi() returns an int, not an unsigned int. atoi() does NOT expect the string it is passed to contain anything other than digits, at least none before the digits.

The String class HAS a toInt() method.

Can you explain me, I found this way on the net, it's a mistake ?

I have multiple sensor and only one analog Pin, I activate it before reading and deactivate it after reading.

You activate what? You deactivate what? How can you have multiple sensors connected to one analog pin?

in the html file I have those line, and the <script>
I don't know if it's correct.

Is there something in place of the ... in what you really have?

in the arduino code I have this code to send the data, maybe it's not the correct way.

Since Web_Soil_Sensor1 is an int, then casting it to an int is useless.

Can you explain me, I found this way on the net, it's a mistake ?

Look at that statement. Suppose the String contains "-14". What value will be in SensorConverted?

Suppose that the String contains "Tom". What value will be in SensorConverted?

Now, it is possible that the String can never contain anything but the representation of a non-negative integer value. Still it is curious that you store the result from atoi() in an unsigned 8 byte integer, and then return that from a function that promises to return a signed 16 bit value.

Hi Paul Thanks for your reply and good remarks :slight_smile:
I need to review my code, I agree with you.

for the moment, I just searching how can I display an integer value from my ESP8266 to my web page.

If I have for example

int MyValue1 = some value that changing all the time;
int MyValue2 = some value that changing all the time;
int MyValue3 = some value that changing all the time;
int MyValue4 = some value that changing all the time;

I just searching the correct code in the ESP8266 arduino IDE and in my HTML page :slight_smile:

Can you help me with that ?

I just searching the correct code in the ESP8266 arduino IDE and in my HTML page

The way that you are dealing with the HTML file now means that you can NOT do what you want. You have a static page defined. Static pages do NOT have dynamic content, which is what you want.

You COULD have two files - Top.html and Bottom.html. You COULD read and send Top.html to send the static stuff that goes before the dynamic content. You COULD send the dynamic content. You COULD then read and send Bottom.html to send the static content that goes after the dynamic content.

As an example, you could have Top.html, containing:

The page title goes here

Moisture readings

and you could have Bottom.html containing:

Bedroom Kitchen Smokehouse Living room Closet

This table contains completely bogus data

You could have some code that collected 5 moisture readings in an array called moist, and some code:

   GetMoistureLevels();
   for(byte i=0; i<5; i++)
   {
      client.print("<td>");
      client.print(moist[i]);
      client.println("</td>");
   }

This snippet would go after the code to read and send Top.html, and before the code to read and send Bottom.html.

HI,

The client.print is not working with my library.
I solved my problem 8)
in my ESP I add some XML code

String XML;
void handleXML()
{
  XML="<?xml version='1.0'?>";
  XML+="<xml>";
  XML+="<val1>";
  XML+= MyValue1;
  XML+="</val1>";  
  XML+="<val2>";
  XML+= MyValue2;
  XML+="</val2>";
  XML+="<val3>";
  XML+= MyValue3;
  XML+="</val3>";
  XML+="<val4>";
  XML+= MyValue4;
  XML+="</val4>";
  XML+="</xml>";
 server.send(200,"text/xml",XML);
}

in the setup code

server.on("/reqEtatVariables",handleXML);

in my HTML code

<script>
 function obtenirVariables()
 {
  var uniqueURL = "/reqEtatVariables" + "?aleatoire=" + Math.trunc(Math.random() * 1000000);
  var request = new XMLHttpRequest();
  // la fonction à appeler lors d'un changement d'avancement de la requête AJAX
  request.onreadystatechange = function()
  {
   if (request.readyState == 4) {
    // Indicateur de l'avancement de l'appel AJAX == 4 => Données complètement accessibles 
    if (request.status == 200) {
     document.getElementById("value1").innerHTML = this.responseXML.getElementsByTagName('val1')[0].childNodes[0].nodeValue;
	 document.getElementById("value2").innerHTML = this.responseXML.getElementsByTagName('val2')[0].childNodes[0].nodeValue;
	 document.getElementById("value3").innerHTML = this.responseXML.getElementsByTagName('val3')[0].childNodes[0].nodeValue;
	 document.getElementById("value4").innerHTML = this.responseXML.getElementsByTagName('val3')[0].childNodes[0].nodeValue;
    }
  }
 }
 request.open("GET", uniqueURL , true); // ici on envoie la requête GET sur l'URL /reqEtatVariables
 request.send(null);
 setTimeout("obtenirVariables()", 1000); // on rappelle obtenirVariables() dans 1s
}
</script>

<p id="value1"></p>
<p id="value2"></p>
<p id="value3"></p>
<p id="value4"></p>

it's working.
For testing I give random number to each variable I see online the random number generated.

MyValue1 = random(300);
MyValue2 = random(300);
MyValue3 = random(300);
MyValue4 = random(300);