Skip to content

Class 4 · The web page

The lamp runs its schedule, but changing it means editing code. Today the ESP32 makes its own Wi-Fi network and serves a settings page. Your phone joins the network, opens the page, and changes the schedule, the night-light colour and the brightness. The settings are saved in the ESP32's flash memory, so they survive a power cut. One more button sets the lamp's clock from your phone.

Web code is new, so the page and the server are given to you as a template. You connect it to your schedule and write the saving and clock-setting parts.

By the end of class

You change the sunrise time on your phone, unplug the lamp, plug it back in, and the page still shows your new time and the lamp follows it.

New parts today

None. Today is all code.

Tool: the ESP32 as a Wi-Fi access point

The ESP32 can make its own Wi-Fi network (an access point). Your phone joins it like any other network. There's no internet on it, and school Wi-Fi doesn't matter. On its own network, the ESP32 is always at the address 192.168.4.1.

A web server waits for a browser to ask for a page, then sends it back. Each page has a path: / is the main page, /hello would be another. server.on() says which function answers which path.

Example, not your project: a page that counts how many times it's been opened.

#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>

WebServer server(80);    // 80 is the normal port for web pages
int visits = 0;

void handleRoot() {
  visits++;
  String page = "<h1>Hello from the ESP32</h1><p>Visits: " + String(visits) + "</p>";
  server.send(200, "text/html", page);    // 200 means "OK"
}

void setup() {
  Serial.begin(115200);
  WiFi.softAP("Counter-Demo", "password123");   // name, password (8+ characters)
  Serial.println(WiFi.softAPIP());              // prints 192.168.4.1
  server.on("/", handleRoot);
  server.begin();
}

void loop() {
  server.handleClient();   // answer any browser that's asking
}

WiFi.h, WebServer.h and Preferences.h come with the ESP32 platform; you don't add them to lib_deps.

server.handleClient() has to run often. A delay(1000) in loop() makes the page take a second to answer; a long while loop makes it never answer. From now on, use millis() for anything that waits.

When your phone joins a network with no internet, it may warn you or try to switch back to cellular data. Tell it to stay connected.

Tool: Preferences (saving to flash)

Variables are lost when the power goes off. Preferences stores numbers in the ESP32's flash memory, which keeps them. You save a value under a name (a key, 15 characters at most), and read it back by the same name. Keys live inside a namespace, a group name for your project.

Example, not your project: count how many times the board has started.

#include <Arduino.h>
#include <Preferences.h>

Preferences prefs;

void setup() {
  Serial.begin(115200);
  prefs.begin("demo", false);          // namespace "demo", false = read and write
  int boots = prefs.getInt("boots", 0); // 0 if it has never been saved
  boots++;
  prefs.putInt("boots", boots);
  prefs.end();
  Serial.print("This board has started ");
  Serial.print(boots);
  Serial.println(" times.");
}

void loop() {}

Press reset a few times, and unplug it: the number keeps going up. There's putInt/getInt for whole numbers and putUInt/getUInt for unsigned ones (a colour like 0xFF6A00 fits in a uint32_t). Flash wears out after many thousands of writes, so save when a setting changes, not every time through loop().

The template

This is the given part. It's a complete program that runs on its own: it makes the network, serves the settings page, and reads what the page sends back into variables. It doesn't save anything or touch the strip or the clock yet. That's your work, in the three functions marked YOUR CODE.

Change AP_PASS before you use it. Anyone in range who knows the password can change your lamp.

Template: main.cpp (click to open)
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>

// ---------- Network ----------
const char* AP_NAME = "ClockLamp";
const char* AP_PASS = "change-me-123";     // 8 characters or more

WebServer server(80);

// ---------- Settings the page can change ----------
// Times are minutes since midnight.
int sunriseStart = 6 * 60 + 30;   // 06:30
int sunriseLength = 20;           // minutes
int onUntil = 7 * 60 + 30;        // 07:30
int nightStart = 21 * 60;         // 21:00
int offTime = 22 * 60;            // 22:00
uint32_t nightColor = 0xFF6A00;   // 0xRRGGBB
int brightness = 150;             // 0-255; keep it at or below your MAX_BRIGHTNESS

// ---------- YOUR CODE ----------
void saveSettings() {
  // Mission 2: save every setting above with Preferences.
  Serial.println("saveSettings() called");
}

void setLampClock(int y, int mo, int d, int h, int mi, int s) {
  // Mission 3: set the DS3231 to this time.
  Serial.printf("Phone time: %d-%02d-%02d %02d:%02d:%02d\n", y, mo, d, h, mi, s);
}

String lampTimeText() {
  // Mission 3: return the DS3231's time as text, like "06:30".
  return "not connected yet";
}

// ---------- The page ----------
const char PAGE[] = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Clock Lamp</title>
<style>
  body { font-family: sans-serif; max-width: 420px; margin: 20px auto; padding: 0 16px; }
  label { display: block; margin-top: 14px; }
  input { font-size: 1.1em; }
  button { font-size: 1.1em; margin-top: 18px; padding: 8px 16px; }
</style>
</head>
<body>
<h1>Clock Lamp</h1>
<p>Lamp time: %NOW%</p>

<form action="/save">
  <label>Sunrise starts <input type="time" name="sunrise" value="%SUNRISE%"></label>
  <label>Sunrise length (minutes) <input type="number" name="length" min="1" max="60" value="%LENGTH%"></label>
  <label>Light on until <input type="time" name="until" value="%UNTIL%"></label>
  <label>Night light on <input type="time" name="night" value="%NIGHT%"></label>
  <label>Lights off <input type="time" name="off" value="%OFF%"></label>
  <label>Night light colour <input type="color" name="color" value="%COLOR%"></label>
  <label>Brightness (0-255) <input type="number" name="bright" min="0" max="255" value="%BRIGHT%"></label>
  <button type="submit">Save</button>
</form>

<button onclick="setClock()">Set the lamp's clock from this phone</button>
<p id="msg"></p>

<script>
function setClock() {
  const d = new Date();
  const q = "y=" + d.getFullYear() + "&mo=" + (d.getMonth() + 1) + "&d=" + d.getDate() +
            "&h=" + d.getHours() + "&mi=" + d.getMinutes() + "&s=" + d.getSeconds();
  fetch("/settime?" + q)
    .then(r => r.text())
    .then(t => { document.getElementById("msg").textContent = t; });
}
</script>
</body>
</html>
)rawliteral";

// ---------- Helpers ----------
// 390 -> "06:30"
String toHHMM(int minutes) {
  char buf[6];
  snprintf(buf, sizeof(buf), "%02d:%02d", minutes / 60, minutes % 60);
  return String(buf);
}

// "06:30" -> 390
int fromHHMM(String text) {
  return text.substring(0, 2).toInt() * 60 + text.substring(3, 5).toInt();
}

// 0xFF6A00 -> "#ff6a00"
String toHexColor(uint32_t color) {
  char buf[8];
  snprintf(buf, sizeof(buf), "#%06x", (unsigned int)color);
  return String(buf);
}

// ---------- What each address does ----------
void handleRoot() {
  String page = PAGE;
  page.replace("%NOW%", lampTimeText());
  page.replace("%SUNRISE%", toHHMM(sunriseStart));
  page.replace("%LENGTH%", String(sunriseLength));
  page.replace("%UNTIL%", toHHMM(onUntil));
  page.replace("%NIGHT%", toHHMM(nightStart));
  page.replace("%OFF%", toHHMM(offTime));
  page.replace("%COLOR%", toHexColor(nightColor));
  page.replace("%BRIGHT%", String(brightness));
  server.send(200, "text/html", page);
}

