ESP32 How to change INT var on webpage

I'm searching now for two weeks and i can't figure it out how to implement it in my code.
I want to be able to adjust the value ZonAAN and ZonUIT on the web page.
Can someone help me with this please?
And possibly also explain why an INT is not shown in an inputTEXT field, in another way I can make it appear, see next to the input text.

The code:

#include <Arduino.h>
#include "config.h"
#include <HardwareSerial.h>
#include <ModbusMaster.h>
#include <SPI.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

//Login gegevens van AP
const char* ssid = "CAIRRA";
const char* password = "CAIRRA2022";

WiFiServer server(80);
String header;

HardwareSerial Serial485(2);
ModbusMaster node;

// set pin numbers
const int buttonPin = 18;  // the number of the pushbutton pin

// variable for storing the pushbutton status
int buttonState = 0;

//Temperatuur instellingen per status
int zonAAN = 60;
int zonUIT = 50;

//Modbusregister schrijven
int ModRegister = 6;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup()
{
  pinMode(RS485_EN_PIN, OUTPUT);
  digitalWrite(RS485_EN_PIN, HIGH);

  pinMode(RS485_SE_PIN, OUTPUT);
  digitalWrite(RS485_SE_PIN, HIGH);

  pinMode(PIN_5V_EN, OUTPUT);
  digitalWrite(PIN_5V_EN, HIGH);

  Serial.begin(9600);
  Serial485.begin(9600, SERIAL_8N1, RS485_RX_PIN, RS485_TX_PIN);
  delay(5);
  Serial.println("test");
  //Slave id = 2
  node.begin(2, Serial485);
  // initialize the pushbutton pin as an input
  pinMode(buttonPin, INPUT);

  // Connect to Wi-Fi network with SSID and password
  Serial.println("Configuring access point...");
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
  Serial.println("Wait 100 ms for AP_START...");
  delay(100);

  Serial.println("Set softAPConfig");
  IPAddress Ip(192, 168, 1, 1);
  IPAddress NMask(255, 255, 255, 0);
  WiFi.softAPConfig(Ip, Ip, NMask);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.begin();
}

void loop()
{
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            
            // CSS style
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button {background-color: #4CAF50; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #555555;}");
            client.println("</style></head>");

            // Web Page Heading
            client.println("<body><h1>HEATPUMP</h1>");

            // Display current state, and settings for watertemp
            client.println("<p>Zonnepanelen</p>");
            if (buttonState == HIGH) {
              client.println("<p><button class=\"button\">AAN</button></p>");
            } else {
              client.println("<p><button class=\"button button2\">UIT</button></p>");
            }
            client.println("<p></p>");
            client.println("<p>Watertemperatuur bij gesloten contact:</p>");
            client.println(zonAAN);
            client.println("<label for='WaterHIGH'></label><input type='text' id='WaterHIGH' name='WaterHIGH' maxlength='2' size='4' value=zonAAN>");
            client.print((char)176);
            client.print("C  ");
            client.println("<a href=\"/rgbw/apply\"><button class=\"button3\">SET</button></a>");
            client.println("<p></p>");

            client.println("<p>Watertemperatuur bij open contact:</p>");
            client.println(zonUIT);
            client.println("<label for='WaterLOW'></label><input type='text' id='WaterLOW' name='WaterLOW' maxlength='2' size='4' value='50'>");
            client.print((char)176);
            client.print("C  ");
            client.println("<a href=\"/rgbw/apply\"><button class=\"button3\">SET</button></a>");
            client.println("<p></p>");
            client.println("</body></html>");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }

  // read the state of the pushbutton value
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH
  if (buttonState == HIGH) {
    // turn LED on
    Serial.println("Contact gesloten");
    node.writeSingleRegister(ModRegister, zonAAN);
  } else {
    // turn LED off
    Serial.println("Contact open");
    node.writeSingleRegister(ModRegister, zonUIT);
  }
  delay(2000);
}

Is one of your problems that the above statement is printing "zonAAN" instead of a numeric value ?

That is indeed one of my problems.

You may get further if your replace this:


client.println("<label for='WaterHIGH'></label><input type='text' id='WaterHIGH' name='WaterHIGH' maxlength='2' size='4' value=zonAAN>");

with this:


client.print("<label for='WaterHIGH'></label><input type='text' id='WaterHIGH' name='WaterHIGH' maxlength='2' size='4' value='") ;
client.print( zonAAN ) ;
client.println( "'>" ) ;

Can you post a link to the tutorial you have been following. There are a number of ways of refreshing information on a web page.

Thank you, this was the solution.
Now i can figure out how to set a new value to it.

The thing is, it is not a single tutorial.
I used

and a lot of snippets from all over the internet.

But in meanwhile, i changed the whole code.
So in this code, i can adjust the value's, but now the button is not working.

if (buttonState == HIGH) {
  <button class="button">ON</button>;
} else {
  <button class="button button3">OFF</button>;
}
/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-input-data-html-form/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

#include <Arduino.h>
#include "config.h"
#include <HardwareSerial.h>
#include <ModbusMaster.h>
#include <SPI.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include "Freenove_WS2812_Lib_for_ESP32.h"

#define LEDS_COUNT  1
#define LEDS_PIN  4
#define CHANNEL   0

Freenove_ESP32_WS2812 strip = Freenove_ESP32_WS2812(LEDS_COUNT, LEDS_PIN, CHANNEL, TYPE_GRB);

AsyncWebServer server(80);

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "
const char* password = 

const char* PARAM_INTHigh = "inputIntHigh";
const char* PARAM_INTLow = "inputIntLow";

HardwareSerial Serial485(2);
ModbusMaster node;

// set pin numbers
const int buttonPin = 18;  // the number of the pushbutton pin

