[Arduino development] Lesson2 NodeMCU ESP8266 establishes a network server

1. Establish a network server for esp8266

Note: by default, our browser or mobile phone uses port 80 to access the server

#Include < ESP8266WiFi. H > / / this program uses the ESP8266WiFi library
#Include < esp8266wifimulti. H > / / esp8266wifimulti Library
#Include < esp8266webserver. H > / / esp8266webserver Library
 
ESP8266WiFiMulti wifiMulti;     // Create an esp8266wifi multi object whose name is' WiFi multi '
 
ESP8266WebServer esp8266_server(80);// Create an ESP8266WebServer object with the name esp8266_server
                                    // The number in parentheses is the port number of the network server in response to the http request
                                    // The standard http port number of the network server is 80, so 80 is used here
 
void setup(void){
  Serial.begin(9600);          // Start serial communication
 
  //Store WiFi name and WiFi password through addAp function
  wifiMulti.addAP("Duer", "duer123456");  
  wifiMulti.addAP("aaaa", "87654321"); 
  wifiMulti.addAP("bbbb", "13572468"); 
                                                // The WiFi information here is just an example. Please fill the WiFi information to be connected into the corresponding position when using.
                                                // In addition, only 3 WiFi information are stored here. You can store more WiFi information here.
 
  int i = 0;                                 
  while (wifiMulti.run() != WL_CONNECTED) {  // Through WiFi multi. Run (), nodemocu will be in the current
    delay(1000);                             // Search the WiFi stored by the addAP function in the environment. If multiple stored WiFi is found, nodemocu
    Serial.print(i++); Serial.print(' ');    // The WiFi signal with the strongest signal will be connected.
  }                                          // Once the WiFI connection is successful, WiFI multi. Run() will return "WL_CONNECTED". This too
                                             // Here, the while loop determines whether to jump out of the loop.
 
  // After the WiFi connection is successful, the connection success information will be output through the serial port monitor 
  Serial.println('\n');                     // After WiFi connection is successful
  Serial.print("Connected to ");            // Nodemocu will output through the serial port monitor.
  Serial.println(WiFi.SSID());              // WiFI name of the connection
  Serial.print("IP address:\t");            // as well as
  Serial.println(WiFi.localIP());           // IP address of nodemocu
  
//--------The "start network service function" program section begins-------- 
  esp8266_server.begin();                   
  esp8266_server.on("/", handleRoot);       	//  Access transfer processing
  esp8266_server.onNotFound(handleNotFound);    // If this page is not found in MCU    
//--------"Start network service function" program section ends--------
  Serial.println("HTTP esp8266_server started");//  Inform the user that the ESP8266 network service function has been started
}

void loop(void){
  esp8266_server.handleClient();     // Handling http server access
}

void handleRoot() {   //Processing access request for site root '/' 
  esp8266_server.send(200, "text/plain", "Hello from ESP8266");   // Nodemocu will call this function.
}
 
// Set the function 'handleNotFound' to handle 404 cases
void handleNotFound(){                                        // When the network resource requested by the browser cannot be found on the server,
  esp8266_server.send(404, "text/plain", "404: Not found");   // Nodemocu will call this function.
}
  • esp8266_server.on("/", handleRoot); When our browser accesses the home page, we use the handleroot function to provide the home page information

  • esp8266_server.onNotFound(handleNotFound); When the accessed page does not exist, call the handlenotfound function to handle the access

  • handleRoot function

    esp8266_server.send: send information using the web server object

    200: Send a status code to the browser, indicating that the request has been successfully received

    text/plain: the sender server will send a plain text (text: text, plain: plain, or html)

    "Hello from ESP8266": text information to be sent

  • handleClient(): handle the browser client and respond whenever there is a browser request

  1. Run and upload the code. The results are as follows

  1. Open page in browser

Return text information correctly

  1. If you enter a page that does not exist at all

Display non-existent information

2. Control the nodemocu development board through the network server

#Include < ESP8266WiFi. H > / / this program uses the ESP8266WiFi library
#Include < esp8266wifimulti. H > / / esp8266wifimulti Library
#Include < esp8266webserver. H > / / esp8266webserver Library
 
ESP8266WiFiMulti wifiMulti;     // Create an esp8266wifi multi object whose name is' WiFi multi '
 
ESP8266WebServer esp8266_server(80);// Create a web server object that is used to respond to HTTP requests. Listening port (80)
 
