ESP32 WebSerial

Hello,

I'd like to set up a little web server where I show the content of what's printed to Serial, for diagnostic reasons (so that you don't have to connect via USB all the time).

I've found the WebSerial and WebSerialLite libraries but it currently looks like I'd have to do the prints twice.. once for the Serial and once for the WebSerial.

Is there any way I could just route the Serial output directly to the WebSerial?

Using IDE 2.3.2 and Arduino Nano ESP32 2.0.13 (ESP32-S3 Rev 0)

Thank you so far!

Why not write a function that takes what you want to print and outputs it to both Serial and WebSerial ?

That way you only have to call your function when you want to output something

1 Like

Both functions use Print.cpp but I wouldn't know where and how to start this function.

Since I use variants of the print function like println and printf..

image

Would I just need to setup a size_t variable?

The size_t variable is what the function returns, which is the number of bytes printed, if this is of interest, which I suspect that it isn't

The function could be as simple as this

void myPrint(int data)
{
    WebSerial.print(data);
    Serial.print(data);
}

Call it like this

myPrint(aVar);   

where aVar is an int

If you want different versions that print different data types then add them

void myPrint(char * data)
{
    WebSerial.print(data);
    Serial.print(data);
}

The compiler will use the appropriate version of the function based on data type. This is known as function overloading

Put all of your versions of your print function in a .h file and #include it in your sketch or better still create a library and call it from any sketch where it is #included

Better to let the compiler do the work for you and put a template in the .h file:

template <typename T, class... Others>
void myPrint(T data, const Others &... others) {
  WebSerial.print(data, others...);
  Serial.print(data, others...);
}

template <typename T, class... Others>
void myPrintln(T data, const Others &... others) {
  WebSerial.println(data, others...);
  Serial.println(data, others...);
}

Whilst I agree that it is better, it is also more obscure if you don't understand templates