HTML using a varable to from arduino in html calculation

I have a resistance read from the Arduino esp32 that i display on the HTML page.

I want to also use that number to help calculate and build a rectangle (see html code "Var pot_value = potreading;"" on the page that grows. The rectangle works when i place a real number like "Var pot_value =42" in the rectangle = location but not using "potreading".

The number from the Arduino shows in the html page displaying "potreading" but it wont work together. I may be wrong but i am guessing it does not see the "potreading" reading as a number but no matter what i try i cant get it to work. Please if anyone has any idea? I am just learning HTML and i have spent days trying to figure this out.

Arduino code
<#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include "index.h"  // Include the index.h file

#define RELAY_PIN 26  // ESP32 pin GPIO26 connected to Relay to start engine
//#define potPin 34  // ESP32 pin GPIO34 to monitor resistance sensor

int relay_state = LOW;
int potValue = 0;
int  oil_levelvalue = 0;
int  oil_tempvalue = 0;
int  coolant_levelvalue = 0;
int  coolant_tempvalue = 0;
int  battery_levelvalue = 0;


const char* ssid = "test"; // CHANGE IT
const char* password = "12345678"; // CHANGE IT
const int potPin = 34;
const int oil_level = 36;
const int oil_temp = 39;
const int coolant_level = 35;
const int coolant_temp = 32;
const int battery_level = 33;
AsyncWebServer server(80);

//float getreadings() {
  // YOUR SENSOR IMPLEMENTATION HERE
  
//  return potValue;
//}
String getHTML() {
  String html = webpage;                                  // Use the HTML content from the index.h file
  html.replace("%RELAY_STATE%", relay_state ? "ON" : "OFF");  // update the relay state

  return html;
}


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

  WiFi.softAP(ssid, password);
//relay pin for engine start stop
  pinMode(RELAY_PIN, OUTPUT);  
  digitalWrite(RELAY_PIN, relay_state);

  IPAddress IP = WiFi.softAPIP();
  //Serial.print("AP IP address: ");
  //Serial.println(IP);
  // Serve the HTML page from the file
  server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    //Serial.println("ESP32 Web Server: New request received:");  // for debugging
    //Serial.println("GET /");                                    // for debugging

    request->send(200, "text/html", webpage);
  });

  // Define a route to get the potreading data
  server.on("/potreading", HTTP_GET, [](AsyncWebServerRequest* request) {
    //Serial.println("ESP32 Web Server: New request received:");  // for debugging
    //Serial.println("GET /potreading");                         // for debugging
    float potreading = potValue;
    // Format the potreading with two decimal places
    String potreadingStr = String(potreading);
    request->send(200, "text/plain", potreadingStr);
 });
  // Route to control the relay to start engine
  server.on("/relay1/on", HTTP_GET, [](AsyncWebServerRequest *request) {
   // Serial.println("ESP32 Web Server: New request received:");
   // Serial.println("GET /relay1/on");
    relay_state = HIGH;
    digitalWrite(RELAY_PIN, relay_state);
    request->send(200, "text/html", getHTML());
  });
  server.on("/relay1/off", HTTP_GET, [](AsyncWebServerRequest *request) {
    //Serial.println("ESP32 Web Server: New request received:");
    //Serial.println("GET /relay1/off");
    relay_state = LOW;
    digitalWrite(RELAY_PIN, relay_state);
    request->send(200, "text/html", getHTML());
  });

  // Start the server
  server.begin();
}

void loop() {
  potValue = analogRead(potPin); 
  oil_levelvalue = analogRead(oil_level);
  oil_tempvalue = analogRead(oil_temp);
  coolant_levelvalue = analogRead(coolant_level);
  coolant_tempvalue = analogRead(coolant_temp);
  battery_levelvalue = analogRead(battery_level);
  updateDisplay();
  delay(10000);
}
void updateDisplay(){
    Serial.print("oil_level: ");
    Serial.println(oil_levelvalue);

    Serial.print("oil_temp: ");
    Serial.println(oil_tempvalue);

    Serial.print("coolant_level: ");
    Serial.println(coolant_levelvalue);

    Serial.print("coolant_temp: ");
    Serial.println(coolant_tempvalue);

    Serial.print("battery_level: ");
    Serial.println(battery_levelvalue);

    Serial.print("potvalue: ");
    Serial.println(potValue);


}

