How to run a Web Server on an Arduino
In this tutorial, I will guide you on how to start a Web Server on an Arduino device with WiFi connectivity, such as the Arduino MKR WiFi 1010.
By connecting to an existing WiFi network, you can interact with the Arduino using your browser via HTTP. This opens up a wide range of possibilities, from simple checks of sensor data to performing actions based on HTTP requests.
To start, let’s use the code from the tutorial “Connect to a WiFi network using an Arduino”:
1 |
|
Before the setup()
function, add this line to initialize a TCP server on port 80:
1 | WiFiServer server(80); |
Then, at the end of the setup()
function, call server.begin()
to start the server:
1 | server.begin(); |
Now, we have a TCP server, but we want to create an HTTP server. Since HTTP is built on top of TCP, we can implement the HTTP server ourselves.
In the loop()
function, let’s listen for client connections:
1 | void loop() { |
The server.available()
method listens for incoming client connections.
Within the if (client)
block, we have an HTTP client connected. Here’s what we need to do:
- Call
client.connected()
to check if the client is still connected and if there is data to read. - Call
client.available()
to get the number of bytes available for reading. This ensures that there is data to read. - Call
client.read()
to read one byte from the incoming data (the HTTP request sent by the client). - Call
client.println()
orclient.print()
to send data back to the client and build a proper HTTP response. - Call
client.stop()
to end the connection.
Let’s print each character sent by the client and close the connection at the end:
1 | void loop() { |
Try uploading this program to your Arduino and point your browser to the Arduino’s IP address. You should see the HTTP request printed in the serial interface. It will look something like this:
1 | GET / |
Note the ending empty line, which marks the end of the HTTP request.
To determine the end of the request, we need to detect two sets of sequence \r\n\r\n
. We can achieve this by storing the previous two characters and checking if they form the sequence \n\r\n
.
Here’s the updated code to handle the response:
1 | void loop() { |
In this code, we send the HTTP response using client.println()
and add a simple response message within the <html>
tags.
Now you can try it out! When you point your browser to the Arduino’s IP address, you should see “test” displayed on the page.
With this approach, you can handle more advanced actions based on the client’s request. You can read each line of the request and act accordingly.
Here’s an alternative code snippet that reads each line of the request:
1 | void loop() { |
In this code, we store each line in a String
variable and evaluate the line when it is terminated by a newline character. This allows us to inspect the request and respond accordingly.
Tags: Arduino, Web Server, WiFi, HTTP, TCP, Internet of Things