ESP application layer may offer simplified a vast number of services as known from the PC world and the Internet yet. The limitation is the RAM size, storage, number of concurrent connections and limited CPU capabilities. Response routines should be kept simple as ESP8266 is single-threaded and uses timers and interrupt system to handle WiFi tasks in the background.
Below we present a number of samples, introducing programming of the various scenarios with ESP8266.
ESP8266 Web Server Sample
This example can be compiled in Arduino IDE. It allows through the website to change the output state of PIN 4 and PIN 5 [1]. We can connect LED to these pins and change its state remotely using a web browser. Before compiling this example it is necessary to change these two lines, to enable the module to connect to the WIFI network:
const char* ssid = ".. put here your own SSID name ..."; const char* password = ".. put here your SSID password.. ";
Now please check in the serial console the ESp8266 IP number and connect with any browser to address: http://esp8266_ipnumber
// Load Wi-Fi library #include <ESP8266WiFi.h> // Replace with your network credentials const char* ssid = ".. put here your own SSID name ..."; const char* password = ".. put here your SSID password.. "; // Set web server port number to 80 WiFiServer server(80); // Variable to store the HTTP request String header; // Auxiliar variables to store the current output state String gpio5State = "off"; String gpio4State = "off"; // Assign output variables to GPIO pins const int gpiopin5 = 5; const int gpiopin4 = 4; void setup() { Serial.begin(115200); // Initialize the output variables as outputs pinMode(gpiopin5, OUTPUT); pinMode(gpiopin4, OUTPUT); // Set outputs to LOW digitalWrite(gpiopin5, LOW); digitalWrite(gpiopin4, LOW); // 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("ESP8266 IP address: "); Serial.println(WiFi.localIP()); server.begin(); } void loop(){ WiFiClient client = server.available(); // Listen for incoming clients if (client) { // If a new client connects, Serial.println("New Client."); // print a message out in the serial port String currentLine = ""; // make a String to hold incoming data while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor header += c; if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code // (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, // then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println("Connection: close"); client.println(); // turns the GPIOs on and off if (header.indexOf("GET /5/on") >= 0) { Serial.println("GPIO 5 on"); gpio5State = "on"; digitalWrite(gpiopin5, HIGH); } else if (header.indexOf("GET /5/off") >= 0) { Serial.println("GPIO 5 off"); gpio5State = "off"; digitalWrite(gpiopin5, LOW); } else if (header.indexOf("GET /4/on") >= 0) { Serial.println("GPIO 4 on"); gpio4State = "on"; digitalWrite(gpiopin4, HIGH); } else if (header.indexOf("GET /4/off") >= 0) { Serial.println("GPIO 4 off"); gpio4State = "off"; digitalWrite(gpiopin4, LOW); } // Display the HTML web page client.println("<!DOCTYPE html><html>"); client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"); client.println("<link rel=\"icon\" href=\"data:,\">"); // CSS to style the on/off buttons // Feel free to change the background-color and // font-size attributes to fit your preferences client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}"); client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;"); client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}"); client.println(".button2 {background-color: #77878A;}</style></head>"); // Web Page Heading client.println("<body><h1>ESP8266 Web Server</h1>"); // Display current state, and ON/OFF buttons for GPIO 5 client.println("<p>GPIO 5 - State " + gpio5State + "</p>"); // If the output5State is off, it displays the ON button if (gpio5State=="off") { client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>"); } else { client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>"); } // Display current state, and ON/OFF buttons for GPIO 4 client.println("<p>GPIO 4 - State " + gpio4State + "</p>"); // If the output4State is off, it displays the ON button if (gpio4State=="off") { client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>"); } else { client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>"); } client.println("</body></html>"); // The HTTP response ends with another blank line client.println(); // Break out of the while loop break; } else { // if you got a newline, then clear currentLine currentLine = ""; } } else if (c != '\r') { // if you got anything // else but a carriage return character, currentLine += c; // add it to the end of the currentLine } } } // Clear the header variable header = ""; // Close the connection client.stop(); Serial.println("Client disconnected."); Serial.println(""); } }
After connecting with web browser to ESP8266 there will be such web page (figure 1), and we can change the input status of PIN 4 and 5 simply by pressing the appropriate button
ESP32 “Hello World”
This is simple program printing “Hello World” and it is written in Espressif IoT Development Framework
#include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_spi_flash.h" void app_main() { printf("Hello world!\n"); /* Print chip information */ esp_chip_info_t chip_info; esp_chip_info(&chip_info); printf("This is ESP32 chip with %d CPU cores, WiFi%s%s, ", chip_info.cores, (chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "", (chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : ""); printf("silicon revision %d, ", chip_info.revision); printf("%dMB %s flash\n", spi_flash_get_chip_size() / (1024 * 1024), (chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external"); for (int i = 10; i >= 0; i--) { printf("Restarting in %d seconds...\n", i); vTaskDelay(1000 / portTICK_PERIOD_MS); } printf("Restarting now.\n"); fflush(stdout); esp_restart(); }
ESP32 Web Server
This example of ESP32 programming in Arduino and shows how to implement simple www server.
First we do a little initialisation
//################# LIBRARIES ################ #include <WiFi.h> #include <ESP32WebServer.h> #include <WiFiClient.h> //################ VARIABLES ################ String webpage = ""; // General purpose variable to hold HTML code const char* ssid = "ssdi"; // WiFi SSID const char* password = "password"; // WiFi Password int status = WL_IDLE_STATUS; int curr_index; String SensorStatusBME; // Site's Main Title String siteheading = "ESP32 Webserver"; // Sub-heading for all pages String subheading = "Sensor Readings"; // Appears on the tabe of a Web Browser String sitetitle = "ESP32 Webserver"; // A foot note e.g. "My Web Site" String yourfootnote = "ESP32 Webserver Demonstration"; // Version of your Website String siteversion = "v1.0";
Then we must implement the main www server activities. Mind, to access the server from outside of your network WiFi (LAN) e.g. on port 80 when in NAT mode, add a rule on your router that forwards a connection request to http://your_network_WAN_address:80 to http://your_network_LAN_address:80 and then you can access your ESP server from virtually anywhere on the Internet.
ESP32WebServer server(80); void setup() { Serial.begin(115200); // initialize serial communications curr_index = 1; time_to_measure = millis(); StartWiFi(ssid, password); StartTime(); //---------------------------------------------------------------------- Serial.println("To connect, uss: http://" + WiFi.localIP().toString() + "/"); // If the user types at their browser // http://192.168.0.100/ control is passed here and then // to user_input, you get values for your program... server.on("/", homepage); // If the user types at their browser // http://192.168.0.100/homepage or via menu control // is passed here and then to the homepage, etc server.on("/homepage", homepage); // If the user types something that is not supported, say so server.onNotFound(handleNotFound); // Start the webserver server.begin(); Serial.println(F("Webserver started...")); } void handleNotFound() { String message = "The request entered could not be found, please try again with a different option\n"; server.send(404, "text/plain", message); } void homepage() { append_HTML_header(); webpage += "<P class='style2'>This is the server home page</p><br>"; webpage += "<p class='style2'>"; webpage += "This is sample webpage"; webpage += "</p><br>"; webpage += "<p>This page was displayed on : " + GetTime() + " Hr</p>"; String Uptime = (String(millis() / 1000 / 60 / 60)) + ":"; Uptime += (((millis() / 1000 / 60 % 60) < 10) ? "0" + String(millis() / 1000 / 60 % 60) : String(millis() / 1000 / 60 % 60)) + ":"; Uptime += ((millis() / 1000 % 60) < 10) ? "0" + String(millis() / 1000 % 60) : String(millis() / 1000 % 60); webpage += "<p>Uptime: " + Uptime + "</p>"; append_HTML_footer(); server.send(200, "text/html", webpage); } void page1() { append_HTML_header(); webpage += "<H3>This is the server Page-1</H3>"; webpage += "<P class='style2'>This is the server home page</p>"; webpage += "<p class='style2'>"; webpage += "This is sample 1 page"; webpage += "</p>"; append_HTML_footer(); server.send(200, "text/html", webpage); }
next we must start Wifi :
void StartWiFi(const char* ssid, const char* password) { int connAttempts = 0; Serial.print(F("\r\nConnecting to: ")); Serial.println(String(ssid)); WiFi.begin(ssid, password); status = WiFi.status(); while (status != WL_CONNECTED ) { Serial.print("."); // wait 10 second for re-trying delay(10000); status = WiFi.status(); Serial.println(status); if (connAttempts > 5) { Serial.println("Failed to connect to WiFi"); // printWiFiStatus(); } connAttempts++; } Serial.print(F("WiFi connected at: ")); Serial.println(WiFi.localIP()); }
and last step is to implement main loop function:
void loop() { delay( 2000 ); server.handleClient(); }