HTML page

#ifndef WEBPAGE_H
#define WEBPAGE_H

const char* webpage = R"=====(
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
<style>
		#rectangle {
			height: 50px;
			background-color: rgb(0, 0, 0);
			transition: width 2s;
		}
</style>
</head>
<body>
    <h1>test</h1>
    <p>Potvalue: <span style="color: red;"><span id="potreading">Loading...</span> &#8451;</span></p>

<div id="rectangle" style="width: 50px;"></div>80

	<script>
    Var pot_value = potreading; // Change this value to adjust the width of the rectangle
		var rectangle = document.getElementById("rectangle");
		rectangle.style.width = pot_value * 10 + "px";
		rectangle.style.backgroundColor = "rgb(" + pot_value * 25 + ", " + pot_value * 10 + ", " + pot_value * 5 + ")";
	</script>

</body>
</html>

    <script>
        function fetchpotreading() {
            fetch("/potreading")
                .then(response => response.text())
                .then(data => {
                    document.getElementById("potreading").textContent = +data;
                          return number;
                });
        }
        fetchpotreading();
        setInterval(fetchpotreading, 4000); // Update every 4 seconds
    </script>

      <link rel='icon' href='data:,'>
      </head>
      <p>Eninge State: <span style='color: red;'>%RELAY_STATE%</span></p>
      <a href='/relay1/on'>Turn ON Engine</a>
      <br><br>
      <a href='/relay1/off'>Turn OFF Engine</a>

</body>
</html>
)=====";

#endif

I'm not sure I've got it, but as far as I can see, you here reply with a fixed text (constant) contained inside "webpage":

  server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send(200, "text/html", webpage);

Any reference to "potreading" here is completely unrelated to the variable you defined on Arduino because html and Javascript code are just client-side.

