Arduino project: Controlling the built-in LED using your browser
Arduino project: Controlling the built-in LED using your browser
In this tutorial, we will build upon the Arduino Web Server example to enable controlling the built-in LED on the Arduino board through commands sent from a web browser.
To achieve this, we will turn on the LED by accessing the /on URL and turn it off by accessing the /off URL. Any other URL will have no effect on the LED.
Let’s start with the code from the previous tutorial:
int status = WL_IDLE_STATUS; while (status != WL_CONNECTED) { Serial.print("Connecting to "); Serial.println(ssid); status = WiFi.begin(ssid, pass); delay(5000); }
voidloop(){ WiFiClient client = server.available(); if (client) { String line = ""; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c);
In the else block at the end of the code, we have a complete line that we can check for its content before clearing it. Here, we can check if it starts with GET /on or GET /off to determine the command we are requested to perform:
1 2 3 4 5 6 7 8 9 10
String command = "";
/* ... */
if (line.startsWith("GET /on ")) { command = "on"; } if (line.startsWith("GET /off ")) { command = "off"; }
When we are ready to send the response back, we can check the command and turn the LED on or off accordingly:
We can also send a confirmation response back to the client with:
1
client.println("Turned the LED " + command);
That’s it! Now upload the code to the Arduino and access the /on or /off URLs in your browser.
If you want to assign a static IP to the Arduino on your local network, you can do so through your router’s settings. In my case, I have added an entry for arduino.local in my /etc/hosts file, so I can access the Arduino using http://arduino.local/on to turn the LED on, and http://arduino.local/off to turn it off.
int status = WL_IDLE_STATUS; while (status != WL_CONNECTED) { Serial.print("Connecting to "); Serial.println(ssid); status = WiFi.begin(ssid, pass); delay(5000); }