Baxter Builds

How to Improve Your ESP32 Web Pages

March 22, 2023 by Baxter

the web page that the code on this page makes

Lets say you have just created a web page for your ESP32 and it does not really look right to you, but your not sure how to make it look better.

This may or may not happen to you, but it definitely has happened to me, so today I will explain some of the tricks I use to make my pages look and work better.

An Example

Instead of just talking about how you can improve you web page. lets work through an example.

Here is some simple HTML that I made for the last tutorial.

<!DOCTYPE HTML>
<html>
 <body>
  <form>
   <label for = "input">Message</label>
   <input type = "text" id = "input"  name = "message">
   <input type = "submit" value = "Send">
  </form>
 </body>
</html>

And here is what running that HTML looks like.

super simple page with label, text box and button.

And I will admit it, we are starting from the absolute bottom of the barrel, but lets see where we can take this page.

POST vs GET

The purpose of the above code is that you can write some text and then send it to the server. If you actually ran it, you would notice to behaviors that are not always desirable.

First, you can always see the last message sent in the URL. If you look at the picture above you can see that I sent the message “hello there” because you can see those words in the URL.

Well actually, URLs format the data slightly so “hello there” becomes “hello+there“, but you get the idea.

The second problem is that every time I send something to the server, the page reloads. This is inefficient and can sometimes be problematic.

All of these problems occur, because our page is using the HTTP GET method. If we were to use the HTTP POST method instead, we could remove all these problems, so lets update the example page to use POST.

<!DOCTYPE HTML>
<html>
 <body>
  <form method = "POST">
   <label for = "input">Message</label>
   <input type = "text" id = "input"  name = "message">
   <input type = "submit" value = "Send">
  </form>
 </body>
</html>

The only thing that has changed is line 4, were we specifically tell the form to use the POST method.

You will also need to update the ESP32 code, so it can handle POST requests correctly. Here is a standard function, that you might normally use.

void page(){
 Serial.println("Client connected");
  if(server.hasArg("message")){
   Serial.println(server.arg("message"));
  }
 server.send(200,"text/html",WebPageCode);
}

And here is how you upgrade it to handle POST requests.

void page() {
  if (server.method() == HTTP_POST) {
    Serial.println("Client connected with post");
    if (server.hasArg("message")) {
      Serial.println(server.arg("message"));
    }
    server.send(204, "text/html", "");
  } else {
    Serial.println("Client connected");
    server.send(200, "text/html", PAGE);
  }
}

The above code should be pretty self explanatory, except line 7 which sends a 204 with blank text “”.

Servers have to send back data when a page makes a request or the page will crash. Unfortunatly if you send a message to a page it will reload the page with the new message.

Sending a 204 is a way to send a message that keeps the page from crashing, but at the same time does not reload the page.

MDNS

Typing in a long IP address every time you want to access you board is a pain, but there is a way round this.

With the magic of MDNS, you can use some text like CoolName.local instead of your IP address, and even cooler, it only takes two lines of code to turn MDNS on.

In your project you start by including the MDNS library. It should already be installed by default.

#include <ESPmDNS.h>

Then in the setup function, you run this.

MDNS.begin("myserver");

And of course you can replace myserver with any name you want with in reason (no spaces, no slashes, jada jada ja).

Then you can use WhatEverYouNamedYouBoard + .local instead of you board’s IP address.

I would highly suggest using MDNS in your projects, because it is so simple to use, and dramatically increases the quality of your page.

Styling Your Page

Up to this point we have talked about some of the small things you can do to make your web page look and work better, but so far we have neglected one of the most important things you can do: styling.

Just a quick note, styling is done with CSS. This post is not intended to teach you CSS, the point of this section is to give you a small list of things you need to be able to do in CSS, and point out some of the best sites to learn them from.

CSS controls a lot of your page’s settings, when you are getting started the two most important things you will want to learn are controlling how objects look, and where there get placed on the screen.

for controlling how objects look, I would look into CSS:

  • background-color
  • border
  • font-family

and for positioning your object you will want to learn:

  • margin
  • padding
  • flex

You might have heard of margin and padding before, but you probably have never heard about flex.

Flex

