Automatic website sensor value update

Hello everyone,

TL;DR (I want my photoresistor value A0 pin to update on the webpage without hustle of manually refreshing the page. How do I do it with this code?)

I am fairly new user to Arduino, and just recently got myself UNO R4 with Wifi feature, so I've been studying up IoT part of arduino, and had a question on how to make the values refresh without the need to actually refresh the "webpage". This is the code that I've been working with, which is mostly copy/paste from the arduino's example:

#include <WiFiS3.h>

char ssid[] = "WIFI NAME";             //self explanatory
char pass[] = "WIFI PASSWORD";      //self explanatory
int keyIndex = 0;                 // should I delete it?
int status = WL_IDLE_STATUS;      //connection status
WiFiServer server(80);            //server socket

WiFiClient client = server.available();

int ledPin = 2;
const int photoPin = A0;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); //FOR LED
  pinMode(photoPin, INPUT); //FOR PHOTORESISTOR
  
  while (!Serial);
  
  enable_WiFi();
  connect_WiFi();

  server.begin();
  printWifiStatus();

}

void loop() {
  client = server.available();

  if (client) {
    printWEB();
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");

  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
}

void enable_WiFi() {
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }
}

void connect_WiFi() {
  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
}

void printWEB() {

  if (client) {                             // if you get a client,
    Serial.println("new client");           // print a message out 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
        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();

            if (currentLine.endsWith("GET /value")) {
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/plain");
              client.println();
              client.print(analogRead(photoPin));
              break;
            }
           
            //create the buttons
            client.print("Click <a href=\"/H\">here</a> turn the LED on<br>");  //HERE WE CREATE A SIGNAL /H
            client.print("Click <a href=\"/L\">here</a> turn the LED off<br><br>"); //HERE WE CREATE A SIGNAL /L
            
            int photoValue = analogRead(photoPin);
            client.print("Readings from photoresistor: ");
            client.print(photoValue);
           
            
            

            // 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
        }

        if (currentLine.endsWith("GET /H")) {
          digitalWrite(2, HIGH);        
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(2, LOW);       
        }

      }
    }
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

In raspberry pi I know that you can embed the HTML file separately, and have the JS mainly running, so you dont have to do the "dirty refresh"...but I am not sure how it works in arduino :confused:

1 Like

I no nothing about HTML but I think this same question came up yesterday (is this a school project). The answer was to use POST not GET IIRC.

1 Like

@sonofcy No its not a school project, I am just a regular hobbyist :slight_smile: teaching myself from internet. And I am not sure what you mean by POST vs GET. Can you clarify it for me a bit more? Im feeling lost in WiFi and Bluetooth territory of arduinos. And thank you for your response!

Like I said I know nothing about HTML. I would simply google those terms.

@sonofcy This has nothing to do with HTML...I just brought in example that I remember that in order to refresh page seamlessly, you can just JS on the webpage (for RPis), but I dont know how Arduino's localhost work

Good luck.

HTML has the capability to refresh a page, and you can even give the time between refreshes. HTML meta http-equiv Attribute (the link does not say "refresh" but it leads you directly there)

1 Like
  • One way is to refresh the page with a meta tag / refresh.
  • Another way is to modify the content of the page using FetchAPI/JavaScript.

I don't have an example for the Arduino Uno R4 wifi, but this works for an Arduino Uno R3 + Ethernet Shield and should give you an idea what's needed to do:

Arduino Webserver automatica refresh of page with Fetch API.

1 Like

@noiasca @xfpd thank you very much! Im gonna look at it tomorrow and update you guys.

Some other notes:

On R4, WiFi.begin ends with its own "wait for WL_CONNECTED" loop. So doing it this way means you are guaranteed to wait ten extra seconds for nothing every time you restart.

When that if condition is true, this ends up sending the 200 OK and response headers twice. That won't work; you need to rearrange the conditions. In addition, that condition basically will never be true; the same with

because the HTTP request start-line would look like

GET /H HTTP/1.1

meaning that it would startsWith the GET verb, not endsWith it. Is this code "AI"-generated?

1 Like

You can do the same also with Uno R4.
Some time ago, I developed a library for this MCU by porting the WebServer class included in the ESP32 core for Arduino.
I have added it to the official Arduino IDE repository also and all the examples you can find have been successfully tested.

The example stringLiteral.ino might suit your needs: the web page displays two gauges that are autonomously updated with MCU's random values using JavaScript (Fetch API).

I'm sorry for the Italian text, I will update in the next release.

1 Like

@kenb4 I couldnt find a solid ground documentation that explains step by step how this works, so the code that I attached is a mix what I found on arduino's project website (tutorial), youtube and chatgpt. But frankly AI sucks so I only use it for debugging.

I wish there was a lot more in depth guide that goes through setting up wifi and bluetooth :frowning:

Thank you for the notes though! When I get home today, I will go through the code and make those adjustments.

@cotestatnt Thank you very much! This is definitely very useful, I couldnt find any information on the cleaner refreshers, but this is exactly what I was looking for!!! When I'll get home from work, I will go through this and hopefully fix my code :smiley: