#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
constexpr uint8_t DIN_PIN = 4;
constexpr uint8_t CLK_PIN = 5;
constexpr uint8_t CS_PIN = 6;
constexpr uint8_t UP_PIN = 0;
constexpr uint8_t OK_PIN = 1;
constexpr uint8_t DOWN_PIN = 3;
constexpr uint8_t UP_BUTTON = 1;
constexpr uint8_t OK_BUTTON = 2;
constexpr uint8_t DOWN_BUTTON = 4;
constexpr unsigned long DATE_DURATION_MS = 5000;
constexpr unsigned long SCROLL_STEP_MS = 280;
constexpr unsigned long WIFI_TIMEOUT_MS = 25000;
constexpr time_t MIN_VALID_TIME = 1704067200;
const char* SETUP_SSID = "MatrixClock-Setup";
const char* SETUP_PASSWORD = "ClockSetup8";
struct Zone {
const char* city;
const char* rule;
};
const Zone zones[] = {
{"Dublin", "GMT0IST,M3.5.0/1,M10.5.0/2"},
{"London", "GMT0BST,M3.5.0/1,M10.5.0/2"},
{"Paris", "CET-1CEST,M3.5.0,M10.5.0/3"},
{"Berlin", "CET-1CEST,M3.5.0,M10.5.0/3"},
{"Tehran", "<+0330>-3:30"},
{"Istanbul", "TRT-3"},
{"Dubai", "GST-4"},
{"New Delhi", "IST-5:30"},
{"Tokyo", "JST-9"},
{"New York", "EST5EDT,M3.2.0,M11.1.0"},
{"Chicago", "CST6CDT,M3.2.0,M11.1.0"},
{"Los Angeles", "PST8PDT,M3.2.0,M11.1.0"},
{"Sydney", "AEST-10AEDT,M10.1.0,M4.1.0/3"},
{"UTC", "UTC0"}
};
constexpr uint8_t ZONE_COUNT = sizeof(zones) / sizeof(zones[0]);
constexpr uint8_t CUSTOM_ZONE = ZONE_COUNT;
struct Settings {
char ssid[33];
char password[65];
char customZone[96];
uint8_t zone;
};
Settings settings {};
Preferences preferences;
WebServer server(80);
bool setupActive = false;
bool restartPending = false;
bool awaitingWiFi = false;
bool wasConnected = false;
bool showingDate = false;
unsigned long restartAt = 0;
unsigned long wifiStartedAt = 0;
unsigned long dateStartedAt = 0;
int brightness = 0;
uint8_t pixels[2][8] = {};
const uint8_t digits[][5] = {
{7,5,5,5,7}, {2,6,2,2,7}, {7,1,7,4,7}, {7,1,7,1,7},
{5,5,7,1,1}, {7,4,7,1,7}, {7,4,7,5,7}, {7,1,1,1,1},
{7,5,7,5,7}, {7,5,7,1,7}
};
const char* const months[] = {
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
};
const char monthLetters[] = "ABCDEFGJLMNOPRSTUVY";
const uint8_t monthFont[][5] = {
{2,5,7,5,5}, {6,5,6,5,6}, {7,4,4,4,7}, {6,5,5,5,6},
{7,4,6,4,7}, {7,4,6,4,4}, {7,4,5,5,7}, {1,1,1,5,7},
{4,4,4,4,7}, {5,7,7,5,5}, {5,7,7,7,5}, {7,5,5,5,7},
{6,5,6,4,4}, {6,5,6,5,5}, {7,4,7,1,7}, {7,2,2,2,2},
{5,5,5,5,7}, {5,5,5,5,2}, {5,5,2,2,2}
};
const char* zoneRule() {
if (settings.zone == CUSTOM_ZONE) return settings.customZone;
return zones[settings.zone].rule;
}
void writePanels(uint8_t reg, uint8_t left, uint8_t right) {
digitalWrite(CS_PIN, LOW);
// The ESP32 feeds the right panel. Send the left panel's data first.
shiftOut(DIN_PIN, CLK_PIN, MSBFIRST, reg);
shiftOut(DIN_PIN, CLK_PIN, MSBFIRST, left);
shiftOut(DIN_PIN, CLK_PIN, MSBFIRST, reg);
shiftOut(DIN_PIN, CLK_PIN, MSBFIRST, right);
digitalWrite(CS_PIN, HIGH);
}
void drawPixel(uint8_t x, uint8_t y) {
// Orientation for modules with the black chips below the LEDs.
pixels[x / 8][x % 8] |= 0x80 >> (7 - y);
}
void drawGlyph(const uint8_t rows[5], int startX, int firstX, int lastX) {
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 3; col++) {
const int x = startX + col;
if (x >= firstX && x <= lastX && (rows[row] & (4 >> col))) {
drawPixel(x, row + 1);
}
}
}
}
void drawMonth(int monthIndex, unsigned long elapsed) {
const int startX = 15 - static_cast<int>(elapsed / SCROLL_STEP_MS);
const char* month = months[monthIndex];
for (int letter = 0; letter < 3; letter++) {
const char* match = strchr(monthLetters, month[letter]);
if (match) {
drawGlyph(monthFont[match - monthLetters], startX + letter * 4, 8, 15);
}
}
}
void showClock() {
memset(pixels, 0, sizeof(pixels));
const unsigned long elapsed = millis() - dateStartedAt;
if (showingDate && elapsed >= DATE_DURATION_MS) showingDate = false;
const time_t now = time(nullptr);
struct tm localTime {};
if (now >= MIN_VALID_TIME && localtime_r(&now, &localTime)) {
const int left = showingDate ? localTime.tm_mday : localTime.tm_hour;
drawGlyph(digits[left / 10], 0, 0, 7);
drawGlyph(digits[left % 10], 4, 0, 7);
if (showingDate) {
drawMonth(localTime.tm_mon, elapsed);
} else {
drawGlyph(digits[localTime.tm_min / 10], 9, 8, 15);
drawGlyph(digits[localTime.tm_min % 10], 13, 8, 15);
if (localTime.tm_sec % 2 == 0) {
drawPixel(7, 2);
drawPixel(7, 4);
}
}
} else {
const uint8_t positions[] = {0, 4, 9, 13};
for (uint8_t x : positions) {
for (uint8_t col = 0; col < 3; col++) drawPixel(x + col, 3);
}
}
for (uint8_t row = 0; row < 8; row++) {
writePanels(row + 1, pixels[0][row], pixels[1][row]);
}
}
void sendSetupPage() {
String page = R"HTML(
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Matrix Clock Setup</title>
<style>
body{font:16px system-ui,sans-serif;margin:28px auto;padding:0 16px;max-width:420px}
label{display:block;margin:16px 0}
input,select,button{box-sizing:border-box;width:100%;padding:10px;margin-top:5px;font:inherit}
</style>
</head>
<body>
<h1>Matrix Clock Setup</h1>
<form method="post" action="/save">
<label>Home Wi-Fi name
<input name="ssid" maxlength="32" required></label>
<label>Home Wi-Fi password
<input name="password" type="password" maxlength="64">
</label>
<label>City / time zone
<select name="zone" id="zone">
)HTML";
for (uint8_t i = 0; i < ZONE_COUNT; i++) {
page += "<option value='";
page += String(i);
page += "'";
if (i == settings.zone) page += " selected";
page += ">";
page += zones[i].city;
page += "</option>";
}
page += "<option value='";
page += String(CUSTOM_ZONE);
page += "'";
if (settings.zone == CUSTOM_ZONE) page += " selected";
page += R"HTML(>Other time zone</option>
</select></label>
<label id="customField">Custom POSIX time-zone rule
<input name="customZone" id="customZone" maxlength="95"
placeholder="Example: UTC0"></label>
<button type="submit">Save & connect</button>
</form>
<script>
const zone = document.getElementById('zone');
const field = document.getElementById('customField');
const input = document.getElementById('customZone');
function updateField() {
const custom = zone.selectedIndex === zone.options.length - 1;
field.hidden = !custom;
input.required = custom;
}
zone.addEventListener('change', updateField);
updateField();
</script>
</body>
</html>
)HTML";
server.sendHeader("Cache-Control", "no-store");
server.send(200, "text/html; charset=utf-8", page);
}
void saveSetup() {
if (restartPending) {
server.send(409, "text/plain", "Settings already saved. Restarting.");
return;
}
const String ssid = server.arg("ssid");
const String password = server.arg("password");
const String selection = server.arg("zone");
String customZone = server.arg("customZone");
customZone.trim();
int selected = -1;
for (uint8_t i = 0; i <= CUSTOM_ZONE; i++) {
if (selection == String(i)) selected = i;
}
if (ssid.length() == 0 || ssid.length() > 32 ||
password.length() > 64 || selected < 0 ||
(selected == CUSTOM_ZONE &&
(customZone.length() == 0 || customZone.length() > 95))) {
server.send(400, "text/plain",
"Check the Wi-Fi name, password and time zone, then try again.");
return;
}
Settings next {};
ssid.toCharArray(next.ssid, sizeof(next.ssid));
password.toCharArray(next.password, sizeof(next.password));
if (selected == CUSTOM_ZONE) {
customZone.toCharArray(next.customZone, sizeof(next.customZone));
}
next.zone = static_cast<uint8_t>(selected);
if (preferences.putBytes("settings", &next, sizeof(next)) != sizeof(next)) {
server.send(500, "text/plain", "Could not save settings. Try again.");
return;
}
server.send(200, "text/html; charset=utf-8",
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
"<h1>Settings saved</h1>"
"<p>The clock will restart and connect to your home Wi-Fi.</p>");
restartAt = millis();
restartPending = true;
}
void startSetup() {
if (setupActive) return;
// Run the setup page on the clock's own Wi-Fi network.
WiFi.setAutoReconnect(false);
WiFi.mode(WIFI_AP);
if (!WiFi.softAP(SETUP_SSID, SETUP_PASSWORD)) return;
awaitingWiFi = false;
wasConnected = false;
server.begin();
setupActive = true;
}
void updateButtons() {
static uint8_t lastRaw = 0;
static uint8_t stable = 0;
static unsigned long changedAt = 0;
static unsigned long okPressedAt = 0;
static bool longPressHandled = false;
uint8_t raw = 0;
if (digitalRead(UP_PIN) == LOW) raw |= UP_BUTTON;
if (digitalRead(OK_PIN) == LOW) raw |= OK_BUTTON;
if (digitalRead(DOWN_PIN) == LOW) raw |= DOWN_BUTTON;
const unsigned long now = millis();
if (raw != lastRaw) {
lastRaw = raw;
changedAt = now;
}
if (now - changedAt >= 30 && raw != stable) {
const uint8_t pressed = raw & ~stable;
const uint8_t released = stable & ~raw;
stable = raw;
if (pressed & OK_BUTTON) {
okPressedAt = now;
longPressHandled = false;
}
if ((released & OK_BUTTON) && !longPressHandled &&
time(nullptr) >= MIN_VALID_TIME) {
showingDate = !showingDate;
dateStartedAt = now;
}
if (pressed == UP_BUTTON || pressed == DOWN_BUTTON) {
const int step = pressed == UP_BUTTON ? 1 : -1;
brightness = constrain(brightness + step, 0, 15);
writePanels(0x0A, brightness, brightness);
}
}
if ((stable & OK_BUTTON) && (raw & OK_BUTTON) &&
!longPressHandled && now - okPressedAt >= 3000) {
longPressHandled = true;
startSetup();
}
}
void setup() {
pinMode(DIN_PIN, OUTPUT);
pinMode(CLK_PIN, OUTPUT);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CLK_PIN, LOW);
digitalWrite(CS_PIN, HIGH);
pinMode(UP_PIN, INPUT_PULLUP);
pinMode(OK_PIN, INPUT_PULLUP);
pinMode(DOWN_PIN, INPUT_PULLUP);
writePanels(0x0C, 0, 0);
writePanels(0x0F, 0, 0);
writePanels(0x09, 0, 0);
writePanels(0x0B, 7, 7);
writePanels(0x0A, brightness, brightness);
showClock();
writePanels(0x0C, 1, 1);
preferences.begin("matrixclock", false);
if (preferences.getBytesLength("settings") == sizeof(settings)) {
preferences.getBytes("settings", &settings, sizeof(settings));
}
if (settings.zone > CUSTOM_ZONE) settings.zone = 0;
server.on("/", HTTP_GET, sendSetupPage);
server.on("/save", HTTP_POST, saveSetup);
setenv("TZ", zoneRule(), 1);
tzset();
if (settings.ssid[0] == '\0') {
startSetup();
} else {
WiFi.mode(WIFI_STA);
WiFi.setAutoReconnect(true);
WiFi.begin(settings.ssid, settings.password);
wifiStartedAt = millis();
awaitingWiFi = true;
}
}
void loop() {
updateButtons();
if (setupActive) {
server.handleClient();
} else {
const bool connected = WiFi.status() == WL_CONNECTED;
if (connected && !wasConnected) {
awaitingWiFi = false;
configTzTime(zoneRule(), "pool.ntp.org", "time.cloudflare.com");
}
wasConnected = connected;
if (awaitingWiFi && millis() - wifiStartedAt >= WIFI_TIMEOUT_MS) {
startSetup();
}
}
if (restartPending && millis() - restartAt >= 2000) {
ESP.restart();
}
static unsigned long lastDraw = 0;
if (millis() - lastDraw >= 40) {
lastDraw = millis();
showClock();
}
delay(5);
}