Flex is one of CSS’s layouts. There are other options you can choose from, but if you are just learning CSS, flex is a good one, because it’s very powerful and not terribly complicated. By far, the best site I have see that explains the flex layout is CSS Tricks.

For the rest of the CSS, I suggested you learn from W3S which is a good place to start and MDN Web Docs which is good if you want a lot of detail.

Grouping

When ever you have a bunch of items that work together on your screen, it’s best if you visually group them together. Here is how you can do that with a div.

<!DOCTYPE HTML>
<html>
 <body>
  <div id = "group">
   <form method = "POST">
    <label for = "input">Message</label>
    <input type = "text" id = "input"  name = "message">
    <input type = "submit" value = "Send">
   </form>
  </div> 
 </body>
</html>

As you can see, we start by putting every thing we want to group together inside of a <div>. We also give the <div> an id, so we can style it later.

<!DOCTYPE HTML>
<html>
 <body>
  <div id = "group">
   <form method = "POST">
    <label for = "input">Message</label>
    <input type = "text" id = "input"  name = "message">
    <input type = "submit" value = "Send">
   </form>
  </div> 
  <style>
      #group{
        background-color: #e2e2e2;
        border: 1px solid black;
        padding:10px;
        display: inline-block;
      }
  </style>
 </body>
</html>

Then we add an extra style. Here is how that works.

The first thing we do is create a rule targeting the <div> with id group.

#group{
  /* styles go here*/
}

Next we set the background color to gray and create a black border around our <div>.

#group{
  background-color: #e2e2e2;
  border: 1px solid black;
}

If you ran the code at this point, it would look like this.

Label, text box, and button, all inside of border that fills width of screen.

To fix the fact that the border runs into the button and the text box, we will add some padding and to stop the <div> from going way past the button we will make the <div> an inline-block.

#group{
  background-color: #e2e2e2;
  border: 1px solid black;
  padding:10px;
  display: inline-block;
}

here is what the result looks like.

Label, text box, and button, all inside of border with gray background

Don’t Reinvent the Wheel

This is probably the most important advice on this page. Before you start creating your web page, go look at other people’s web pages that do something similar to what you want, and study there pages to see how you could design your own.

This should go without saying, but First only imitate people you want to be like. If you want you web page to look good, make sure to look at high quality web pages, and second make the page your own. There is a big difference between getting some ideas of how to create your page, and just cloning the page.

Here is the complete rehaul of the code we started with.

I updated it from GET to POST, grouped everything together, and took inspiration from a similar web page to create it.

<!DOCTYPE HTML>
<html>
 <body>
 <div id="content">
  <form method = "post">
   <label for = "input">Message</label>
   <input type = "text" id = "input"  name = "message">
   <input type = "submit" id = "button" value = "Send">
  </form>
  </div>
  <style>
   html{
      height:auto;    
      background-color: #dee2de;
   }
      
   body{   
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-100%);
   }
  
   #content{
      background-color: white;
      border-radius: 6px;
      padding: 10px;
      font-family: arial, sans-serf;
      border: 1px solid black;
   }
  
   #button{
      background-color: #3dafb9;
      border: 1px solid transparent;
      border-radius: 2px;
   }
  
  </style>
 </body>
</html>

If you are interest in a full Arduino sketch or how the original HTML code works, you should check out Creating a ESP32 Web Server with Text Input.

Filed Under: ESP32 Web Page

Creating a ESP32 Web Server with Text Input

March 16, 2023 by Baxter

Simple web page with text box and send button

Being able to send text to your board from a web page is extremely useful. With it, you could create a chat server, simple command line, or any number of other cool projects, so today I will show you a simple way to create a web page with text input.

The Path to Victory

Before we go any further its important to quickly explain, how we are going to reach our goal.

We will start by create a simple HTML web page, and I do mean simple, it is only ten lines long.

Even so I do hope you understand the basics of HTML like what a tag is. If you are a little rusty on how HTML works, there is a ton of great web pages out there that explain HTML. I find a lot of my information from W3S html.

Then we are going to create an ESP32 program to host that page and read any message the page sends out.

The HTML page

Here is the code that we are going to talk about.