void setup(void){
  Serial.begin(9600);   // Start serial communication
 
  pinMode(D4, OUTPUT); //Set the built-in LED pin as the output mode to control the LED
  
  //Store WiFi name and WiFi password through addAp function
  wifiMulti.addAP("Duer", "duer123456");  // These three statements record three different WiFi network information by calling the function addAP.
//  wifiMulti.addAP("CMCC-yLaQ", "1123456"); //  These three WiFi network names and passwords
//  wifiMulti.addAP("taichi-maker3", "13572468");
                                                // The WiFi information here is just an example. Please fill the WiFi information to be connected into the corresponding position when using.
                                                // In addition, only 3 WiFi information are stored here. You can store more WiFi information here.
  Serial.println("on connection Wifi,One moment please:");  
  int i = 0;                                 
  while (wifiMulti.run() != WL_CONNECTED) {  // WiFi multi. Run () here is the focus. Through WiFi multi. Run (), nodemocu will be in the current
    delay(1000);                             // Search the WiFi stored by the addAP function in the environment. If multiple stored WiFi is found, nodemocu
    Serial.print(i++); Serial.print(' ');    // The WiFi signal with the strongest signal will be connected.
  }                                          // Once the WiFI connection is successful, WiFI multi. Run() will return "WL_CONNECTED". This too
                                             // Here, the while loop determines whether to jump out of the loop.
  
  // After the WiFi connection is successful, the connection success information will be output through the serial port monitor 
  Serial.println('\n');
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());              // Output the WiFi name of the connection through the serial port monitor
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());           // Output the IP of esp8266 nodemcu through the serial port monitor
 
  esp8266_server.begin();                           // Start site service
  esp8266_server.on("/", HTTP_GET, handleRoot);     // Set the server root, that is, the function 'handleRoot' of '/'
  esp8266_server.on("/LED", HTTP_POST, handleLED);  // Set the function 'handleLED' to handle LED control requests
  esp8266_server.onNotFound(handleNotFound);        // Set the function 'handleNotFound' to handle 404 cases
 
  Serial.println("HTTP esp8266_server started");//  Inform the user that the ESP8266 network service function has been started
}
 
void loop(void){
  esp8266_server.handleClient();                     // Check http server access
}
 
void handleRoot() {       
  esp8266_server.send(200, "text/html", "<form action=\"/LED\" method=\"POST\"><input type=\"submit\" value=\"LED\"></form>");
}
 
//Function 'handleLED' for handling LED control request
void handleLED() {                          
  digitalWrite(D4,!digitalRead(D4));// Change the LED on or off state
  esp8266_server.sendHeader("Location","/");          // Jump back to page root
  esp8266_server.send(303);                           // Send Http corresponding code 303 jump  
}
 
// Set the function 'handleNotFound' to handle 404 cases
void handleNotFound(){
  esp8266_server.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (page not found) and send the text "404: Not found" to the browser
}
  • esp8266_server.on("/", HTTP_GET, handleRoot): use GET to request the browser

  • esp8266_server.on("/LED", HTTP_POST, handleLED);: Call the handleled function in post mode

  • esp8266_server.send:

  • 200: received message

  • "text/html": the type is html code

    <form action=\"/LED\" method=\"POST\">
        <input type=\"submit\" value=\"Toggle LED\">
    </form>
    
    • When the user presses the key, he sends a request to the server. The request mode is POST and the submitted page is LED
    • Until the program does not see the backslash, it does not indicate which are the double quotation marks of C language
  • digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN));: Change the LED on or off state

  • esp8266_server.sendHeader("Location","/");: Jump back to the home page

Write at the end

Note: all experiments in this column use the free simulation platform TinkerCAD, and the portal is as follows

Portal: ThinkerCAD

Code reference case Wireless terminal mode of nodemocu development board by Taiji maker

Ladies and gentlemen, I've seen it here. Please use your fingers to praise the blogger 8. Your support is the author's greatest creative power!
<(^-^)>
Lack of talent and learning. If there is any mistake, please correct it
This article is only for the purpose of learning and communication, not for any commercial purpose. If copyright issues are involved, please contact the author as soon as possible

Tags: Single-Chip Microcomputer server arduino NodeMCU

Posted on Mon, 22 Nov 2021 01:52:42 -0500 by sqlmc