You should start either by splitting the "webpage" in two (the first up to "Var pot_value = " the second starting with ";var rectangle = document.getElementById("rectangle");...and so on", or avoiding a constant and make "webpage" as a string where you can replace any "$potreading$" instance with the string representing the value (in this case it's like a "token" or a "placeholder").

If you want to save RAM the first solution is preferred, so I'd just split "webpage" into "webpage1" and "webpage2", add a label (instead of the div) to show the numeric value, and use javascript to both show the value and set rectangle width. Something like (advise: untested code...):

#ifndef WEBPAGE_H
#define WEBPAGE_H

const char* webpage1 = R"(
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
<style>
		#rectangle {
			height: 50px;
			background-color: rgb(0, 0, 0);
			transition: width 2s;
		}
</style>
</head>
<body>
    <h1>test</h1>
    <p>Potvalue: <span style="color: red;"><span id="potreading"></span> &#8451;</span></p>
<div id="rectangle" style="width: 50px;"></div>80
	<script>
    Var pot_value = ";

const char* webpage2 = R"(;
                // Show the value using the "label"
                var potreading = document.getElementById("potreading");
                potreading.innerHTML = pot_value;
                // Set rectangle width
		var rectangle = document.getElementById("rectangle");
		rectangle.style.width = pot_value * 10 + "px";
		rectangle.style.backgroundColor = "rgb(" + pot_value * 25 + ", " + pot_value * 10 + ", " + pot_value * 5 + ")";
   ... and so on ...

Then send the response back by sending a concatenation of "webpage1", the current value, and "webpage2":

 server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send(200, "text/html", String(webpage1)+String(potreading)+String(webpage2));

HTH. Let me know...

Not sure I understand it all, but I will play with it and see what I can get from this idea.

Thanks!

Thanks for trying to help me out. I spent all day on it, but I just don't know enough to do what you are saying.

I had it working without the dynamic rectangle growing and changing colors "relays on/off, resistance reading on webpage and rectangle box with fixed number" I did not expect it to be so hard to just assign a variable (using the same value i am already displaying and updating" instead of a number to have it dynamically grow and change color. But i am new to html and its proving to be hard for me to pick up.

Thanks again!

using ESPAsyncWebServer you pass a parameter %potreading% to the HTML
at run time function

// The processor() function replaces any placeholders on the HTML text used to build the web page 
String processor(const String& var){

replaces the %potreading% with the actual value
e.g. see esp32-web-server-sent-events

Just replace the code in your Arduino code to build the response string, so instead of:

  server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send(200, "text/html", webpage);

replace it with:

 server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send(200, "text/html", String(webpage1)+String(potreading)+String(webpage2));

and change your webpage ("index.h") to split the constant string representing the html/javascript response page:

#ifndef WEBPAGE_H
#define WEBPAGE_H

const char* webpage1 = R"(
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
<style>
		#rectangle {
			height: 50px;
			background-color: rgb(0, 0, 0);
			transition: width 2s;
		}
</style>
</head>
<body>
    <h1>test</h1>
    <p>Potvalue: <span style="color: red;"><label id="potreading"></label> &#8451;</span></p>
<div id="rectangle" style="width: 50px;"></div>80
	<script>
    Var pot_value = ";

const char* webpage2 = R"(;
    // Show the value using the "label"
    var potreading = document.getElementById("potreading");
    potreading.innerHTML = pot_value;
    // Set rectangle width
		var rectangle = document.getElementById("rectangle");
		rectangle.style.width = pot_value * 10 + "px";
		rectangle.style.backgroundColor = "rgb(" + pot_value * 25 + ", " + pot_value * 10 + ", " + pot_value * 5 + ")";
	</script>
</body>
</html>

    <script>
        function fetchpotreading() {
            fetch("/potreading")
                .then(response => response.text())
                .then(data => {
                    document.getElementById("potreading").textContent = +data;
                          return number;
                });
        }
        fetchpotreading();
        setInterval(fetchpotreading, 4000); // Update every 4 seconds
    </script>

      <link rel='icon' href='data:,'>
      </head>
      <p>Eninge State: <span style='color: red;'>%RELAY_STATE%</span></p>
      <a href='/relay1/on'>Turn ON Engine</a>
      <br><br>
      <a href='/relay1/off'>Turn OFF Engine</a>

</body>
</html>
)";
#endif

The solution I suggested you is pretty "raw" but it'd work. If you aren't familiar with html and, in this case, also javascript, is a bit hard to start with but I strongly suggest you to study both html and javascript if you want to create some sort of dynamic pages.

Yeah, this is one of the possible solutions. But without sufficient knowledge of html and javascript is something that solves this specific problem only, he'll get into trouble again with the next steps..:wink:

Thanks i will try this. My only other plans is to add more of the same kind of sensors and showing them the same way. So nothing else crazy then more of the same. I will study what you gave and see what i can do. Thanks!

Just one more hint. If you need some kinda dynamic web pages, I suggest you to store their base code on an SD card so you'll be able to both create more complex pages and update them just by updating the files instead of recompiling and uploading the whole program. Your program will just load the required page (depending on the request) as a string, replace all the "tokens" representing the places where some values are to be shown (e.g. "$TEMP$" with temperature, "$PRESS$" with pressure, and so on), and then send the resulting string back to client to show the page.
Another way is to build "real" dynamic pages using javascript/Ajax (the page has a fixed source but values are to be fetched by some javascript code when loading the page, with separate html calls to Arduino). And maybe "refresh" the values at specific time intervals, or any other "dynamic" function you need.

But please note both approaches require you to study html and javascript first: if you think you'll need it for the next future, I can assure you that it won't be a waste of time...

I finally got it to verify and upload but I had to take out a lot of my old stuff. It would have a lot of errors and would not verify. But I was left with nothing working and the same none growing square I had with my original code but no other readings or controls. Not sure how I messed it up but copying and pasting what you had did not verify it had a lot of errors, so I am sure I broke it while trying to get it to compile.

#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include "index.h"  // Include the index.h file
#define RELAY_PIN 26  // ESP32 pin GPIO26 connected to Relay to start engine
//#define potPin 34  // ESP32 pin GPIO34 to monitor resistanse sensor

int relay_state = LOW;
int potValue = 0;
int  oil_levelvalue = 0;
int  oil_tempvalue = 0;
int  coolant_levelvalue = 0;
int  coolant_tempvalue = 0;
int  battery_levelvalue = 0;


const char* ssid = "test"; // CHANGE IT
const char* password = "12345678"; // CHANGE IT
const int potPin = 34;
const int oil_level = 36;
const int oil_temp = 39;
const int coolant_level = 35;
const int coolant_temp = 32;
const int battery_level = 33;
AsyncWebServer server(80);
String potreading;
String webpage2;
//float getreadings() {
  // YOUR SENSOR IMPLEMENTATION HERE
  
//  return potValue;
//}
//String getHTML() {
//  String html = webpage;                                  // Use the HTML content from the index.h file
//  html.replace("%RELAY_STATE%", relay_state ? "ON" : "OFF");  // update the relay state

//  return html;
//}


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

  WiFi.softAP(ssid, password);
//relay pin for engine start stop
  pinMode(RELAY_PIN, OUTPUT);  
  digitalWrite(RELAY_PIN, relay_state);

  IPAddress IP = WiFi.softAPIP();
  //Serial.print("AP IP address: ");
  //Serial.println(IP);
  // Serve the HTML page from the file
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send(200, "text/html", String(webpage1)+String(potreading)+String(webpage2));
});

  // Define a route to get the potreading data
  server.on("/potreading", HTTP_GET, [](AsyncWebServerRequest* request) {
    //Serial.println("ESP32 Web Server: New request received:");  // for debugging
    //Serial.println("GET /potreading");                         // for debugging
    float potreading = potValue;
    // Format the potreading with two decimal places
    String potreadingStr = String(potreading);
    request->send(200, "text/plain", potreadingStr);
 });
  // ////////////Route to control the relay to start engine