<!DOCTYPE HTML>
<html>
 <body>
  <form>
   <label for = "input">Message</label>
   <input type = "text" id = "input"  name = "message">
   <input type = "submit" value = "Send">
  </form>
 </body>
</html>

Now lets look at how it works.

<!DOCTYPE HTML>

We start all HTML files with the above tag. It is always put at the beginning of your HTML file, and its job is to make sure the browser uses the correct version of HTML to run your code.

Next we have the <html> tags.

<!DOCTYPE HTML>
<html>

</html>

All of the rest of our HTML code needs to go between the start <html> tag and the end </html> tag. Don’t forget the / on the end tag.

The next tag we use is the <body> tag.

<!DOCTYPE HTML>
<html>
 <body>

 </body>
</html>

Anything that is seen on your web page like images, text, buttons, etc. needs to go between the start <body> tag and the end </body> tag.

Now we have reached something that is a little more interesting, the <form> tag.

<!DOCTYPE HTML>
<html>
 <body>
  <form>

  </form>
 </body>
</html>

Forms are designed, so that you give them a bunch of inputs, like text areas and checkboxes, and if you press a special button on the screen the form sends the current value of all its inputs to the server, in are case that would be an ESP32.

We will start by putting a text box in our form.

<!DOCTYPE HTML>
<html>
 <body>
  <form>

   <input type = "text" id = "input"  name = "message">

  </form>
 </body>
</html>

As you can see to create our text box, we use the <input> tag. One thing that is a little unique about the <input> tag is that it does not have an end </input> tag.

We have to pass three attributes to the <input> tag: type, id, name.

We are setting the type of our input to text, which makes it a single line text box, but there are several other options you can choose from.

The id attribute is used for a lot of things, but today we will use it to create a label, which we are going to talk about in just a second. For now, we will set id equal to “input“, but you can call it what ever you want.

Imagine for a moment that you have a form that has several text boxes, when you send the form to the server how will it now which message comes from which text box.

Well you give each text box a name, and when the server reads a message, it is also given the name of the text box that sent the message. In HTML, you give inputs names in this way name=”SomeName”.

HTML actually takes this a step further and says, if an input doesn’t have a name, it should not be sent to the server, so make sure you give all of your inputs names.

Labels

If we ran the code right now, all we would see on the screen is a little text box, but that is not very user friendly. You almost always want a label next to your inputs, that explains what they are for, so lets create one.

<!DOCTYPE HTML>
<html>
 <body>
  <form>

   <label for = "input">Message</label>
   <input type = "text" id = "input"  name = "message">

  </form>
 </body>
</html>

Thankfully labels are pretty simple. You put the label’s text in between the start and end <label> tag.

And what makes labels cool is that you can connect them to your inputs. For example if you connect a label to a button, and then you click the label the button will be clicked as well.

You connect a label to an input with the for attribute. All you have to do is set the for attribute equal to the id of the input. We set the id of our text box to “input” earlier, so we connect our label to the textbox with for = “input”.

The Submit Button

I said earlier that there is supposed to be a button that when you click it, the form gets upload to the ESP32. Well we still need to create that button.

Fortunately it is simple. You create a new input with type = “submit” and set the value of it to what ever you want the text of the button to be.

<!DOCTYPE HTML>
<html>
 <body>
  <form>
   <label for = "input">Message</label>
   <input type = "text" id = "input"  name = "message">
   <input type = "submit" value = "Send">
  </form>
 </body>
</html>

The ESP32 Code

Ok, you have seen all the HTML code, now we will look at the ESP32 code. We are mainly going to focus on the part of the code that process the messages set by the page, but we will briefly skim through the rest of the code as well.

Here is the complete code.

#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>

WebServer server(80);



String PAGE = R"rrrrr(
<!DOCTYPE HTML>
<html>
 <body>
  <form>
   <label for = "input">Message</label>
   <input type = "text" id = "input"  name = "message">
   <input type = "submit" value = "Send">
  </form>
 </body>
</html>
)rrrrr";



void page(){
  if(server.hasArg("message")){
    Serial.println(server.arg("message"));
  }
  server.send(200,"text/html",PAGE);
}


