1+ /* ********
2+ Rui Santos
3+ Complete project details at https://randomnerdtutorials.com
4+ *********/
5+
6+ // Import required libraries
7+ #include " WiFi.h"
8+ #include " ESPAsyncWebServer.h"
19#include " SPIFFS.h"
10+
11+ // Replace with your network credentials
12+ const char * ssid = " Hotspot" ;
13+ const char * password = " Password" ;
14+
15+ // Set LED GPIO
16+ const int ledPin = 2 ;
17+ // Stores LED state
18+ String ledState;
19+
20+ // Create AsyncWebServer object on port 80
21+ AsyncWebServer server (80 );
22+
23+ // Replaces placeholder with LED state value
24+ String processor (const String& var){
25+ Serial.println (var);
26+ if (var == " STATE" ){
27+ if (digitalRead (ledPin)){
28+ ledState = " ON" ;
29+ }
30+ else {
31+ ledState = " OFF" ;
32+ }
33+ Serial.print (ledState);
34+ return ledState;
35+ }
36+ return String ();
37+ }
238
3- void setup () {
39+ void setup (){
40+ // Serial port for debugging purposes
441 Serial.begin (115200 );
5-
42+ pinMode (ledPin, OUTPUT);
43+
44+ // Initialize SPIFFS
645 if (!SPIFFS.begin (true )){
746 Serial.println (" An Error has occurred while mounting SPIFFS" );
847 return ;
948 }
10-
11- File file = SPIFFS.open (" /test_example.txt" );
12- if (!file){
13- Serial.println (" Failed to open file for reading" );
14- return ;
49+
50+ // Connect to Wi-Fi
51+ WiFi.begin (ssid, password);
52+ while (WiFi.status () != WL_CONNECTED) {
53+ delay (1000 );
54+ Serial.println (" Connecting to WiFi.." );
1555 }
56+
57+ // Print ESP32 Local IP Address
58+ Serial.println (WiFi.localIP ());
59+
60+ // Route for root / web page
61+ server.on (" /" , HTTP_GET, [](AsyncWebServerRequest *request){
62+ request->send (SPIFFS, " /index.html" , String (), false , processor);
63+ });
1664
17- Serial.println (" File Content:" );
18- while (file.available ()){
19- Serial.write (file.read ());
20- }
21- file.close ();
22- }
23-
24- void loop () {
25- delay (2000 );
65+ // Route to load style.css file
66+ server.on (" /style.css" , HTTP_GET, [](AsyncWebServerRequest *request){
67+ request->send (SPIFFS, " /style.css" , " text/css" );
68+ });
2669
27- File file = SPIFFS. open ( " /test_example.txt " );
28- if (!file ){
29- Serial. println ( " Failed to open file for reading " );
30- return ;
31- }
70+ // Route to set GPIO to HIGH
71+ server. on ( " /on " , HTTP_GET, [](AsyncWebServerRequest *request ){
72+ digitalWrite (ledPin, HIGH);
73+ request-> send (SPIFFS, " /index.html " , String (), false , processor) ;
74+ });
3275
33- Serial.println (" File Content:" );
34- while (file.available ()){
35- Serial.write (file.read ());
36- }
37- Serial.println (" " );
38- file.close ();
76+ // Route to set GPIO to LOW
77+ server.on (" /off" , HTTP_GET, [](AsyncWebServerRequest *request){
78+ digitalWrite (ledPin, LOW);
79+ request->send (SPIFFS, " /index.html" , String (), false , processor);
80+ });
3981
82+ // Start server
83+ server.begin ();
84+ }
85+
86+ void loop (){
87+
4088}
0 commit comments