//  server.on("/relay1/on", HTTP_GET, [](AsyncWebServerRequest *request) {
   // Serial.println("ESP32 Web Server: New request received:");
   // Serial.println("GET /relay1/on");
//    relay_state = HIGH;
//    digitalWrite(RELAY_PIN, relay_state);
//    request->send(200, "text/html", getHTML());
//  });
//  server.on("/relay1/off", HTTP_GET, [](AsyncWebServerRequest *request) {
    //Serial.println("ESP32 Web Server: New request received:");
    //Serial.println("GET /relay1/off");
//    relay_state = LOW;
//    digitalWrite(RELAY_PIN, relay_state);
//    request->send(200, "text/html", getHTML());
//  });
/////////////////////
  // Start the server
  server.begin();
}

void loop() {
  potValue = analogRead(potPin); 
  oil_levelvalue = analogRead(oil_level);
  oil_tempvalue = analogRead(oil_temp);
  coolant_levelvalue = analogRead(coolant_level);
  coolant_tempvalue = analogRead(coolant_temp);
  battery_levelvalue = analogRead(battery_level);
  updateDisplay();
  delay(10000);
}
void updateDisplay(){
    Serial.print("oil_level: ");
    Serial.println(oil_levelvalue);

    Serial.print("oil_temp: ");
    Serial.println(oil_tempvalue);

    Serial.print("coolant_level: ");
    Serial.println(coolant_levelvalue);

    Serial.print("coolant_temp: ");
    Serial.println(coolant_tempvalue);

    Serial.print("battery_level: ");
    Serial.println(battery_levelvalue);

    Serial.print("potvalue: ");
    Serial.println(potValue);


}
#ifndef WEBPAGE_H
#define WEBPAGE_H

const char* webpage1 = R"(
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
<style>
		#rectangle {
			height: 50px;
			background-color: rgb(0, 0, 0);
			transition: width 2s;
		}
</style>
</head>
<body>
    <h1>test</h1>
    <p>Potvalue: <span style="color: red;"><label id="potreading"></label> &#8451;</span></p>
<div id="rectangle" style="width: 50px;"></div>80
	<script>
    Var pot_value = ";