void setup() {
  Serial.begin(115200);
  WiFi.begin("Your Wifi Name", "Your Password");
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print('.');
  }
  Serial.println();
  MDNS.begin("myserver");

  server.on("/",page);
  server.begin();
}

void loop() {
  server.handleClient();
  delay(5);
}

Now lets go through the code.

#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>

We start by including the three libraries needed to make our webpage.

WebServer server(80);

Then we create a web server on port 80.

String PAGE = R"rrrrr(
<!DOCTYPE HTML>
<html>
 <body>
  <form>
   <label for = "input">Message</label>
   <input type = "text" id = "input"  name = "message">
   <input type = "submit" value = "Send">
  </form>
 </body>
</html>
)rrrrr";

This is the HTML code we create earlier. You can write a string that covers multiple line if you start and end it with R”some_identifier( and )some_identifier” which is what the code above does.

void page(){
  if(server.hasArg("message")){
    Serial.println(server.arg("message"));
  }
  server.send(200,"text/html",PAGE);
}

This is where all the magic happens. The function above is called whenever someone tries to access the ESP32 and it does three things.

First, it checks if the server has an argument called message. In the HTML we named the textbox message, so what this line of code is really doing is checking, if the textbox has sent anything to the ESP32.

Secondly, if it has sent something, we print the message out to the Serial Monitor.

And lastly, we send the HTML code back to the browser, so that it can show our webpage.

void setup() {
  Serial.begin(115200);
  WiFi.begin("Your Wifi Name", "Your Password");
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print('.');
  }
  Serial.println();
  MDNS.begin("myserver");

  server.on("/",page);
  server.begin();
}

Above is the setup function, its job is to connect to WIFI and start the server along with a few other things.

make sure to change the line that says “Your Wifi Name” and “Your Password” to your WIFI network and its password.

WiFi.begin("Your Wifi Name", "Your Password");

You might also be interested in this line.

 MDNS.begin("myserver");

It allows you to connect to your ESP32 with the name myserver.local instead of having to use the ESP32 IP address. You can change the myserver part to what ever you want.

void loop() {
  server.handleClient();
  delay(5);
}

And of course we run the above code to make sure the webpage responds to anyone that connects to it.

Simple web page with text box and send button

Using the Code

There are two ways you can run the code on this page.

On Your Computer

Whenever you actually create you own webpage, which I highly suggest you do, its best if you write and test the code on your computer. If you want to play around with running the HTML just on your computer going to The Tools Needed to Write HTML for Microcontrollers will explain how its done.

On the ESP32

But honestly you probably just want to run the code. Take the complete arduino code( the one with numbers next to the code) and like I said earlier update the WIFI name and password.

Then you will need to upload the code to your ESP32.

Make sure you computer is on the same network that you told the ESP32 to connect to, and then type in your browser “myserver.local“. If you get an error message, it probably just means that your board has not had a enough time to connect to the internet. All you have is wait a second or two and restart the page.

Once the page loads type what ever you want into the text box, and then hit enter or click the send button.

Serial Monitor with lots of text that ends with "hello there" the message set from the client

If you look at the Serial Monitor for your ESP32 you should see what you typed in the box printed to the screen.

Filed Under: ESP32 Web Page

Learning JavaScript For the ESP32

March 13, 2023 by Baxter

To create a web page for your ESP32, you need to know HTML, CSS, and JavaScript, and while I can’t help you much with HTML and CSS, JavaScript is a different story.

JavaScript is very similar to C++ (the Arduino IDE language) and if you already know C++ there is a faster way to learn it.

Instead of learning the entire language from scratch, you can learn the major differences between C++ and JavaScript. Which should take much less time then reading an entire beginners guide to JavaScript.

Where To Put Your Code

It is pretty well know that JavaScript is part of how web pages are made, but a little less know is how you actual put it in the page. There is two main ways and I hope you understand a little HTML other wise this will probably be complete gibberish.

The first place is in-between the HTML script tags, which looks something like this.

<script>

// Your code goes here 

</script>

Or you can create a file, lets say you called it mycode.js, and then include it with the script tags.

<script src="mycode.js"></script>

If you use the file method make sure to put your js file in the same folder as your HTML code.

Void Loop and Void Setup