void handleSave() {
  if (server.hasArg("sunrise")) sunriseStart = fromHHMM(server.arg("sunrise"));
  if (server.hasArg("length"))  sunriseLength = constrain(server.arg("length").toInt(), 1, 60);
  if (server.hasArg("until"))   onUntil = fromHHMM(server.arg("until"));
  if (server.hasArg("night"))   nightStart = fromHHMM(server.arg("night"));
  if (server.hasArg("off"))     offTime = fromHHMM(server.arg("off"));
  if (server.hasArg("color"))   nightColor = strtoul(server.arg("color").substring(1).c_str(), NULL, 16);
  if (server.hasArg("bright"))  brightness = constrain(server.arg("bright").toInt(), 0, 255);
  saveSettings();
  server.sendHeader("Location", "/");   // send the phone back to the main page
  server.send(303);
}

void handleSetTime() {
  int y  = server.arg("y").toInt();
  int mo = server.arg("mo").toInt();
  int d  = server.arg("d").toInt();
  int h  = server.arg("h").toInt();
  int mi = server.arg("mi").toInt();
  int s  = server.arg("s").toInt();
  if (y < 2024) {
    server.send(400, "text/plain", "That doesn't look like a real date.");
    return;
  }
  setLampClock(y, mo, d, h, mi, s);
  server.send(200, "text/plain", "Lamp clock set to " + toHHMM(h * 60 + mi));
}

void setup() {
  Serial.begin(115200);
  WiFi.softAP(AP_NAME, AP_PASS);
  Serial.print("Join the Wi-Fi network ");
  Serial.print(AP_NAME);
  Serial.print(" and open http://");
  Serial.println(WiFi.softAPIP());

  server.on("/", handleRoot);
  server.on("/save", handleSave);
  server.on("/settime", handleSetTime);
  server.begin();
}

void loop() {
  server.handleClient();
  // Your lamp code runs here too. No long delay() calls.
}

How the template works, in short:

  • PAGE is the HTML for the page, stored as one long piece of text. The words between % signs (%SUNRISE%) are placeholders. handleRoot() swaps each one for the current setting before sending the page, so the page always shows what the lamp is using.
  • When you press Save, the browser opens /save?sunrise=06:30&length=20&.... handleSave() reads each value with server.arg(), turns it back into a number, then calls saveSettings().
  • The Set the lamp's clock button runs a few lines of JavaScript in the phone's browser. It reads the phone's own date and time and sends them to /settime. handleSetTime() passes them to setLampClock().

Mission 1 · Your phone sees the page

Make a new project (or a new copy of your lamp project) and run the template on its own. Change the password. Join the network on your phone and open http://192.168.4.1. Change a setting and press Save.

Done when

The page opens on your phone, and after Save it shows your new value and the Serial Monitor shows saveSettings() called.

Mission 2 · The page runs the lamp, and remembers

Combine the template with your Class 3 lamp code into one program. Your schedule now uses the template's variables instead of constants. Then write saveSettings() with Preferences, and a loadSettings() that setup() calls to read them back, with the template's values as the defaults for the first start.

Watch for delay() in your Class 3 code: anything longer than a few milliseconds makes the page slow. Swap them for millis() timing.

Done when

You change the sunrise time on your phone, unplug the ESP32, plug it back in, and the page shows the new time. With a test sunrise set a couple of minutes ahead, the strip starts at the time you chose on the phone.

Mission 3 · Set the clock from your phone

Write setLampClock() so it sets the DS3231 (RTClib's rtc.adjust() takes a DateTime(year, month, day, hour, minute, second)). Write lampTimeText() so it returns the DS3231's current time. Remove any leftover rtc.adjust(DateTime(F(__DATE__), ...)) line from setup().

Done when

Set the DS3231 wrong on purpose (an hour off), press the button on your phone, and reload the page: "Lamp time" matches the phone.

If you finish early

  • Add a Test sunrise button that starts a 1-minute sunrise right now, so you can demo it any time.
  • Add a slider (<input type="range">) for the sunrise length.
  • Add a "Lights on / off" button that overrides the schedule until the next scheduled change.
  • Show the current mode (sunrise, on, night light, off) on the page.

Sign-off with Dr. Alvear

  • Phone opens the page; password changed from the template's
  • A setting changed on the phone survives an unplug
  • The button sets the lamp's clock from the phone
  • Build log updated (photo + two sentences)