#include <WiFi.h>
#include <WiFiUdp.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
// Set your WiFi credentials
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
// NTP Server details
const char* ntpServer = "pool.ntp.org";
const int ntpPort = 123;
// Time offset in seconds for your timezone
const int timeZoneOffset = 3600; // Example: GMT+1 (1 hour = 3600 seconds)
// LED Matrix configuration
const int numOfModules = 1; // Number of MAX7219 modules connected
const int dataPin = 23; // GPIO23 pin on ESP32
const int clockPin = 18; // GPIO18 pin on ESP32
const int csPin = 5; // GPIO5 pin on ESP32
// Create instances of necessary objects
WiFiUDP udp;
MD_MAX72XX mx = MD_MAX72XX(numOfModules, dataPin, clockPin, csPin);
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize LED Matrix
mx.begin();
mx.control(MD_MAX72XX::INTENSITY, 5); // Set the brightness level (0-15)
// Initialize UDP for NTP
udp.begin(localPort);
// Set time offset
setTimeOffset(timeZoneOffset);
}
void loop() {
// Update the time from NTP server every 60 seconds
static unsigned long lastUpdate = 0;
if (millis() - lastUpdate >= 60000) {
updateTime();
lastUpdate = millis();
}
// Display the current time
displayTime();
}
void updateTime() {
// Get the current time from the NTP server
IPAddress ntpServerIP;
while (udp.parsePacket() > 0)
; // Discard any previously received packets
if (udp.beginPacket(ntpServer, ntpPort)) {
udp.write((byte)0xE3);
udp.write((byte)0x00);
udp.write((byte)0x06);
udp.write((byte)0xEC);
udp.endPacket();
}
while (udp.parsePacket() == 0)
; // Wait until a valid NTP packet is received
byte packetBuffer[48];
udp.read(packetBuffer, 48);
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
unsigned long ntpTime = highWord << 16 | lowWord;
// Set the system time to the received NTP time
setTime(ntpTime);
}
void displayTime() {
// Get the current time
time_t currentTime = now();
// Extract individual time components
int hour = hour(currentTime);
int minute = minute(currentTime);
int second = second(currentTime);
// Format the time as a string
String timeString = String(hour) + ":" +
(minute < 10 ? "0" : "") + String(minute) + ":" +
(second < 10 ? "0" : "") + String(second);
// Display the time on the LED Matrix
mx.clear();
mx.print(timeString.c_str());
mx.commit();
}