ESP32 LittleFS index.html show value on website question :)

Hey there,
I have an ESP32 with which a fan is controlled. It is controlled via a website (index.html).
It looks like this:

//Webaddress: 192.168.178.66/html

#include "LittleFS.h"
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFiMulti.h>



#define FAN1 25
#define PWM_CH_FAN 1
#define PWM_RES 8
const int MAX_DC = (int)(pow(2, PWM_RES) - 1);

// GPIO where the DS18B20 is connected to
const int oneWireBus = 33;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
//Variable to store RPM or fan state
//String fanstate = "";

// Variables to store temperature values
String temperatureC = "";
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 2000;


// Replace with your network credentials
const char *ssid = "dgdfgdfgdg";
const char *password = "fdgdfgdgddgd";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

const char *PARAM_INPUT_1 = "start50";
const char *PARAM_INPUT_2 = "start100";
const char *PARAM_INPUT_3 = "activate";
const char *PARAM_INPUT_4 = "setspeed";
String inputParam;
String inputsetspeed;
String inputstate;
String inputstart50;
String inputstart100;
int intinputsetspeed = 0;
int fanvalue = 0;



String readDSTemperatureC() {
  // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);

  if (tempC == -127.00) {
    Serial.println("Failed to read from DS18B20 sensor");
    return "--";
  } else {
    Serial.print("Temperature Celsius: ");
    Serial.println(tempC);
  }
  return String(tempC);
}

// Replaces placeholder with DS18B20 values
String processor(const String &var) {
  //Serial.println(var);
  if (var == "TEMPERATUREC") {
    return temperatureC;
  }
  return String();
}

WiFiMulti wifiMulti;

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

  delay(10);

  wifiMulti.addAP("fritzboxdampf", "92091143543959477057");
  wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
  wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

  Serial.println("Connecting Wifi...");
  if (wifiMulti.run() == WL_CONNECTED) {
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }
  Serial.println();

  // Print ESP Local IP Address
  Serial.println(WiFi.localIP());

  if (!LittleFS.begin()) {
    Serial.println("An Error has occurred while mounting LittleFS");
    return;
  }

  File file = LittleFS.open("/index.html", "r");
  if (!file) {
    Serial.println("Failed to open file for reading");
    return;
  }

  Serial.println("File Content:");
  while (file.available()) {
    Serial.write(file.read());
  }
  file.close();

  // PWM CH 1 (FAN)
  // 5 kHz freq
  // 8 bit resolution
  // attached to GPIO 25
  ledcSetup(PWM_CH_FAN, 5000, PWM_RES);
  ledcAttachPin(FAN1, PWM_CH_FAN);
  delay(3000);
  // kick start the FAN
  ledcWrite(PWM_CH_FAN, MAX_DC);
  Serial.print("MAX_DC: ");
  Serial.println(MAX_DC);
  delay(1000);

  // Start up the DS18B20 library
  sensors.begin();

  temperatureC = readDSTemperatureC();

  // Route for root / web page
  server.on("/html", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(LittleFS, "/index.html", "text/html");
  });
  // Send a GET request to <ESP_IP>/get?input1=<inputMessage>
  server.on("/get", HTTP_GET, [](AsyncWebServerRequest *request) {
    // GET input1 value on <ESP_IP>/get?input1=<inputMessage>
    if (request->hasParam(PARAM_INPUT_1)) {
      inputstart50 = request->getParam(PARAM_INPUT_1)->value();
      inputParam = PARAM_INPUT_1;
    }
    // GET input2 value on <ESP_IP>/get?input2=<inputMessage>
    else if (request->hasParam(PARAM_INPUT_2)) {
      inputstart100 = request->getParam(PARAM_INPUT_2)->value();
      inputParam = PARAM_INPUT_2;
    }
    // GET input3 value on <ESP_IP>/get?input3=<inputMessage>
    else if (request->hasParam(PARAM_INPUT_3)) {
      inputstate = request->getParam(PARAM_INPUT_3)->value();
      inputParam = PARAM_INPUT_3;
    }
    // GET input2 value on <ESP_IP>/get?input2=<inputMessage>
    else if (request->hasParam(PARAM_INPUT_4)) {
      inputsetspeed = request->getParam(PARAM_INPUT_4)->value();
      inputParam = PARAM_INPUT_4;
    }



    request->send(200, "text/html", "HTTP GET request sent to your ESP on input field (" + inputParam + ") with value: "
                                                                                                        "<br><a href=\"/\">Return to Home Page</a>");
  });

  server.begin();
}