const char* webpage2 = R"(;
    // Show the value using the "label"
    var potreading = document.getElementById("potreading");
    potreading.innerHTML = pot_value;
    // Set rectangle width
		var rectangle = document.getElementById("rectangle");
		rectangle.style.width = pot_value * 10 + "px";
		rectangle.style.backgroundColor = "rgb(" + pot_value * 25 + ", " + pot_value * 10 + ", " + pot_value * 5 + ");
	</script>
</body>
</html>

    <script>
        function fetchpotreading() {
            fetch("/potreading")
                .then(response => response.text())
                .then(data => {
                    document.getElementById("potreading").textContent = +data;
                          return number;
                });
        }
        fetchpotreading();
        setInterval(fetchpotreading, 4000); // Update every 4 seconds
    </script>

      <link rel='icon' href='data:,'>
      </head>
      <p>Eninge State: <span style='color: red;'>%RELAY_STATE%</span></p>
      <a href='/relay1/on'>Turn ON Engine</a>
      <br><br>
      <a href='/relay1/off'>Turn OFF Engine</a>

</body>
</html>
)";
#endif

Thanks, I am learning more each day, but I have so much more to learn to even come close to getting this down.

Well, I think you added this line when the compiler complained you haven't any "webpage2" variable defined, right?
If you carefully look inside "index.h" file (even the one you posted here), you'd note the color of the "const char* webpage2" definition isn't the same as "webpage1".
I mean this:
image
...
image

See the "webpage2" variable name isn't black? This is because the first string hasn't been closed so the whole "webpage1" variable contains all the text you see there, including the "webpage2" variable definition (obviously not good for the page/javascript integrity...).

Thus, instead of:

	<script>
    Var pot_value = ";

to "close" the first variable you should add a parenthesis:

	<script>
    Var pot_value = )";

In this case you should get rid of the "String webpage2;" also, then try to build the code again, and see if it works (sorry, I can't test your code, I don't have any ESP at the moment).
If it still won't work, post your full code again (if changed) but have a look at the html page source you have on your browser (don't post pictures, use your browser function to open up the full HTML source of the page and paste it here as "code").

Thanks again for the help and the time you are spending on this!

I see that now sometimes it so hard to see the obvious when i dont have that trained eye yet. I have one more i cant find. Getting the error "missing terminating " character" at the end of index.h file )";

#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include "index.h"  // Include the index.h file

#define RELAY_PIN 26  // ESP32 pin GPIO26 connected to Relay to start engine
//#define potPin 34  // ESP32 pin GPIO34 to monitor resistanse sensor

int relay_state = LOW;
int potValue = 0;
int  oil_levelvalue = 0;
int  oil_tempvalue = 0;
int  coolant_levelvalue = 0;
int  coolant_tempvalue = 0;
int  battery_levelvalue = 0;


const char* ssid = "test"; // CHANGE IT
const char* password = "12345678"; // CHANGE IT
const int potPin = 34;
const int oil_level = 36;
const int oil_temp = 39;
const int coolant_level = 35;
const int coolant_temp = 32;
const int battery_level = 33;
AsyncWebServer server(80);

//float getreadings() {
  // YOUR SENSOR IMPLEMENTATION HERE
  
//  return potValue;
//}
String getHTML() {
  String html = webpage;                                  // Use the HTML content from the index.h file
  html.replace("%RELAY_STATE%", relay_state ? "ON" : "OFF");  // update the relay state

  return html;
}


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

  WiFi.softAP(ssid, password);