You should be familiar with the idea that Arduino boards have a setup and loop function and they are where you start your code from. They usually look something like this.

void setup(){
 //some setup code
}

void loop(){
  //some loop code
}

JavaScript does not have ether of these functions, instead you write code where ever you want. Think of it like the entire program is inside the setup function.

Here is how you would write the code above in JavaScript.


//some setup code 

while(true){

//some loop code

}

Variables

Arduino has a lot of different ways you can declare a variable. You have int, String, char, byte, bool, etc. JavaScript is different in that it only has four ways you create variables.

Var

The var keyword replaces all of the Arduino variable types. Lets run through a few examples.

This is how you create a number variable in C++.

int number = 123;

And this is how its done with JS (JavaScript).

var number = 123;

Here is a letter variable in C++.

char letter = 'L';

And here is how its done with JS.

var letter = 'L';

You should see the pattern, you just replace any keyword you would normally use like int with the var keyword.

Const

The Const keyword is used to create a variable that can be read but never changed.

Here is how you use it.

const number = 123;

Here is the C++ equivalent.

const int number = 123;

Let

The let keyword is used to make your programs slightly more memory efficient.

If you used the var keyword to create a variable inside of an if statement, you can still access the variable after the if statement has finished like in the code below.

if(true){
var myvar = 10;
}

alert(myvar); // totally allowed

But many times you don’t need that variable any more, and it is just waisting your memory.

The let keyword tells the computer to automatically delete the variable once the if statement is completed.

if(true){
let myvar = 10;
}

alert(myvar); // myvar no longer exists so it is undefined

In fact the let command works for any code inside of brackets {}, so it is also useful with loops.

Nothing

This is probably the weirdest of the bunch, but you are also allowed to create variables with out a keyword at all.

myvar = 10;

Functions

Functions are pretty much identical except the parts that use variables. It is easiest, if I show an example.

Here is a C++ function.

int add(int a,int b){
  return a + b;
}

And here is the same function in JS.

function add(a,b){
  return a + b;
}

The key things to notice is that all functions start with the word function and that the arguments for a function are simply a list of names and never have words like var or let with them.

Comparisons

In C++ comparisons are done with the ==, !=, >=, etc. In JavaScript you need to add an extra = to the end of the == and != commands. As usual here is an example.

C++ code.

int value = 200;

if(value >= 1000){
  Serial.println("High");
}else if(value == 0){
  Serial.println("Zero");
}else{
  Serial.println("In-between");
}

Add here is the same thing in JavaScript.

var value = 200;

if(value >= 1000){
  alert("High");
}else if(value === 0){
  alert("Zero");
}else{
  alert("In-between");
}

Arrays

JavaScript and C++ arrays are actually very different behind the scenes. To start here is a C++ array.

int numbers[10] = {0,10,20,30,40,50,60,70,80,90};

Serial.println(numbers[3]);

And here is the same array but in JS.

var numbers = [0,10,20,30,40,50,60,70,80,90];

alert(numbers[3]);

While those two arrays may look similar, there are actually two main differences, JavaScript arrays can change in size which is why, when you create a new array, you don’t have to specify the size.

JavaScript arrays can also contain multiple types of data at the same time, look at this array.

var mixedArray = [10,"some text",true,"and some more"];

Strings

Arduino boards have two types of strings used with them C style strings, and the String library. JavaScript strings are closest to the String library.

Here is a simple example of them in action.

var string = "hello world";
string = string + "!" + 1;

alert(string); 

Input and Output

When you are writing code, it is always nice, if you have some simple way to send debug information out and receive commands in.

You can get basic input and output by using the alert and prompt commands.

alert("some message");

var answer = prompt("a question");

The alert command creates a popup box with the message you give it and The prompt command will create a popup box that asks a question and below that there is a little text area that you can type your answer in. Your answer will then be returned by the prompt command.

Math

Thankfully math is pretty much the same in both languages. You can use the +, -, *, / or the +=, -=, etc. The only thing you will need to keep in mind is that JavaScript will automatically turn strings into numbers, if the strings are in a math equation.

var result = "100" - 20;

The result of the above code will be 80. This rule is true for all operations except addition.

var result = "100" + 20;

