Sub topic 10
Serving a Page from the Board
This chapter turns the board into a small web server. A browser on your local network asks the board for a page, and the board answers with data it has read or computed. You will start from the uptime sketch in the plan, then handle request parsing, a proper HTML page, simple routes, and the limits of a server this small.
Prerequisites assumed: you can already connect a WiFiNINA board to your network and read its IP address (see "Connecting to your network" and "Checking status, IP address, and signal strength"), and you know what a port and an HTTP request are. The sketches use arduino_secrets.h as shown in the credentials chapter.
How a board server differs from a client
In earlier chapters the board was a client: it opened a connection to a remote server and sent a request. Here the roles reverse. The board is the server: it listens on a port, waits for a client to connect, reads the request, and writes a response.
Two classes do this work in the WiFiNINA library:
WiFiServerlistens on a TCP port. You create it with a port number and callbegin()once the board is connected.WiFiClientrepresents one connected peer. When you callserver.available(), you get back aWiFiClientthat stands for the browser that just connected. If nobody is waiting, the returned object evaluates to false.
The minimal server
This sketch answers every request with a plain-text uptime reading. It reads and discards the request, so it does not care which path you ask for.
#include <WiFiNINA.h>
#include "arduino_secrets.h"
WiFiServer server(80);
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
server.begin();
Serial.print("Open http://");
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient client = server.available();
if (!client) return;
while (client.connected() && client.available()) {
client.read();
}
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/plain");
client.println("Connection: close");
client.println();
client.print("Uptime seconds: ");
client.println(millis() / 1000);
client.stop();
}Upload it, open the Serial Monitor, and type the printed address into a browser on a device connected to the same network. The page shows the uptime. Reload to see it grow.
What each part does
WiFiServer server(80)creates the server object for port 80, the default for HTTP. Browsers add no port to the URL when you use 80.server.begin()starts listening. Call it after the board has an IP address.server.available()returns the client that has data to read, or an empty object if there is none. Theif (!client) return;line keepsloop()fast when nobody is connected.- The status line
HTTP/1.1 200 OK, the headers, and the blank line form the response head. Everything after the blank line is the body. Connection: closetells the browser the board will close the socket after this response, so the browser does not wait for more data.client.stop()closes the connection and frees the socket.
Each line written with println ends in a carriage return and line feed (\r\n), which is what HTTP requires.
Reading the request properly
The minimal sketch throws the request away. That works for one page, but a useful server needs to know what was asked. An HTTP request looks like this:
GET /temperature HTTP/1.1
Host: 192.168.1.50
User-Agent: ...
Accept: ...
The first line is the request line: method, path, and protocol version. Headers follow, one per line, and a blank line ends them. The blank line is the signal that the request is complete.
A common pattern reads the request one character at a time and tracks lines. When it sees an empty line (a newline right after another newline), the request has ended and the response can start. This sketch also saves the request line so it can route on the path.
#include <WiFiNINA.h>
#include "arduino_secrets.h"
WiFiServer server(80);
void sendText(WiFiClient &client, const char *status, const char *body) {
client.print("HTTP/1.1 ");
client.println(status);
client.println("Content-Type: text/plain");
client.println("Connection: close");
client.println();
client.println(body);
}
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
server.begin();
Serial.print("Open http://");
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient client = server.available();
if (!client) return;
String requestLine = "";
String currentLine = "";
bool firstLineDone = false;
unsigned long start = millis();
while (client.connected() && millis() - start < 2000) {
if (!client.available()) continue;
char c = client.read();
if (c == '\n') {
if (currentLine.length() == 0) break; // blank line: headers done
if (!firstLineDone) {
requestLine = currentLine;
firstLineDone = true;
}
currentLine = "";
} else if (c != '\r') {
currentLine += c;
}
}
Serial.println(requestLine);
if (requestLine.startsWith("GET / ")) {
sendText(client, "200 OK", "Hello from the board");
} else if (requestLine.startsWith("GET /uptime ")) {
sendText(client, "200 OK", String(millis() / 1000).c_str());
} else {
sendText(client, "404 Not Found", "Not found");
}
client.stop();
}Points to notice:
- The loop has a two-second timeout (
millis() - start < 2000). Without it, a client that connects and sends nothing would hold the board in the loop forever. - The comparison includes a trailing space, as in
"GET /uptime ". The space marks the end of the path, so/uptimematches but/uptime2does not. A query string such as/uptime?x=1also fails to match, which you would handle separately if you need it. - Unknown paths get a
404 Not Foundstatus. Browsers also request/favicon.icoautomatically, so you will see that request in the Serial Monitor and receive a 404 for it. This is normal.
Sending an HTML page
Plain text is fine for debugging. For a page people read, send HTML and set the content type to text/html.
void sendPage(WiFiClient &client) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html; charset=utf-8");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE html>");
client.println("<html><head><title>Arduino</title>");
client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("</head><body>");
client.println("<h1>Board status</h1>");
client.print("<p>Uptime: ");
client.print(millis() / 1000);
client.println(" s</p>");
client.print("<p>Signal strength: ");
client.print(WiFi.RSSI());
client.println(" dBm</p>");
client.println("</body></html>");
}Replace the sendText call for GET / with sendPage(client) in the routing sketch. Dynamic values are written with client.print, so the page reflects the state of the board at the moment of the request.
Add <meta http-equiv="refresh" content="5"> inside <head> if you want the browser to reload the page every five seconds.
Keep memory in mind
Boards like the MKR WiFi 1010 and Nano 33 IoT have limited RAM. Two habits help:
- Write the page in pieces with
printandprintln, as above, instead of building one largeString. Each call sends data straight to the socket. - Wrap fixed text in the
F()macro, for exampleclient.println(F("<h1>Board status</h1>")), so the text stays in flash memory and not in RAM. On ARM-based boards such as the MKR family and Nano 33 IoT, string literals already live in flash, soF()is harmless but gives little benefit. It matters mostly on AVR boards.
Serving more than one request
WiFiServer handles clients one at a time in this pattern. While the board writes a response to one browser, the next browser waits in the queue. This is fine for a status page. It becomes a problem if:
- A response takes a long time to build, for example because you wait on a slow sensor.
- A client keeps the connection open and never finishes its request.
The timeout in the request reader limits the second case. For the first, read sensors in loop() outside the request handler, store the values in variables, and have the handler only format them. This keeps each response fast.
Browsers often open several connections at once, for the page and for the favicon. If the page seems to load slowly, check that every path calls client.stop() so the socket is released.
Controlling something from a page
A page can also send commands. The simplest method uses links that request different paths, and the board changes state when it sees them.
const int LED_PIN = LED_BUILTIN;
void handleRequest(const String &requestLine) {
if (requestLine.startsWith("GET /led/on ")) {
digitalWrite(LED_PIN, HIGH);
} else if (requestLine.startsWith("GET /led/off ")) {
digitalWrite(LED_PIN, LOW);
}
}Call pinMode(LED_PIN, OUTPUT) in setup() and call handleRequest(requestLine) before sending the page. Then add links such as <a href="/led/on">On</a> to the HTML.
Using GET to change state is easy but has a flaw: any link, image, or browser prefetch that requests the URL triggers the action. HTTP convention reserves GET for reading, and POST for changes. Reading a POST body from the board is possible but needs more parsing, so many hobby projects accept the GET shortcut on a private network. Treat it as a shortcut, not a design.
Security and reachability
The server has no encryption and no login.
- Plain HTTP. Anyone on the same network can read the traffic and the requests.
WiFiServerdoes not provide TLS, so do not put passwords or private data on the page. - Local network only. The board has a private address such as
192.168.1.50. Devices on the internet cannot reach it unless you configure port forwarding on your router. Avoid that. It exposes an unauthenticated device with little memory for handling hostile input. - Limited input handling. The
Stringconcatenation above grows with the request. A long request line uses more memory. Cap the line length (for example, stop appending after 200 characters) if the network is not fully trusted. - Actions without authentication. Anyone who can reach
/led/oncan use it. Do not wire a lock, heater, or similar device to an open path.
If you need access from outside your home, use an outbound connection from the board instead, such as MQTT through a broker, which the board opens itself.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Browser times out | Device on a different network or a guest network with client isolation | Join the same network. Disable client isolation on the router. |
| Page never finishes loading | Missing blank line after headers, or no `client.stop()` | Check the head ends with an empty `println()`. Close the client. |
| Page shows raw HTML text | Content type is `text/plain` | Send `Content-Type: text/html`. |
| Server stops answering after hours | Wi-Fi dropped and was never restored | Add the non-blocking reconnect check from the reconnection chapter, and call `server.begin()` again if needed. |
| Extra 404 lines in Serial Monitor | Browser requests `/favicon.ico` | Ignore them, or answer with a 404 or 204 status. |
| IP address changes after reboot | The router's DHCP gave a new lease | Reserve the address for the board in the router. |
Putting it together
A reliable board server follows this order on every pass through loop():
- Check the Wi-Fi status and reconnect without blocking if it is down.
- Read sensors on a timer and store the values.
- Call
server.available()and, if a client is present, read the request with a timeout. - Route on the request line, and write a response with a status, headers, a blank line, and a body.
- Call
client.stop().
Exercise
A browser loads your board's page but shows the text of the HTML tags (such as <h1>Board status</h1>) as plain characters. Which line of the response is most likely wrong, and what should it be?
Show answer
The Content-Type header is probably "text/plain". Change it to "Content-Type: text/html; charset=utf-8" so the browser renders the markup.
Exercise
Your routing code uses requestLine.startsWith("GET /uptime"), without a trailing space. Give one request that matches but should not, and say how to fix it.
Show answer
A request such as "GET /uptime-history HTTP/1.1" (or "GET /uptime2 ...") matches, because only the prefix is compared. Include the trailing space, as in "GET /uptime ", so the path must end there. A query string such as /uptime?x=1 then needs separate handling.
Exercise
Why is it a poor idea to forward port 80 on your router to this board so you can reach it from anywhere?
Show answer
The server uses plain HTTP with no login, so anyone on the internet could read the traffic and trigger any action the board exposes. The board also has little memory to handle hostile or malformed requests. Use an outbound connection such as MQTT, or a VPN to your home network, instead.