bob
bob

Reputation: 11

updating variable on local hosted webpage without reloading

I have had this problem with an esp8266 nodemcu where I cannot seem to find a way to update a variable on a webpage without having to sit there and spam F5, the project is for a weather vane to show which way the wind is going in real time. Here is the code which hosts the webpage, shows the variable but a refresh is needed to update the data:



// Include necessary libraries
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

// Set WiFi credentials
const char* ssid = "wifi_Username";
const char* password = "wifi_Password";

// Create web server object
ESP8266WebServer server(80);

// Define analog pin for wind direction sensor
const int windDirectionPin = A0;

// Variable to store wind direction value
int windDirectionValue = 0;

// Function to handle root path request
void handleRoot() {
  // Read wind direction value from analog pin
  windDirectionValue = analogRead(windDirectionPin);

  // Send HTML code to client
  server.send(200, "text/html", "<h1>Wind Direction: " + String(windDirectionValue) + "</h1>");
}

// Function to handle not found path request
void handleNotFound() {
  // Send error message to client
  server.send(404, "text/plain", "Not found");
}

// Setup function
void setup() {
  // Initialize serial communication
  Serial.begin(9600);

  // Connect to WiFi network
  WiFi.begin(ssid, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Print WiFi network information
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Start web server
  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);
  server.begin();

  // Print server status
  Serial.println("Server started");
}

// Loop function
void loop() {
  // Handle client requests
  server.handleClient();
}

The code should host the webpage and show the variable on the webpage, however I cannot find a way to automate a refresh (excluding js meta refresh because it doesn't refresh fast enought and looks really bad)

Upvotes: 0

Views: 70

Answers (0)

Related Questions