/* ESP32 HTTP IoT Server Example for Wokwi.com
https://wokwi.com/projects/320964045035274834
To test, you need the Wokwi IoT Gateway, as explained here:
https://docs.wokwi.com/guides/esp32-wifi#the-private-gateway
Then start the simulation, and open http://localhost:9080
in another browser tab.
Note that the IoT Gateway requires a Wokwi Club subscription.
To purchase a Wokwi Club subscription, go to https://wokwi.com/club
*/
#include <WiFi.h>/* --------------------------------------------------------------
Application: 05 - Option 1 [ Hard ]
Class: Real Time Systems - Su 2025
Author: [M Borowczak]
Email: [[email protected]]
Company: [University of Central Florida]
Website: theDRACOlab.com
AI Use: Please commented inline where you use(d) AI
Notes: This code shows you enough hints to prove that you can implement
a wifi webserver in wokwi ; it's hacked together from a couple different
examples from esp-idf, wokwi, and other sources! It does NOT use any tasks
but it should ;-)
Option 2 [Easier] Convert the code in the project below to use the arduino_freertos library https://github.com/feilipu/Arduino_FreeRTOS_Library
Remember - your goal is to convert the code here: http://wokwi.com/projects/320964045035274834
use tasks as appropriate, and then extend it!
To test, you need the Wokwi IoT Gateway, as explained here:
https://docs.wokwi.com/guides/esp32-wifi#the-private-gateway
Then start the simulation, and open http://localhost:9080
in another browser tab.
---------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //Requires by memset
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include <esp_http_server.h>
#include "esp_wifi.h"
#include "esp_event.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include "driver/gpio.h"
#include <lwip/sockets.h>
#include <lwip/sys.h>
#include <lwip/api.h>
#include <lwip/netdb.h>
#define LED_PIN 2
#define CONFIG_LOG_DEFAULT_LEVEL_INFO 1
#define CONFIG_LOG_MAXIMUM_LEVEL 5
char on_resp[] = "<!DOCTYPE html><html><head><style type=\"text/css\">html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;}h1{ color: #070812; padding: 2vh;}.button { display: inline-block; background-color: #b30000; //red color border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}.button2 { background-color: #364cf4; //blue color}.content { padding: 50px;}.card-grid { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));}.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);}.card-title { font-size: 1.2rem; font-weight: bold; color: #034078}</style> <title>ESP32 WEB SERVER</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"icon\" href=\"data:,\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" type=\"text/css\" ></head><body> <h2>ESP32 WEB SERVER</h2> <div class=\"content\"> <div class=\"card-grid\"> <div class=\"card\"> <p><i class=\"fas fa-lightbulb fa-2x\" style=\"color:#c81919;\"></i> <strong>GPIO2</strong></p> <p>GPIO state: <strong> ON</strong></p> <p> <a href=\"/led2on\"><button class=\"button\">ON</button></a> <a href=\"/led2off\"><button class=\"button button2\">OFF</button></a> </p> </div> </div> </div></body></html>";
char off_resp[] = "<!DOCTYPE html><html><head><style type=\"text/css\">html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;}h1{ color: #070812; padding: 2vh;}.button { display: inline-block; background-color: #b30000; //red color border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}.button2 { background-color: #364cf4; //blue color}.content { padding: 50px;}.card-grid { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));}.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);}.card-title { font-size: 1.2rem; font-weight: bold; color: #034078}</style> <title>ESP32 WEB SERVER</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"icon\" href=\"data:,\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" type=\"text/css\"></head><body> <h2>ESP32 WEB SERVER</h2> <div class=\"content\"> <div class=\"card-grid\"> <div class=\"card\"> <p><i class=\"fas fa-lightbulb fa-2x\" style=\"color:#c81919;\"></i> <strong>GPIO2</strong></p> <p>GPIO state: <strong> OFF</strong></p> <p> <a href=\"/led2on\"><button class=\"button\">ON</button></a> <a href=\"/led2off\"><button class=\"button button2\">OFF</button></a> </p> </div> </div> </div></body></html>";
static const char *TAG = "espressif"; // TAG for debug
int led_state = 0;
#define EXAMPLE_ESP_WIFI_SSID "Wokwi-GUEST"
#define EXAMPLE_ESP_WIFI_PASS ""
#define EXAMPLE_ESP_MAXIMUM_RETRY 5
/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;
/* The event group allows multiple bits for each event, but we only care about two events:
* - we are connected to the AP with an IP
* - we failed to connect after the maximum amount of retries */
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
static int s_retry_num = 0;
static void event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
{
esp_wifi_connect();
}
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
{
if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY)
{
esp_wifi_connect();
s_retry_num++;
ESP_LOGI(TAG, "retry to connect to the AP");
}
else
{
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
ESP_LOGI(TAG, "connect to the AP fail");
}
else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
{
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
void connect_wifi(void)
{
s_wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
esp_event_handler_instance_t instance_any_id;
esp_event_handler_instance_t instance_got_ip;
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
&event_handler,
NULL,
&instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP,
&event_handler,
NULL,
&instance_got_ip));
wifi_config_t wifi_config = {
.sta = {
.ssid = EXAMPLE_ESP_WIFI_SSID,
.password = EXAMPLE_ESP_WIFI_PASS,
/* Setting a password implies station will connect to all security modes including WEP/WPA.
* However these modes are deprecated and not advisable to be used. Incase your Access point
* doesn't support WPA2, these mode can be enabled by commenting below line */
// .threshold.authmode = WIFI_AUTH_WPA2_PSK,
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "wifi_init_sta finished.");
/* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
* number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
portMAX_DELAY);
/* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
* happened. */
if (bits & WIFI_CONNECTED_BIT)
{
ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
}
else if (bits & WIFI_FAIL_BIT)
{
ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
}
else
{
ESP_LOGE(TAG, "UNEXPECTED EVENT");
}
vEventGroupDelete(s_wifi_event_group);
}
esp_err_t send_web_page(httpd_req_t *req)
{
int response;
if (led_state == 0)
response = httpd_resp_send(req, off_resp, HTTPD_RESP_USE_STRLEN);
else
response = httpd_resp_send(req, on_resp, HTTPD_RESP_USE_STRLEN);
return response;
}
esp_err_t get_req_handler(httpd_req_t *req)
{
return send_web_page(req);
}
esp_err_t led_on_handler(httpd_req_t *req)
{
//gpio_set_level(LED_PIN, 1);
led_state = 1;
return send_web_page(req);
}
esp_err_t led_off_handler(httpd_req_t *req)
{
//gpio_set_level(LED_PIN, 0);
led_state = 0;
return send_web_page(req);
}
httpd_uri_t uri_get = {
.uri = "/",
.method = HTTP_GET,
.handler = get_req_handler,
.user_ctx = NULL};
httpd_uri_t uri_on = {
.uri = "/led2on",
.method = HTTP_GET,
.handler = led_on_handler,
.user_ctx = NULL};
httpd_uri_t uri_off = {
.uri = "/led2off",
.method = HTTP_GET,
.handler = led_off_handler,
.user_ctx = NULL};
httpd_handle_t setup_server(void)
{
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
httpd_handle_t server = NULL;
if (httpd_start(&server, &config) == ESP_OK)
{
httpd_register_uri_handler(server, &uri_get);
httpd_register_uri_handler(server, &uri_on);
httpd_register_uri_handler(server, &uri_off);
}
return server;
}
void app_main()
{
esp_log_level_set(TAG, ESP_LOG_INFO);
// Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
connect_wifi();
// GPIO initialization
//gpio_pad_select_gpio(LED_PIN);
//gpio_set_direction(LED_PIN, GPIO_MODE_OUTPUT);
led_state = 0;
ESP_LOGI(TAG, "LED Control Web Server is running ... ...\n");
setup_server();
}
#include <WiFiClient.h>
#include <WebServer.h>
#include <uri/UriBraces.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
WebServer server(80);
const int LED1 = 26;
const int LED2 = 27;
bool led1State = false;
bool led2State = false;
void sendHtml() {
String response = R"(
<!DOCTYPE html><html>
<head>
<title>ESP32 Web Server Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html { font-family: sans-serif; text-align: center; }
body { display: inline-flex; flex-direction: column; }
h1 { margin-bottom: 1.2em; }
h2 { margin: 0; }
div { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: auto auto; grid-auto-flow: column; grid-gap: 1em; }
.btn { background-color: #5B5; border: none; color: #fff; padding: 0.5em 1em;
font-size: 2em; text-decoration: none }
.btn.OFF { background-color: #333; }
</style>
</head>
<body>
<h1>ESP32 Web Server</h1>
<div>
<h2>LED 1</h2>
<a href="/toggle/1" class="btn LED1_TEXT">LED1_TEXT</a>
<h2>LED 2</h2>
<a href="/toggle/2" class="btn LED2_TEXT">LED2_TEXT</a>
</div>
</body>
</html>
)";
response.replace("LED1_TEXT", led1State ? "ON" : "OFF");
response.replace("LED2_TEXT", led2State ? "ON" : "OFF");
server.send(200, "text/html", response);
}
void setup(void) {
Serial.begin(115200);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", sendHtml);
server.on(UriBraces("/toggle/{}"), []() {
String led = server.pathArg(0);
Serial.print("Toggle LED #");
Serial.println(led);
switch (led.toInt()) {
case 1:
led1State = !led1State;
digitalWrite(LED1, led1State);
break;
case 2:
led2State = !led2State;
digitalWrite(LED2, led2State);
break;
}
sendHtml();
});
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
delay(2);
}