ESP32 WebSerial: Web-based Remote Serial Monitor

In this guide, you’ll learn how to create and use a web-based “Serial Monitor” for your ESP32 projects using the WebSerial library. This creates a web-based interface to output debugging messages, as you would do with a regular serial monitor. You can also send messages from the web-based serial monitor to the ESP32.

ESP32 WebSerial Web-based Remote Serial Monitor Arduino Core IDE

We have a similar tutorial for the ESP8266 board: ESP8266 NodeMCU WebSerial Web-based Remote Serial Monitor

Web-based Serial Monitor

In most of your ESP32 projects, you use the serial monitor to output debugging messages that help you better understand what’s happening with the microcontroller.

You create a Serial communication between your board and your computer, and then you can visualize the messages using the serial monitor. However, when your board is not connected to your computer, you can’t see the debugging messages.

A workaround for this issue is to use a web-based serial monitor—the ESP32 hosts a web server that serves a page to visualize the messages as you would with the “regular” serial monitor. The WebSerial web page also allows you to send data from the web page to your board.

WebSerial Library ESP32 ESP8266 web-based Serial Monitor

For this tutorial, we’ll use the WebSerial library.

If you like this library and you’ll use it in your projects, consider supporting the developer’s work.

WebSerial Features

List of WebSerial features:

  • Works on WebSockets;
  • Realtime logging;
  • Any number of serial monitors can be opened on the browser;
  • Uses AsyncWebserver for better performance.

WebSerial Functions

Using WebSerial is similar to use the serial monitor. Its main functions are print() and println():

  • print(): prints the data on the web-based serial monitor without newline character (on the same line);
  • println(): prints the data on the web-based serial monitor with a newline character (on the next line);

Installing the WebSerial Library

For this project, we’ll use the WebSerial.h library. To install the library:

  1. In your Arduino IDE, go to Sketch > Include Library > Manage Libraries…
  2. Search for webserial.
  3. Install the WebSerial library by Ayush Sharma.
Installing Web Serial Library Arduino IDE

You also need to install the ESPAsyncWebServer and the AsyncTCP libraries. Click the following links to download the libraries’ files.

To install these libraries, click on the previous links to download the libraries’ files. Then, in your Arduino IDE, go to Sketch > Include Library > Add .ZIP Library…

If you’re using VS Code with the PlatformIO extension, copy the following to the platformio.ini file to include the libraries.

lib_deps = ESP Async WebServer
  ayushsharma82/WebSerial @ ^1.1.0

ESP32 WebSerial Example

The library provides a simple example about creating the Web Serial Monitor to output and receive messages. We’ve modified the example a bit to make it more interactive.

This example prints Hello! to the web-based serial monitor every two seconds. Additionally, you can send messages from the web-based serial monitor to the board. You can send the message ON to light up the board’s built-in LED or the message OFF to turn it off.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-webserial-library/
  
  This sketch is based on the WebSerial library example: ESP32_Demo
  https://github.com/ayushsharma82/WebSerial
*/

#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <WebSerial.h>

#define LED 2

AsyncWebServer server(80);

const char* ssid = "REPLACE_WITH_YOUR_SSID";          // Your WiFi SSID
const char* password = "REPLACE_WITH_YOUR_PASSWORD";  // Your WiFi Password

void recvMsg(uint8_t *data, size_t len){
  WebSerial.println("Received Data...");
  String d = "";
  for(int i=0; i < len; i++){
    d += char(data[i]);
  }
  WebSerial.println(d);
  if (d == "ON"){
    digitalWrite(LED, HIGH);
  }
  if (d=="OFF"){
    digitalWrite(LED, LOW);
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.printf("WiFi Failed!\n");
    return;
  }
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  // WebSerial is accessible at "<IP Address>/webserial" in browser
  WebSerial.begin(&server);
  WebSerial.msgCallback(recvMsg);
  server.begin();
}

void loop() {
  WebSerial.println("Hello!");
  delay(2000);
}

View raw code

Before uploading the code to your board, don’t forget to insert your network credentials.

In this example, the ESP32 is in station mode. This example also works in access point mode. To learn how to set up your ESP32 as an access point, read:

How the Code Works

Continue reading to learn how the code works or skip to the demonstration section.

First, you need to include the required libraries for WebSerial. The WiFi.h library is needed to connect the ESP32 to a Wi-Fi network.

#include <WiFi.h>

The WebSerial library uses the AsyncTCP and the ESPAsyncWebServer libraries to create the web-based serial monitor.

#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

Finally, the WebSerial library provides easy methods to build the web-based serial monitor.

#include <WebSerial.h>

Create a variable called LED for the built-in LED on GPIO 2.

#define LED 2

Initialize an AsyncWebServer object on port 80 to set up the web server.