void loop() {
  if ((millis() - lastTime) > timerDelay) {

    convert();

    Serial.println(intinputsetspeed);
    Serial.println(inputstart50);
    Serial.println(inputstart100);
    Serial.println(inputstate);
    temperatureC = readDSTemperatureC();
    if (wifiMulti.run() != WL_CONNECTED) {
      Serial.println("WiFi not connected!");
    }
         fanON();
    lastTime = millis();
  }
}


void convert()
{
  intinputsetspeed = inputsetspeed.toInt();
  if (intinputsetspeed == 25) {
    fanvalue = 65;
  } else if (intinputsetspeed == 50) {
    fanvalue = 125;
  } else if (intinputsetspeed == 75) {
    fanvalue = 180;
  } else if (intinputsetspeed == 100) {
    fanvalue = 255;
  } else if (intinputsetspeed == 0) {
    fanvalue = 0;
  }
}

void fanON() {

  Serial.println("set fan value now");
 
  ledcWrite(PWM_CH_FAN, fanvalue);
}

<!DOCTYPE HTML>
<html>
   <head>
      <title>Fan-Control</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
	  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
   </head>
   <body onload="getActualValues()">
 <form action="/get">
         lower temperature threshold: <input type="range" name="start50" value="30" min="0" max="100" oninput="this.nextElementSibling.value = this.value">
         <output>30</output>°C
        <span id="start100-actual"></span> 
		<input type="submit" value="Submit">
      </form>
      <br>
 <form action="/get">
         upper temperature threshold: <input type="range" name="start100" value="50" min="0" max="100" oninput="this.nextElementSibling.value = this.value">
        <output>50</output>°C
        <span id="start100-actual"></span> 
		<input type="submit" value="Submit">
      </form>
      <br>
      <form action="/get">
         automated control ON: <input type="radio" name="activate" value="on"><br>
         automated control OFF: <input type="radio" name="activate"  value="off"><br>
         <input type="submit" value="Submit">
         <br>
         <b><span id="activate-actual">Actual fan-state: xxxx</span></b>
      </form>
      <form action="/get">
         <label for="illumination">Manuelle Steuerung:</label>
         <select id="illumination" name="setspeed">
            <option value="0">off</option>
            <option value="25">25%</option>
            <option value="50">50%</option>
            <option value="75">75%</option>
            <option value="100">100%</option>
         </select>
         <input type="submit" value="Submit">
      </form>
      
      <script>      
        function getActualValues() {
          var url = new URL("http://" + `${window.location.hostname}` + "/getValues")
          fetch(url)

          .then(response => response.json())
          .then(data => {
          

I have two questions.
1.) How can I display a variable on the website?
2) If I confirm a value with submit, then the index.html should only update itself (actual fan state). No further site must/should be displayed, as is currently the case.

Maybe someone has time and would like to help me :slight_smile:

Does this demo (which I also currently have on my desk) help ? It is very easy to set up since you are already using the asyncwebserver : ESP32 ESPAsyncWebServer sample demonstration application

When I want to display variables on a website using ESPAsyncWebServer.h, I use the method where place holders are put in the html with percent chars either side. E.g. in the html %REPLACEME%.
Then there is a function in the code called processor, it gets called back when the data for the website is being prepared for sending. The processor function allows you to replace %REPLACEME% with any String.
The code in this example uses the above technique.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.