//relay pin for engine start stop
  pinMode(RELAY_PIN, OUTPUT);  
  digitalWrite(RELAY_PIN, relay_state);

  IPAddress IP = WiFi.softAPIP();
  //Serial.print("AP IP address: ");
  //Serial.println(IP);
  // Serve the HTML page from the file
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    request->send(200, "text/html", String(webpage1)+String(potreading)+String(webpage2));
  });

  // Define a route to get the potreading data
  server.on("/potreading", HTTP_GET, [](AsyncWebServerRequest* request) {
    //Serial.println("ESP32 Web Server: New request received:");  // for debugging
    //Serial.println("GET /potreading");                         // for debugging
    float potreading = potValue;
    // Format the potreading with two decimal places
    String potreadingStr = String(potreading);
    request->send(200, "text/plain", potreadingStr);
 });
  // Route to control the relay to start engine
  server.on("/relay1/on", HTTP_GET, [](AsyncWebServerRequest *request) {
   // Serial.println("ESP32 Web Server: New request received:");
   // Serial.println("GET /relay1/on");
    relay_state = HIGH;
    digitalWrite(RELAY_PIN, relay_state);
    request->send(200, "text/html", getHTML());
  });
  server.on("/relay1/off", HTTP_GET, [](AsyncWebServerRequest *request) {
    //Serial.println("ESP32 Web Server: New request received:");
    //Serial.println("GET /relay1/off");
    relay_state = LOW;
    digitalWrite(RELAY_PIN, relay_state);
    request->send(200, "text/html", getHTML());
  });

  // Start the server
  server.begin();
}

void loop() {
  potValue = analogRead(potPin); 
  oil_levelvalue = analogRead(oil_level);
  oil_tempvalue = analogRead(oil_temp);
  coolant_levelvalue = analogRead(coolant_level);
  coolant_tempvalue = analogRead(coolant_temp);
  battery_levelvalue = analogRead(battery_level);
  updateDisplay();
  delay(10000);
}
void updateDisplay(){
    Serial.print("oil_level: ");
    Serial.println(oil_levelvalue);

    Serial.print("oil_temp: ");
    Serial.println(oil_tempvalue);

    Serial.print("coolant_level: ");
    Serial.println(coolant_levelvalue);

    Serial.print("coolant_temp: ");
    Serial.println(coolant_tempvalue);

    Serial.print("battery_level: ");
    Serial.println(battery_levelvalue);

    Serial.print("potvalue: ");
    Serial.println(potValue);


}
#ifndef WEBPAGE_H
#define WEBPAGE_H

const char* webpage1 = R"(
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
<style>
		#rectangle {
			height: 50px;
			background-color: rgb(0, 0, 0);
			transition: width 2s;
		}
</style>
</head>
<body>
    <h1>test</h1>
    <p>Potvalue: <span style="color: red;"><label id="potreading"></label> &#8451;</span></p>
<div id="rectangle" style="width: 50px;"></div>80
	<script>
    Var pot_value = )";

const char* webpage2 = R"(;
    // Show the value using the "label"
    var potreading = document.getElementById("potreading");
    potreading.innerHTML = pot_value;
    // Set rectangle width
		var rectangle = document.getElementById("rectangle");
		rectangle.style.width = pot_value * 10 + "px";
		rectangle.style.backgroundColor = "rgb(" + pot_value * 25 + ", " + pot_value * 10 + ", " + pot_value * 5 + ")";
	</script>
</body>
</html>

    <script>
        function fetchpotreading() {
            fetch("/potreading")
                .then(response => response.text())
                .then(data => {
                    document.getElementById("potreading").textContent = +data;
                          return number;
                });
        }
        fetchpotreading();
        setInterval(fetchpotreading, 4000); // Update every 4 seconds
    </script>

      <link rel='icon' href='data:,'>
      </head>
      <p>Eninge State: <span style='color: red;'>%RELAY_STATE%</span></p>
      <a href='/relay1/on'>Turn ON Engine</a>
      <br><br>
      <a href='/relay1/off'>Turn OFF Engine</a>

</body>
</html>
)";
#endif

The problem is all on your HTML/Javascript code: you make a lot of confusion!

First of all the HTML page structure that should be like this:

<html>
  <head>
    .... title
    .... headers
    .... scripts  which will be runned before loading the content of page
  </head>
  <body>
    .... the content of page
    .... other scripts which will be runned after loading the content of page
  </body>
</html>

Regarding your scripts

  • Var is not the same of var
  • return number; The variable number is undefined and the line is totally useless
  • the portion of script where you would change the rectangle size is executed only once on loading. Change as a function and call when you get potreading from the server (I think you should also scale the values because then you will probably always get a white background and a too wide width)

