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!
WiFi-Controlled LED (Access Point)
This project allows you to control an LED light through a web interface. The Arduino board acts as a WiFi access point, creating its own local network that you can connect to with a web browser. Once connected, you can navigate to the device’s IP address using the web browser, where you’ll find options to turn an LED (connected to the board’s pin 13) on and off. The project provides real-time feedback on the LED status via the Serial Monitor, making it easier to debug and understand the flow of operations.
1. Upload the code
Open the 01-wifi_ap.ino file under the path of elite-explorer-kit-main\r4_new_feature\01-wifi_ap, or copy this code into Arduino IDE.
Note
Wi-Fi® support is enabled via the built-in WiFiS3 library that is shipped with the Arduino UNO R4 Core. Installing the core automatically installs the WiFiS3 library.
You still need to create or modify arduino_secrets.h, replace SECRET_SSID and SECRET_PASS with the name and password of your WiFi access point. The file should contain:
//arduino_secrets.h header file
#define SECRET_SSID "your_ssid"
#define SECRET_PASS "your_password"
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 create a new access point (with no password).
6 It will then launch a new server and print out the IP address
7 to the Serial Monitor. From there, you can open that address in a web browser
8 to turn on and off the LED on pin 13.
9
10 If the IP address of your board is yourAddress:
11 http://yourAddress/H turns the LED on
12 http://yourAddress/L turns it off
13
14 created 25 Nov 2012
15 by Tom Igoe
16 adapted to WiFi AP by Adafruit
17
18 Find the full UNO R4 WiFi RTC documentation here:
19 https://docs.arduino.cc/tutorials/uno-r4-wifi/wifi-examples#access-point
20 */
21
22
23#include "WiFiS3.h"
24
25#include "arduino_secrets.h"
26
27///////please enter your sensitive data in the Secret tab/arduino_secrets.h
28char ssid[] = SECRET_SSID; // your network SSID (name)
29char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
30int keyIndex = 0; // your network key index number (needed only for WEP)
31
32int led = LED_BUILTIN;
33int status = WL_IDLE_STATUS;
34WiFiServer server(80);
35
36void setup() {
37 //Initialize serial and wait for port to open:
38 Serial.begin(9600);
39 while (!Serial) {
40 ; // wait for serial port to connect. Needed for native USB port only
41 }
42 Serial.println("Access Point Web Server");
43
44 pinMode(led, OUTPUT); // set the LED pin mode
45
46 // check for the WiFi module:
47 if (WiFi.status() == WL_NO_MODULE) {
48 Serial.println("Communication with WiFi module failed!");
49 // don't continue
50 while (true);
51 }
52
53 String fv = WiFi.firmwareVersion();
54 if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
55 Serial.println("Please upgrade the firmware");
56 }
57
58 // by default the local IP address will be 192.168.4.1
59 // you can override it with the following:
60 WiFi.config(IPAddress(192,48,56,2));
61
62 // print the network name (SSID);
63 Serial.print("Creating access point named: ");
64 Serial.println(ssid);
65
66 // Create open network. Change this line if you want to create an WEP network:
67 status = WiFi.beginAP(ssid, pass);
68 if (status != WL_AP_LISTENING) {
69 Serial.println("Creating access point failed");
70 // don't continue
71 while (true);
72 }
73
74 // wait 10 seconds for connection:
75 delay(10000);
76
77 // start the web server on port 80
78 server.begin();
79
80 // you're connected now, so print out the status
81 printWiFiStatus();
82}
83
84
85void loop() {
86
87 // compare the previous status to the current status
88 if (status != WiFi.status()) {
89 // it has changed update the variable
90 status = WiFi.status();
91
92 if (status == WL_AP_CONNECTED) {
93 // a device has connected to the AP
94 Serial.println("Device connected to AP");
95 } else {
96 // a device has disconnected from the AP, and we are back in listening mode
97 Serial.println("Device disconnected from AP");
98 }
99 }
100
101 WiFiClient client = server.available(); // listen for incoming clients
102
103 if (client) { // if you get a client,
104 Serial.println("new client"); // print a message out the serial port
105 String currentLine = ""; // make a String to hold incoming data from the client
106 while (client.connected()) { // loop while the client's connected
107 delayMicroseconds(10); // This is required for the Arduino Nano RP2040 Connect - otherwise it will loop so fast that SPI will never be served.
108 if (client.available()) { // if there's bytes to read from the client,
109 char c = client.read(); // read a byte, then
110 Serial.write(c); // print it out to the serial monitor
111 if (c == '\n') { // if the byte is a newline character
112
113 // if the current line is blank, you got two newline characters in a row.
114 // that's the end of the client HTTP request, so send a response:
115 if (currentLine.length() == 0) {
116 // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
117 // and a content-type so the client knows what's coming, then a blank line:
118 client.println("HTTP/1.1 200 OK");
119 client.println("Content-type:text/html");
120 client.println();
121
122 // the content of the HTTP response follows the header:
123 client.print("<p style=\"font-size:7vw;\">Click <a href=\"/H\">here</a> turn the LED on<br></p>");
124 client.print("<p style=\"font-size:7vw;\">Click <a href=\"/L\">here</a> turn the LED off<br></p>");
125
126 // The HTTP response ends with another blank line:
127 client.println();
128 // break out of the while loop:
129 break;
130 }
131 else { // if you got a newline, then clear currentLine:
132 currentLine = "";
133 }
134 }
135 else if (c != '\r') { // if you got anything else but a carriage return character,
136 currentLine += c; // add it to the end of the currentLine
137 }
138
139 // Check to see if the client request was "GET /H" or "GET /L":
140 if (currentLine.endsWith("GET /H")) {
141 digitalWrite(led, HIGH); // GET /H turns the LED on
142 }
143 if (currentLine.endsWith("GET /L")) {
144 digitalWrite(led, LOW); // GET /L turns the LED off
145 }
146 }
147 }
148 // close the connection:
149 client.stop();
150 Serial.println("client disconnected");
151 }
152}
153
154void printWiFiStatus() {
155 // print the SSID of the network you're attached to:
156 Serial.print("SSID: ");
157 Serial.println(WiFi.SSID());
158
159 // print your WiFi shield's IP address:
160 IPAddress ip = WiFi.localIP();
161 Serial.print("IP Address: ");
162 Serial.println(ip);
163
164 // print where to go in a browser:
165 Serial.print("To see this page in action, open a browser to http://");
166 Serial.println(ip);
167
168}
2. Code explanation
Importing Required Libraries
Importing the
WiFiS3library for WiFi functionalities andarduino_secrets.hfor sensitive data like passwords.#include "WiFiS3.h" #include "arduino_secrets.h"
Configuration and Variable Initialization
Define WiFi SSID, password, and key index along with the LED pin and WiFi status.
char ssid[] = SECRET_SSID; char pass[] = SECRET_PASS; int keyIndex = 0; int led = LED_BUILTIN; int status = WL_IDLE_STATUS; WiFiServer server(80);
setup()FunctionInitialize the serial communication and configure the WiFi module.
void setup() { // ... setup code ... // Create access point status = WiFi.beginAP(ssid, pass); // ... error handling ... // start the web server on port 80 server.begin(); }
We also check if the firmware version of uno R4 wifi is up to date. If it is not the latest version, a prompt for upgrade will be displayed. You can refer to Update the radio module firmware on your UNO R4 WiFi board for firmware upgrade.
... String fv = WiFi.firmwareVersion(); if (fv < WIFI_FIRMWARE_LATEST_VERSION) { Serial.println("Please upgrade the firmware"); } ...
You may want to modify the following code in order to be able to change the default IP of Arduino.
WiFi.config(IPAddress(192,48,56,2));
Main
loop()FunctionThe
loop()function in the Arduino code performs several key operations, specifically:Checking if a device has connected or disconnected from the access point.
Listening for incoming clients who make HTTP requests.
Reading client data and executing actions based on that data—like turning an LED on or off.
Here, let’s break down the
loop()function to make these steps more understandable.Checking WiFi Status
The code first checks if the WiFi status has changed. If a device has connected or disconnected, the serial monitor will display the information accordingly.
if (status != WiFi.status()) { status = WiFi.status(); if (status == WL_AP_CONNECTED) { Serial.println("Device connected to AP"); } else { Serial.println("Device disconnected from AP"); } }
Listening for Incoming Clients
WiFiClient client = server.available();waits for incoming clients.WiFiClient client = server.available();
Handling Client Requests
Listens for incoming clients and serves them the HTML web page. When a user clicks on the “Click here to turn the LED on” or “Click here to turn the LED off” links on the served webpage, an HTTP GET request is sent to the Arduino server. Specifically, the URLs “http://yourAddress/H” for turning on the LED and “http://yourAddress/L” for turning it off will be accessed.
WiFiClient client = server.available(); if (client) { // ... client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println(); client.print("<p style=\"font-size:7vw;\">Click <a href=\"/H\">here</a> turn the LED on<br></p>"); client.print("<p style=\"font-size:7vw;\">Click <a href=\"/L\">here</a> turn the LED off<br></p>"); // ... }
The Arduino code listens for these incoming GET requests. When it detects
GET /Hat the end of an incoming line of text (HTTP header), it sets the LED connected to pin 13 to HIGH, effectively turning it on. Similarly, if it detectsGET /L, it sets the LED to LOW, turning it off.while (client.connected()) { // loop while the client's connected delayMicroseconds(10); // This is required for the Arduino Nano RP2040 Connect - otherwise it will loop so fast that SPI will never be served. if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out to the serial monitor if (c == '\n') { // if the byte is a newline character ... } else { // if you got a newline, then clear currentLine: currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } // Check to see if the client request was "GET /H" or "GET /L": if (currentLine.endsWith("GET /H")) { digitalWrite(led, HIGH); // GET /H turns the LED on } if (currentLine.endsWith("GET /L")) { digitalWrite(led, LOW); // GET /L turns the LED off } }
Reference