Instead a equaling 120, the code above actually results in “10020”. With addition, the number will be turned to a string, and then the two strings will be added together.

Loops

JavaScript loops are the same as C++.

for(var i = 0; i < 100;i++){
//do something
}

while(true){
//do something
}

Obliviously I can’t explain the entire JavaScript language in a single post, but by now you should have a basic understanding of how it works.

Filed Under: ESP32 Web Page

The Tools Needed to Write HTML for Microcontrollers

March 10, 2023 by Baxter

Web page with text Hello World

Have you ever wanted to create a web page for an esp32, and I don’t mean just have you esp32 host a web page, I mean have you ever wanted to write your own web page from scratch.

The fact that your here, probably means you do, and just like you need a saw to cut wood, there are tools you need to have to write a web page. Today we are going to look at those tools.

What are Web Pages Made of

I am glad you asked. It turns out that web pages are made of three languages: HTML, JavaScript, and CSS.

HTML

HTML is like the king of the three. While it is totally possible to create a web page without JavaScript or CSS, HTML is just required. The good news is that HTML is pretty simple.

JavaScript

JavaScript is what you would normally have to worry about. It’s a full on coding language with lots and lost of powerful features, but you likely already have a huge head start. JavaScript is very similar to C++ (the Arduino IDE language) which means that if you can program an Arduino board, learning JavaScript should also be pretty simple.

CSS

CSS controls how your web page looks. It can put borders around images, change the background color of your website, set the font used, etc. Learning the basics is straight forward, though I will be honest and say that mastering it is a different story.

The Required Tools

To write in the above coding languages you need two things: A browser and a text editor.

The factor that you can see this web page means you probably have a browser and most computers have at least one text editor by default, so you already have every thing you need.

Some text editors for example Microsoft Word add extra information to the text so your can’t use them to write HTML,JavaScript, or CSS.

Notepad or Gedit are two good options to start with. You can also find editors specially designed for HTML, JavaScript, and CSS. I use notepad++, but at the end of the day chose what ever is most convenient for you.

Hidden Extensions

If you look around on you computer for a minute do any of the file names you see end with .png, .jpeg, .txt, etc. If you can not find any files that end with .something you probably have hidden extensions turned on.

If extensions are hidden, it will be really hard to create your code files correctly so you will probably want to turn off hidden extensions. Just search the internet for “disabling hidden extensions” and you will find a few good pages on how its done.

A Quick Example

You have all the tools you need, so lets create a simple web page.

Create a file on your computer and name it “mypage.html“.

Then open that file with your text editor and write the following “Hello World” and after that save the file and close the editor.

picture of notepad++ with file open that has the text Hello World

Then right click on that file, select the open with option and then select your browser(in my case chrome).

A new browser tab should open with the text “Hello World” on the page.

Web page with text Hello World

If you want a little more of a webpage, you might like this page: Creating a ESP32 Web Server with Text Input

Some Extras

While these are the basic tools need to create a web page, there are a few more you might be interested in.

WYSIWYG

While I highly suggest learning HTML, it can be a pain to write a ton of HTML code, even if you now how. If you are creating a bigger page, it’s often a good idea to find a WYSIWYG program. These types of programs allow you to create a web page by a drag and drop interface or something similar, and then it generates the HTML code for you.

You will still have to create the JavaScript code and you will probably need to go in and edit the HTML a bit, but they can speed up the process of creating a web page a lot.

HTML Compressors

HTML compressors remove any unneeded space in your code so it is as small as possible. Which really helps when you have to work with microcontrollers that don’t have a lot of memory available.

You should now have a pretty good setup to write your own web page code.

Filed Under: ESP32 Web Page

Recent Posts

  • How to Shorten Your Micropython LVGL Code
  • FreeRTOS Mutex Example
  • FreeRTOS Task Notification Example
  • FreeRTOS Queue Example
  • FreeRTOS Semaphore Example

Categories

  • Arduino
  • ESP32 Web Page
  • FreeRTOS
  • LEGO Technic
  • LEGO tips
  • LEGO war robots
  • Lego's
  • Legos
  • LEGOS-build your own
  • Micropython

Copyright © 2025 · Minimum Pro Theme on Genesis Framework · WordPress · Log in