AsyncWebServer server(80);

Insert your network credentials in the following variables:

const char* ssid = "REPLACE_WITH_YOUR_SSID"; // Your WiFi SSID
const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // Your WiFi Password

Handling Received Messages

The following function receives incoming messages sent from the web-based serial monitor. The message is saved on the d variable. Then, it is printed on the web serial monitor using WebSerial.println(d).

void recvMsg(uint8_t *data, size_t len){
  WebSerial.println("Received Data...");
  String d = "";
  for(int i=0; i < len; i++){
    d += char(data[i]);
  }
  WebSerial.println(d);

Next, we check if the content of the d variable is ON or OFF and light up the LED accordingly.

if (d == "ON"){
  digitalWrite(LED, HIGH);
}
if (d=="OFF"){
  digitalWrite(LED, LOW);
}

setup()

In the setup(), set the LED as an OUTPUT.

pinMode(LED, OUTPUT);

Connect your board to your local network:

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

Initialize the web-based serial monitor with the begin() method on the WebSerial object. This function accepts as an argument an AsyncWebServer object.

WebSerial.begin(&server);

Register the recvMsg() as a callback function using the msgCallback() method on the WebSerial object. The recvMsg() function will run whenever you send a message from the monitor to the board.

WebSerial.msgCallback(recvMsg);

Finally, initialize the server.

server.begin();

It is just after calling this line that the web-based serial monitor will start working.

loop()

In the loop(), print the Hello! message every 2000 milliseconds (2 seconds) using the println() function on the WebSerial object.

void loop() {
  WebSerial.println("Hello!");
  delay(2000);
}

Demonstration

After inserting your network credentials, you can upload the code to your board.

After uploading, open the “regular” serial monitor at a baud rate of 115200. The board’s IP address will be printed.

ESP32 WebSerial Web-based Remote Serial Monitor Arduino IDE Demonstration

Now, open a browser on your local network and type the ESP IP address followed by /webserial. For example, in my case:

192.168.1.85/webserial

The WebSerial page should load.

Testing Web Serial Library Basic Example Demonstration

As you can see, it is printing Hello! every two seconds. Additionally, you can send commands to the ESP32. All the commands that you send are printed back on the web serial monitor. You can send the ON and OFF commands to control the built-in LED.

ESP32 board Built in LED turned on HIGH

This was just a simple example showing how you can use the WebSerial library to create a web-based serial monitor to send and receive data.

Now, you can easily add a web-based serial monitor to any of your projects using the WebSerial library.

Wrapping Up

In this quick tutorial, you learned how to create a web-based serial monitor. This is especially useful if your project is not connected to your computer via Serial communication and you still want to visualize debugging messages. The communication between the web-based serial monitor and the ESP32 uses WebSocket protocol.

We hope you find this tutorial useful. We have other web server tutorials you may like:

Learn more about the ESP32 with our resources:

Thank you for reading.



Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our newsletter!

34 thoughts on “ESP32 WebSerial: Web-based Remote Serial Monitor”

  1. Data on how to include WiFi.h incomplete as far as i see using VS platform. I copied the
    lib_deps = ESP Async WebServer as instructed to platform.ino

    ayushsharma82/WebSerial @ ^1.1.0
    but all the following includes
    #include <WiFi.h>
    #include <AsyncTCP.h>
    #include <ESPAsyncWebServer.h>
    #include <WebSerial.h>
    resulted in errors. Files not found!

    Reply
    • Hi.
      Those two lines are all you need.
      The WiFi library is included by default.
      The AsyncTCP is called by the ESPAsyncWebServer that is included in the lib_deps.
      The WebSerial is also included in the lib_deps.
      What is exactly the error that you get?
      Regards,
      Sara

      Reply
      • I moved the code to the Arduino esp 8266 IDE and it compiled with no error, but when I use the displayed IP on both an Android and PC browser I get refuse to connect. My router sees the devices IP. I will cut and paste the example again and see what happens. Where is the HTML of image located in library?

        I will go load back to VS and get the exact error later today.

        Reply
  2. Good evening Sara,

    Sorry to bother you but as this topic interests me a lot, I would love to put this great tutorial into practice.

    I just copy / paste the source code into my Arduino IDE, I installed the WebSerial then ESPAsyncWebServer and AsyncTCP libraries there as shown in the tutorial. I find them in the list of original and contributory libraries.

    I documented my username and password, restarted my computer but nothing helped. The response is always “Compilation error for ESP32 Dev Module board”.

    What is my problem?

    Reply
  3. My ESP32 boards (I have tried 4 from 2 different vendors) really struggle to connect to my network, though sometimes they will manage.

    In contrast, my ESP8266 boards connect easily. Both boards see the network with similar strength when I run a scan. I got the ESP8266 version of this project working immediately.

    I’m using Arduino, and I feel there’s a configuration problem somewhere. I think the hardware is ok (because of the scan) and the software sometimes (but rarely) works, so it’s not grossly wrong.

    Any ideas?

    Reply
  4. Not sure why just yet, but adding the WebSerial.h library into a dual-core sketch using the xTaskCreatePinnedToCore option (yes, I am using core0 for all my wifi related stuff) is throwing declaration issues when trying to compile. Deleting WebSerial.h restores the sketch. Again, not sure what’s going on yet…
    FYI.

    Reply
  5. Thanks Sara for your interest in my problem.
    Following is the full message received from the Arduino IDE.
    The part about using one of the two WiFi libraries usually doesn’t bother me.
    = = = = = = = = =
    C:\Users\Claude\Documents\Arduino\libraries\AsyncTCP-master\src\AsyncTCP.cpp: In function ‘bool _start_async_task()’:
    C:\Users\Claude\Documents\Arduino\libraries\AsyncTCP-master\src\AsyncTCP.cpp:221:141: error: ‘xTaskCreateUniversal’ was not declared in this scope
    xTaskCreateUniversal(_async_service_task, “async_tcp”, 8192 * 2, NULL, 3, &_async_service_task_handle, CONFIG_ASYNC_TCP_RUNNING_CORE);
    ^
    Plusieurs bibliothèque trouvées pour “WiFi.h”
    Utilisé : C:\Users\Claude\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.1\libraries\WiFi
    Non utilisé : C:\Program Files (x86)\Arduino\libraries\WiFi
    exit status 1
    Erreur de compilation pour la carte ESP32 Dev Module

    Reply
  6. I finally solved my problem by upgrading the ESP32 board manager of my Arduino IDE :
    1.0.1 -> 1.0.6

    Good day to everyone

    Reply
  7. Hello! I bought the book, and learned quite a lot.
    Would it be possible to show us how to do something like this serial monitor library in more of a home-made style so that we can modify it and add to it?
    The library works fine but I’d like to do more on the web page than just this one function.
    Rhanks
    Doug

    Reply
    • Hi.
      To do that, you would have to create your own WebSerial.
      You can do that using WebSocket protocol with the ESP32.
      You would need to set up an input field where the user enters messages to send to the ESP32, and some HTML text that would be replaced with the messages sent from the ESP32.
      I don’t think you can modify the web page using the library. But, you can ask here: https://github.com/ayushsharma82/WebSerial/issues
      Regards,
      Sara

      Reply
      • Hi,
        Yes, I looked at the webserial library with the hope of learning more about its implementation. Unfortunately, it is pretty much obscured, which is not what I’m used to for Arduino-style libraries. Perhaps it is because there is a commercial cousin of the library available?
        I will review the websocket section of the book and have a go. Any more hints about generating the html output would be much appreciated!
        Doug

        Reply
  8. Hello there,

    It’s amazing what I’ve learned the last few weeks, thanks to your tutorials!
    Thanks again!

    Thanks for mentioning how to implement this Webserial library.
    I tried combining it with a static IP adress, but that didn’t work.
    Probably something went wrong on my side, but if other people have the same problem let me know. Or even better a solution:)

    Kind Regards,
    Michiel

    Reply
      • In file included from E:\Arduino\libraries\AsyncTCP\src\AsyncTCP.cpp:24:0:
        E:\Arduino\libraries\AsyncTCP\src\AsyncTCP.h:53:8: note: forward declaration of ‘struct ip_addr’
        struct ip_addr;
        ^
        E:\Arduino\libraries\AsyncTCP\src\AsyncTCP.cpp:982:33: error: invalid use of incomplete type ‘struct ip_addr’
        connect(IPAddress(ipaddr->u_addr.ip4.addr), _connect_port);
        ^
        In file included from E:\Arduino\libraries\AsyncTCP\src\AsyncTCP.cpp:24:0:
        E:\Arduino\libraries\AsyncTCP\src\AsyncTCP.h:53:8: note: forward declaration of ‘struct ip_addr’
        struct ip_addr;
        exit status 1
        An error occurred when compiling for the development board NodeMCU-32S.

        Reply
        • Hi.
          I never faced that issue.
          I suggest updating your ESP32 board’s installation as well as installing all the libraries again.
          Regards,
          Sara

          Reply
  9. Thanks for this tutorial.
    It works well and most important thing, you make it easy to understand.

    One thing, if you do send a message every 2 seconds is it normal the ESP32 to get warm? I think because to use a lot the WiFi communications. Or is it normal?

    Thank you :-).

    Reply

Leave a Reply to Bernard Barrois Cancel reply

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.