Friday, January 7, 2022

ESP Webserver tutorial part 2 - button

For an index to all my stories click this line.

This is the second installment in a series about building a webpage in the Arduino language for the ESP8266 and the ESP32 to command appliences.

This time I am going to show you how to put a button on a web-page which you can click and that action will set a led on the ESP off your choice on or off.

This seems like old school and has been done numerous times before. However I am taking a different approach. One I have not seen being used before and which opens possibilities for more ways to process the data which we receive from a webpage. So stay with me and let's make a webpage with many different items in this series.

This weblog entry leans heavily on the previous story in this series. That story showed you how to build a web-server and send text messages to the ESP. We are going to use that same webserver here but now for buttons. So please read and study the previous article first. You can find it here: http://lucstechblog.blogspot.com/2019/07/esp-webserver-tutorial-part-1-textfields.html

The ESP8266 setup routine.

The setup routine is the same as the routine in the program from the first article. I just added two lines that make IO pin D5 available for attaching a led:


  pinMode(D5, OUTPUT);
  digitalWrite(D5,LOW);

The button routine.

As we use the same web-server from the previous article in this series as a framework we only have to alter a few parts in the program to bring a button to the webpage.
There are two entries in the software. First the HTML part:


  page += "<FORM action=\"/\" method=\"post\">";
  page += "<button type=\"submit\" name=\"button1ON\" id=\"button1ON\" value=\"but1ON\">Led 1 ON</button>";
  page += "</form>";

  page += "<FORM action=\"/\" method=\"post\">";
  page += "<button type=\"submit\" name=\"button1OFF\" id=\"button1OFF\" value=\"but1OFF\">Led 1 OFF</button>";
  page += "</form>";
  page += "<br>";
  page += "<br>";

For each button (the ON and the OFF button) we build a webform. The button type is submit which makes sure the value is send to the webserver. The ON button will send the command but1ON to the ESP8266 and the OFF button will send but1OFF.

And then the server has to react on what it receives from the web-page:


   if (server.hasArg("button1ON"))
      {
      buttonON = server.arg("button1ON");
      Serial.print("Thereceived button is:             ");
      Serial.println(buttonON);
      Serial.print("If it is an integer its value is:        ");
      Serial.println(buttonON.toInt());
      digitalWrite(D5, HIGH);
      } 

   if (server.hasArg("button1OFF"))
      {
      buttonOFF = server.arg("button1OFF");
      Serial.print("Thereceived button is:             ");
      Serial.println(buttonOFF);
      Serial.print("If it is an integer its value is:        ");
      Serial.println(buttonOFF.toInt());
      digitalWrite(D5, LOW);
      }  

As you can see the server receives a command from the webpage. That command will be but1ON or but1OFF. Actually nothing is done with this command besides displaying it on the Serial Monitor. This just shows you how to send a command from the webpage to the ESP8266. You can alter these commands to your own purposes.
What the routine does however is directly set the led which is attached to D5 ON or OFF depending on the received command.

The ESP8266 breadboard setup

The breadboard setup is as simple as it can be.




Just an ESP8266, a Wemos D1 mini, with a led attached through a 220 ohm delimiting resistor to D5.


The ESP32 breadboard setup

The ESP32 breadboard setup is equally simple.




I am using the ESP32 Devkit Board. These ESP32's do not fit on a breadboard. I therefore use 2 breadboards. From one of these I stripped the power rail as discussed in the story you can find here:
https://lucstechblog.blogspot.com/2018/08/breadboard-hack-for-esp32-and-esp8266.html

The led is attached to GPIO32 through a 220Ohm current delimiting resistor.

The complete program.

I will not go over the framework here as I did that already in the previous story. If you want to re-read that just click this link: http://lucstechblog.blogspot.com/2019/07/esp-webserver-tutorial-part-1-textfields.html


You do need to make some minor alterations for using the program with the ESP32 which will be described below the listing.



 // ======================================================
// Webserver program that sends button information
// to ESP8266 and puts a control led on the page
// ======================================================

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

// Your routers credentials
const char* ssid = "YOUR-ROUTERS-NAME";
const char* password = "PASSWORD";

// ==========================================
// initial variables
// ========================================== 

String buttonON;
String buttonOFF;



