Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

Simple Webserver

This simple Arduino program is designed to create a basic WiFi web server, allowing users to control the on and off state of an LED on the Arduino board via a web browser.

Run the Code

Note

  • You can open the file 01_simple_webserver.ino under the path of elite-explorer-kit-main\iot_project\01_simple_webserver directly.

  • Or copy this code into Arduino IDE.

Note

In the code, SSID and password are stored in arduino_secrets.h. Before uploading this example, you need to modify them with your own WiFi credentials.

arduino_secrets.h
#define SECRET_SSID "your_ssid"        // your network SSID (name)
#define SECRET_PASS "your_password"        // your network password (use for WPA, or use as key for WEP)
01_simple_webserver.ino
  1/*
  2  WiFi Web Server LED Blink
  3
  4  A simple web server that lets you blink an LED via the web.
  5  This sketch will print the IP address of your WiFi module (once connected)
  6  to the Serial Monitor. From there, you can open that address in a web browser
  7  to turn on and off the LED_BUILTIN.
  8
  9  If the IP address of your board is yourAddress:
 10  http://yourAddress/H turns the LED on
 11  http://yourAddress/L turns it off
 12
 13  This example is written for a network using WPA encryption. For
 14  WEP or WPA, change the WiFi.begin() call accordingly.
 15
 16  Circuit:
 17  * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and Uno WiFi Rev.2)
 18  * LED attached to pin 9
 19
 20  created 25 Nov 2012
 21  by Tom Igoe
 22
 23  Find the full UNO R4 WiFi Network documentation here:
 24  https://docs.arduino.cc/tutorials/uno-r4-wifi/wifi-examples#simple-webserver
 25 */
 26
 27#include "WiFiS3.h"
 28
 29#include "arduino_secrets.h" 
 30///////please enter your sensitive data in the Secret tab/arduino_secrets.h
 31char ssid[] = SECRET_SSID;        // your network SSID (name)
 32char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
 33int keyIndex = 0;                 // your network key index number (needed only for WEP)
 34
 35int led =  LED_BUILTIN;
 36int status = WL_IDLE_STATUS;
 37WiFiServer server(80);
 38
 39void setup() {
 40  Serial.begin(9600);      // initialize serial communication
 41  pinMode(led, OUTPUT);      // set the LED pin mode
 42
 43  // check for the WiFi module:
 44  if (WiFi.status() == WL_NO_MODULE) {
 45    Serial.println("Communication with WiFi module failed!");
 46    // don't continue
 47    while (true);
 48  }
 49
 50  String fv = WiFi.firmwareVersion();
 51  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
 52    Serial.println("Please upgrade the firmware");
 53  }
 54
 55  // attempt to connect to WiFi network:
 56  while (status != WL_CONNECTED) {
 57    Serial.print("Attempting to connect to Network named: ");
 58    Serial.println(ssid);                   // print the network name (SSID);
 59
 60    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
 61    status = WiFi.begin(ssid, pass);
 62    // wait 10 seconds for connection:
 63    delay(10000);
 64  }
 65  server.begin();                           // start the web server on port 80
 66  printWifiStatus();                        // you're connected now, so print out the status
 67}
 68
 69
 70void loop() {
 71  WiFiClient client = server.available();   // listen for incoming clients
 72
 73  if (client) {                             // if you get a client,
 74    Serial.println("new client");           // print a message out the serial port
 75    String currentLine = "";                // make a String to hold incoming data from the client
 76    while (client.connected()) {            // loop while the client's connected
 77      if (client.available()) {             // if there's bytes to read from the client,
 78        char c = client.read();             // read a byte, then
 79        Serial.write(c);                    // print it out to the serial monitor
 80        if (c == '\n') {                    // if the byte is a newline character
 81
 82          // if the current line is blank, you got two newline characters in a row.
 83          // that's the end of the client HTTP request, so send a response:
 84          if (currentLine.length() == 0) {
 85            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
 86            // and a content-type so the client knows what's coming, then a blank line:
 87            client.println("HTTP/1.1 200 OK");
 88            client.println("Content-type:text/html");
 89            client.println();
 90
 91            // the content of the HTTP response follows the header:
 92            client.print("<p style=\"font-size:7vw;\">Click <a href=\"/H\">here</a> turn the LED on<br></p>");
 93            client.print("<p style=\"font-size:7vw;\">Click <a href=\"/L\">here</a> turn the LED off<br></p>");
 94            
 95            // The HTTP response ends with another blank line:
 96            client.println();
 97            // break out of the while loop:
 98            break;
 99          } else {    // if you got a newline, then clear currentLine:
100            currentLine = "";
101          }
102        } else if (c != '\r') {  // if you got anything else but a carriage return character,
103          currentLine += c;      // add it to the end of the currentLine
104        }
105
106        // Check to see if the client request was "GET /H" or "GET /L":
107        if (currentLine.endsWith("GET /H")) {
108          digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
109        }
110        if (currentLine.endsWith("GET /L")) {
111          digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
112        }
113      }
114      
115    }
116    // close the connection:
117    client.stop();
118    Serial.println("client disconnected");
119  }
120}
121
122void printWifiStatus() {
123  // print the SSID of the network you're attached to:
124  Serial.print("SSID: ");
125  Serial.println(WiFi.SSID());
126
127  // print your board's IP address:
128  IPAddress ip = WiFi.localIP();
129  Serial.print("IP Address: ");
130  Serial.println(ip);
131
132  // print the received signal strength:
133  long rssi = WiFi.RSSI();
134  Serial.print("signal strength (RSSI):");
135  Serial.print(rssi);
136  Serial.println(" dBm");
137  // print where to go in a browser:
138  Serial.print("To see this page in action, open a browser to http://");
139  Serial.println(ip);
140}

After uploading the code, you will be able to see the IP address in the serial monitor. You can enter this IP address in your web browser to turn the onboard LED on/off.

../_images/01_webserver.png

How it works?

Here is an explanation of the code:

  1. Header Files and Global Variables:

    • #include "WiFiS3.h": This includes the WiFi library for connecting and managing WiFi. This library is included with Arduino UNO R4 Core, so no additional installation is required.

    • #include "arduino_secrets.h": This includes sensitive WiFi connection data such as SSID and password.

    • ssid, pass, keyIndex: These are network credentials used for WiFi connection.

    • led, status, server: These define the LED pin, WiFi status, and web server object.

  2. setup():

    • Begin serial communication.

    • Check for the presence of the WiFi module.

    • Check if the WiFi module’s firmware version is up-to-date.

    • Attempt to connect to the WiFi network.

    • Start the web server.

    • Print the WiFi status.

  3. loop():

    • Check for new web client connections.

    • If there are client connections, read their incoming HTTP requests.

    • Based on the requests, you can control the on/off state of the LED. For example, if the request is “GET /H,” it will turn on the LED; if it’s “GET /L,” it will turn off the LED.

    • Send an HTTP response to instruct the user on how to control the LED.

    • Disconnect the client.

  4. printWifiStatus():

    • Print the connected WiFi SSID.

    • Print the IP address of the Arduino board.

    • Print the received signal strength.

    • Explain how to view this page in a web browser.