// variable for storing the pushbutton status
int buttonState = 0;

//Modbusregister schrijven
int ModRegister = 6;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

// HTML web page
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><head>
  <title>HEATPUMP Input Form</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html {font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}
//button {background-color: #4CAF50; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
//button2 {background-color: #555555;}

.button {
  background-color: #4CAF50; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

.button2 {background-color: #008CBA;} /* Blue */
.button3 {background-color: #f44336;} /* Red */ 
.button4 {background-color: #e7e7e7; color: black;} /* Gray */ 
.button5 {background-color: #555555;} /* Black */

input[type='number']{
    width: 50px;
}
</style>
  
  <script>
    function submitMessage() {
      alert("Instelling word gecontrolleerd");
      setTimeout(function(){ document.location.reload(false); }, 2000);   
    }
  </script></head><body>
  <h1>HEATPUMP</h1>

if (buttonState == HIGH) {
  <button class="button">ON</button>;
} else {
  <button class="button button3">OFF</button>;
}
  
  <form action="/get" target="hidden-form">
    Watertemperatuur bij gesloten contact:<br><br>
    <input type="number" name="inputIntHigh" min="30" max="60" value="%inputIntHigh%">
    <input type="submit" value="Opslaan" onclick="submitMessage()">
  </form><br><br>
  <form action="/get" target="hidden-form">
    Watertemperatuur bij open contact:<br><br>
    <input type="number" name="inputIntLow" min="30" max="60" value="%inputIntLow%">
    <input type="submit" value="Opslaan" onclick="submitMessage()">
  </form>
  <iframe style="display:none" name="hidden-form"></iframe>
  
</body></html>)rawliteral";

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

String readFile(fs::FS &fs, const char * path) {
  Serial.printf("Reading file: %s\r\n", path);
  File file = fs.open(path, "r");
  if (!file || file.isDirectory()) {
    Serial.println("- empty file or failed to open file");
    return String();
  }
  Serial.println("- read from file:");
  String fileContent;
  while (file.available()) {
    fileContent += String((char)file.read());
  }
  file.close();
  Serial.println(fileContent);
  return fileContent;
}

void writeFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Writing file: %s\r\n", path);
  File file = fs.open(path, "w");
  if (!file) {
    Serial.println("- failed to open file for writing");
    return;
  }
  if (file.print(message)) {
    Serial.println("- file written");
  } else {
    Serial.println("- write failed");
  }
  file.close();
}

// Replaces placeholder with stored values
String processor(const String& var) {
  //Serial.println(var);
  if (var == "inputIntHigh") {
    return readFile(SPIFFS, "/inputIntHigh.txt");
  }
  else if (var == "inputIntLow") {
    return readFile(SPIFFS, "/inputIntLow.txt");
  }
  return String();
}

void setup() {
  pinMode(RS485_EN_PIN, OUTPUT);
  digitalWrite(RS485_EN_PIN, HIGH);

  pinMode(RS485_SE_PIN, OUTPUT);
  digitalWrite(RS485_SE_PIN, HIGH);

  pinMode(PIN_5V_EN, OUTPUT);
  digitalWrite(PIN_5V_EN, HIGH);

  Serial.begin(9600);
  Serial485.begin(9600, SERIAL_8N1, RS485_RX_PIN, RS485_TX_PIN);
  delay(5);
  Serial.println("test");
  //Slave id = 2
  node.begin(2, Serial485);
  // initialize the pushbutton pin as an input
  pinMode(buttonPin, INPUT);

  // Initialize SPIFFS
#ifdef ESP32
  if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
#else
  if (!SPIFFS.begin()) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
#endif

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Failed!");
    return;
  }
  Serial.println();
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // Send web page with input fields to client
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/html", index_html, processor);
  });

  // Send a GET request to <ESP_IP>/get?inputIntHigh=<inputMessage>
  server.on("/get", HTTP_GET, [] (AsyncWebServerRequest * request) {
    String inputMessage;
    // GET inputIntHigh value on <ESP_IP>/get?inputIntHigh=<inputMessage>
    if (request->hasParam(PARAM_INTHigh)) {
      inputMessage = request->getParam(PARAM_INTHigh)->value();
      writeFile(SPIFFS, "/inputIntHigh.txt", inputMessage.c_str());
    }
    // GET inputInt value on <ESP_IP>/get?inputInt=<inputMessage>
    else if (request->hasParam(PARAM_INTLow)) {
      inputMessage = request->getParam(PARAM_INTLow)->value();
      writeFile(SPIFFS, "/inputIntLow.txt", inputMessage.c_str());
    }
    else {
      inputMessage = "No message sent";
    }
    Serial.println(inputMessage);
    request->send(200, "text/text", inputMessage);
  });
  server.onNotFound(notFound);
  server.begin();
  strip.begin();
  strip.setBrightness(5);
}

void loop() {

  int HighTemp = readFile(SPIFFS, "/inputIntHigh.txt").toInt();
  Serial.print("*** Your inputInt: ");
  Serial.println(HighTemp);

  int LowTemp = readFile(SPIFFS, "/inputIntLow.txt").toInt();
  Serial.print("*** Your inputInt: ");
  Serial.println(LowTemp);

  // read the state of the pushbutton value
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH
  if (buttonState == HIGH) {
    // turn LED GREEN
    strip.setLedColor(0, 0, 255, 0);
    Serial.println("Contact gesloten");
    node.writeSingleRegister(ModRegister, HighTemp);
  } else {
    // turn LED RED
    strip.setLedColor(0, 255, 0, 0);
    Serial.println("Contact open");
    node.writeSingleRegister(ModRegister, LowTemp);
  }
  delay(2000);
}

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