// =========================================
// Here is the HTML page
// =========================================
String getPage()
  {
  String page = "<!DOCTYPE HTML>";
  page += "<html>";
  page += "<head>";
  page += "<meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0 maximum-scale = 2.5, user-scalable=1\">";
  page += "<title>Luc's button demo</title>";
  page += "<body style='background-color:powderblue;'>"; 
  page += "</head>";
  page += "<body>";
  
  page += "<h1 style='color:red'>Luc's web-button for ESP8266</h1>";
  page += "<br>";
  page += "<br>";

  page += "<FORM action=\"/\" method=\"post\">";
  page += "<button type=\"submit\" name=\"button1ON\" id=\"button1ON\" value=\"but1ON\">Led 1 ON</button>";
  page += "</form>";

  page += "<FORM action=\"/\" method=\"post\">";
  page += "<button type=\"submit\" name=\"button1OFF\" id=\"button1OFF\" value=\"but1OFF\">Led 1 OFF</button>";
  page += "</form>";
  page += "<br>";
  page += "<br>";

  return page;
  }


// ==================================================
// Handle for page not found
// ==================================================
void handleNotFound()
{
  server.send(200, "text/html", getPage());
}


// ==================================================
// Handle submit form
// ==================================================
void handleSubmit()
{
  //Text to show
   
   if (server.hasArg("button1ON"))
      {
      buttonON = server.arg("button1ON");
      Serial.print("Thereceived button is:             ");
      Serial.println(buttonON);
      Serial.print("If it is an integer its value is:        ");
      Serial.println(buttonON.toInt());
      digitalWrite(D5, HIGH);
      } 

   if (server.hasArg("button1OFF"))
      {
      buttonOFF = server.arg("button1OFF");
      Serial.print("Thereceived button is:             ");
      Serial.println(buttonOFF);
      Serial.print("If it is an integer its value is:        ");
      Serial.println(buttonOFF.toInt());
      digitalWrite(D5, LOW);
      }      
     
  server.send(200, "text/html", getPage());       //Response to the HTTP request

}  


// ===================================================
// Handle root
// ===================================================
void handleRoot() 
{   
  if (server.args() ) 
    {
    handleSubmit();
    } 
  else 
    {
    server.send(200, "text/html", getPage());  
    }
}


// ===================================================
// Setup
// ===================================================
void setup()
{
  delay(1000);
  Serial.begin(115200);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid,password);
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);

  server.begin();
  delay(500);

  pinMode(D5, OUTPUT);
  digitalWrite(D5,LOW);
}


// ===================================================
// Loop
// ===================================================
void loop()
{  
  server.handleClient(); 
  delay(50);
}

The difference with the previous story was that in that story text was send from a textfield.  This version sends the data from a button. The details in sending the button data are described above.

The alterations for the ESP32

There are just some minimal alterations you should make for using this program with the ESP32.


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

WebServer server(80);

// Your routers credentials
const char* ssid = "YourRoutersName";
const char* password = "YourPassWord";

These are the first lines in the program being the lines that load and initialise the libraries. As you can see the changes are minimal.


  pinMode(32, OUTPUT);
  digitalWrite(32,LOW);

You also need to make some changes in the setup routine as the led is attached to GPIO32 as the breadboard setup showed you.

The last alterations you need to make in the  handleSubmit() routine.

digitalWrite(D5, HIGH);

Should be altered in:

digitalWrite(32, HIGH);

And

digitalWrite(D5, LOW);

Should be altered in:

digitalWrite(32, LOW);

The webpage



Here is how the webpage will look. Nothing to fancy. You could add some CSS code to make the buttons more attractive like having rounded corners and colors. I leave that up to you for now.


The difference with other programs.

Setting a button ON or OFF from a webpage has been done many times before. But there is a distinct difference here. Not only can we react immediately on the click on a button on the webpage by setting the led ON or OFF, we also receive a text which we can use and test on in other parts of the program. So we have more feedback as in other programs which do the same. And more feedback means more possibillities to act upon.

In the blind ???

The above featured program has a flaw. As we press the ON button or OFF button the led on the ESP8266 will react. However the website does not show us what was pressed. As long as we are near the ESP8266 we can check visually. However when you are using this program from a distant location you do not have a feedback. That is what we will tackle next time.


So make sure you understand what is happening in this program and make some alterations like extra headings and maybe a combination with buttons and a textfield like described last time. The better you understand all this the more attarctive your own websites will get. So get ready for the next step.


Till next time.
Have fun

Luc