In addition you are using a "mixed" technique to update your page, which is even more confusing:

  • you get the potreading value with an asynchronous AJAX call (good)
  • you update the relay_state value using a placeholder (bad)

As for your webpage try this:

<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <style>
      #rectangle {
      height: 50px;
      background-color: rgb(0, 0, 0);
      transition: width 2s;
      }
    </style>
  </head>
  
  <body>
    <h1>test</h1>
    <p>Potvalue: <span style="color: red;"><span id="potreading">Loading...</span> &#8451;</span></p>
    <div id="rectangle" style="width: 50px;"></div>
    <a href='/relay1/on'>Turn ON Engine</a>
    <br><br>
    <a href='/relay1/off'>Turn OFF Engine</a>
    <p>Engine State: <span style='color: red;'>%RELAY_STATE%</span></p>

    <script>
      function setRectSize(val) {
        var pot_value = val; // Change this value to adjust the width of the rectangle
        var rectangle = document.getElementById("rectangle");
        rectangle.style.width = pot_value + "px";
        rectangle.style.backgroundColor = "rgb(" + pot_value * 25 + ", " + pot_value * 10 + ", " + pot_value * 5 + ")";
      }
      
      function fetchpotreading() {
        fetch("/potreading")
          .then(response => response.text())
          .then(data => {
              document.getElementById("potreading").textContent = data;
              setRectSize(data);
          });
      }
      fetchpotreading();
      setInterval(fetchpotreading, 4000); // Update every 4 seconds
    </script>

  </body>
</html>

Again, have a look at the code coloring. See the "reddish" webpage2 string content ends, and the next lines, starting from "</script>" are black? This means the compiler (in this case, even the forum color rendering...) doesn't understand the lines as part of the string. the reason is because you here have a semicolon you shouldn't have:
image
Move that semicolon before the last quotes (it's part of the javascript line terminating) and you won't get that error anymore.

But I strongly suggest you to better study both the C language and html/javascript, carefully read what @cotestatnt said about html page structure and syntax. When working with C language, html and javascript you should have a bit more practice with such topics. It lets you avoid such kind of pretty easy errors, and us trying to understand what you want/try to do and all subsequent trial and error processes.

I have a few days off coming up and will see what i can do. Thanks! I did mess with that line of code thinking it was a problem but had the wrong side deleted.

Well i have spent a few more days on it and still can't get it error free. I am getting frustrated so i am going to put the project down for a while. Thanks for the help.

Sorry to read you're frustrated and you're putting down the project. Please, don't.

The best advice I can try to give you is to make things easier, and face the problems one step at the time.

The project is not very complicated, basically it's just a web server responding to specific requests. So instead of trying to implement the functions altogether, start with just one at the time.

If you plan to extend the web server pages number (and you do), start consider storing all the web pages over an SD card (as I already suggested it before, see post #8), I think it's easier to manage the thing as it keeps the code shorter and lets you change the page content/behaviour without needing to recompile the whole code. And if you need to learn html and/or javascript make sure you'll need to do it often!

So start writing a first test sketch to reply to "GET /" with a simple fixed homepage (e.g. an "index.htm"), reading its text from the "index.htm" file over SD card into a local string buffer variable and send it back to the caller. I think you can easily do that task.

When it works, then start creating a "token replacer" function: before sending back the response, it should search the buffer for the "tokens" to be replaced, if they exist (just ignore if one or more tokens aren't included in the buffer). The tokens must start and end with a specific character of your choice, let's say like '$'. Start with a single token, to test with substitutions.
Connect a pushbutton to a pin (e.g. D9) set as INPUT_PULLUP, and change the "index.htm" page to include the button status, something like:

<div style="background-color: $BUTTON$;">BUTTON</div>

then replace the "$BUTTON$" token to be replaced with a color code based on the button status, e.g. "red" if HIGH (not pressed) or "green" if LOW (pressed).

Once you'll get such functionality you can start adding the required sensors, readings, and related tokens substitution.

Hope it helps you to get enthusiasm back...

It does thank you i needed the encouragement! I will tackle it again on my next days off.

Thanks again!

I got the basics working.. Thanks for the help! I will now spend time improving and adding to it.

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