The goal of this project was to learn how to stream live data from a sensor using a NodeMCU ESP8266, which enables us to create a web server.

While the basic part involves using the right library to create the server and adding some HTML code to display it, it is not enough to keep it updated without having to refresh the page in the browser.

So, I tried different methods:

  • Create a Flask server on an EC2 (AWS) instance and send the sensor data.
  • Same thing but the server is local.
  • Using webSockets locally.

For the first approach I used a Flask server with the microcontroller transmitting the data via the POST method. While the setup was successful, a notable “challenge” arose in the form of high latency, which is to be expected.

For the second one, same thing happend.

Ultimately, the simplest method proved to be the most effective and less complicated.

The example was made using the ESP8266 microcontroller and the Arduino framework, using PlatformIO.

I will now show the most important parts of the code. The rest is simply using the library to create the web server and adding the connection data.


#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <WebSocketsServer.h>
.......
ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
.......
void handleRoot() {
  ....
  html += "<h2>Score: <span id=\"contador\">" + String(contador) + "</span></h2>";
  html += "<script>";
  html += "var socket = new WebSocket('ws://' + window.location.hostname + ':81/');";
  html += "socket.onmessage = function(event) {";
  html += "  document.getElementById('counter').innerHTML = event.data;";
  html += "}";
  html += "</script>";
  ....
  server.send(200, "text/html", html);
}

void setup() {
  ...
  server.on("/", handleRoot);
  server.begin();
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}
void loop() {
  server.handleClient();
  webSocket.loop();
  ...
  webSocket.broadcastTXT(buffer);
}