Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project: # Time Sync
- - Version: 009
- - Source Code NOT compiled for: ESP32S3 Dev Module
- - Source Code created on: 2026-03-15 23:50:04
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* ESP32-S3 hard reset system clock to 2024-03-16 */
- /* baseline before NTP sync to fix incorrect */
- /* date/time issues, then synchronize with NTP server */
- /* for accurate time */
- /****** SYSTEM REQUIREMENT 2 *****/
- /* Connect to WiFi "二楼" with password "88888888" and */
- /* display accurate HH:MM:SS on 1.8 inch ST7735S */
- /* display in cyan color, updating every second */
- /****** SYSTEM REQUIREMENT 3 *****/
- /* Output detailed time synchronization debug */
- /* information to serial (9600 baud) showing system */
- /* clock reset, NTP sync status, and synchronized */
- /* time */
- /****** END SYSTEM REQUIREMENTS *****/
- /* START CODE */
- // System Requirements:
- // 1. "ESP32-S3 hard reset system clock to 2024-03-16 baseline before NTP sync to fix incorrect date/time issues, then synchronize with NTP server for accurate time"
- // 2. "Connect to WiFi "二楼" with password "88888888" and display accurate HH:MM:SS on 1.8 inch ST7735S display in cyan color, updating every second"
- // 3. "Output detailed time synchronization debug information to serial (9600 baud) showing system clock reset, NTP sync status, and synchronized time"
- // Include core Arduino WiFi and time libraries for network and NTP functionality
- #include <WiFi.h>
- #include <time.h>
- #include <sys/time.h>
- // Include Adafruit graphics and ST7735S display libraries for display support
- #include <Adafruit_GFX.h>
- #include <Adafruit_ST7735.h>
- // Include SPI library for hardware SPI communication with ST7735S display
- #include <SPI.h>
- // WiFi Credentials - Configure with your WiFi network details
- const char* ssid = "二楼";
- const char* password = "88888888";
- // NTP Server Configuration for time synchronization
- const char* ntpServer = "pool.ntp.org";
- const long gmtOffset_sec = 0;
- const long daylightOffset_sec = 0;
- // Hard reset baseline date for system clock (2024-03-16 00:00:00 UTC)
- // This timestamp represents March 16, 2024 at midnight UTC
- // Used to set system clock before NTP sync to ensure valid baseline
- const time_t BASELINE_TIMESTAMP = 1710547200; // 2024-03-16 00:00:00 UTC
- // ST7735S 1.8 inch Display Configuration and pin definitions for ESP32-S3
- // Pin configuration for 1.8 inch ST7735S display with black tab
- // CS (Chip Select): GPIO 5 - Active low, selects the display for SPI communication
- // DC (Data/Command): GPIO 16 - High for data mode, low for command mode
- // RST (Reset): GPIO 15 - Active low reset signal to restart display controller
- // SCLK (Serial Clock): GPIO 18 - SPI clock signal for synchronizing data transfer
- // MOSI (Master Out Slave In): GPIO 11 - Data line from ESP32-S3 to display
- #define TFT_CS 5
- #define TFT_RST 15
- #define TFT_DC 16
- #define TFT_MOSI 11
- #define TFT_SCLK 18
- // Create display object instance for ST7735S communication with proper ESP32-S3 SPI pins
- // Adafruit_ST7735 software SPI constructor takes: (CS, DC, MOSI, SCLK, RST)
- // This creates a 1.8 inch display object that will be initialized with INITR_18BLACKTAB
- Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
- // Global variables for time tracking and display updates
- // lastTimeUpdate: timestamp of last display refresh to control update rate
- // TIME_UPDATE_INTERVAL: milliseconds between display refreshes (1000ms = 1 second)
- unsigned long lastTimeUpdate = 0;
- const unsigned long TIME_UPDATE_INTERVAL = 1000;
- // Function prototypes declaring all functions used in the sketch
- // Allows functions to be called in any order within the file
- void initializeDisplay();
- void resetSystemClock();
- void connectToWiFi();
- void syncTimeWithNTP();
- String getCurrentTimeString();
- String getFormattedTimeString();
- void displayCurrentTime();
- void displayInitializationUI();
- void displayWiFiStatusUI();
- void displayClockResetUI();
- void displayNTPSyncUI();
- void printDebugSeparator();
- // Main setup function - runs once at power on or reset
- // Initializes all hardware, resets system clock, connects to WiFi, syncs time, and starts the main loop
- void setup() {
- // Initialize serial communication for debugging at 9600 baud rate
- // This allows the program to send diagnostic messages to the Serial Monitor
- // Using 9600 baud for compatibility with most serial monitoring tools
- // Delay ensures serial port is ready before sending first message
- Serial.begin(9600);
- delay(2000);
- // Print system startup message with separator for visibility
- printDebugSeparator();
- Serial.println("========== WEATHER STATION INITIALIZATION ==========");
- Serial.println("System startup at: " + String(__TIME__) + " on " + String(__DATE__));
- Serial.println("Target: 1.8\" ST7735S Display, 128x160 pixels");
- Serial.println("WiFi SSID: 二楼");
- Serial.println("NTP Server: pool.ntp.org (UTC+0)");
- Serial.println("System Clock Reset Baseline: 2024-03-16 00:00:00 UTC");
- printDebugSeparator();
- // Initialize SPI interface for ST7735S display communication on ESP32-S3
- // SPI.begin(SCLK, MISO, MOSI, CS) configures the SPI bus with specified pins
- // MISO is -1 because the display is write-only (no data read from display)
- // This sets up VSPI with GPIO 18 (SCLK), GPIO 11 (MOSI), GPIO 5 (CS)
- // ESP32-S3 uses GPIO matrix to dynamically assign pins to SPI peripheral
- SPI.begin(TFT_SCLK, -1, TFT_MOSI, TFT_CS);
- // Initialize and configure ST7735S 1.8 inch display with proper hardware setup
- // This function sets up the display controller with correct initialization sequence
- initializeDisplay();
- // Display initialization message on screen during setup sequence
- // Shows "CLOCK" title and "Initializing..." status to inform user device is starting
- displayInitializationUI();
- // Perform hard reset of system clock to 2024-03-16 baseline before NTP sync
- // This ensures system has valid time reference point for NTP synchronization
- // Without baseline, NTP sync may fail or produce incorrect results
- resetSystemClock();
- // Connect to WiFi network with provided SSID and password credentials
- // Shows WiFi connection status on display and serial monitor
- connectToWiFi();
- // Synchronize system time with NTP server via internet connection
- // Contacts pool.ntp.org and updates ESP32-S3 internal RTC to network time
- syncTimeWithNTP();
- // Display the initial time after all initialization is complete
- // This clears previous setup messages and shows the current time
- displayCurrentTime();
- // Send completion message to serial monitor for debugging
- Serial.println();
- printDebugSeparator();
- Serial.println("Setup complete! System ready for time display.");
- Serial.println("Time display updates every second on ST7735S in cyan color.");
- printDebugSeparator();
- }
- // Main loop function - runs repeatedly during normal operation
- // Continuously updates the time display every second using non-blocking timers
- void loop() {
- // Get current system time in milliseconds since device startup (millis() overflows after ~49 days)
- unsigned long currentMillis = millis();
- // Non-blocking timer check: has enough time elapsed for next update?
- // This approach avoids blocking the loop with delays while still updating every second
- // Only refreshes display when TIME_UPDATE_INTERVAL milliseconds have passed
- if (currentMillis - lastTimeUpdate >= TIME_UPDATE_INTERVAL) {
- // Update last time tracker to current time for next comparison
- lastTimeUpdate = currentMillis;
- // Get current time from system clock and display it on ST7735S
- // This happens once per second due to the interval check above
- displayCurrentTime();
- }
- // Small delay to allow other tasks and prevent watchdog timer from resetting device
- // 100ms delay is short enough to update display smoothly, long enough to save power
- delay(100);
- }
- // Initialize ST7735S 1.8 inch display with proper configuration for black tab variant
- // Sets up display controller with INITR_18BLACKTAB, configures rotation and clears screen
- // This function must be called before any display operations
- void initializeDisplay() {
- // Initialize the ST7735S display controller with 1.8 inch black tab variant
- // INITR_18BLACKTAB is the initialization routine for the specific 1.8 inch model
- // This sends the correct command sequence to the ST7735 controller IC
- // Configures display size to 128x160 pixels with black tab orientation
- tft.initR(INITR_18BLACKTAB);
- // Set display rotation to landscape mode (rotation value 1)
- // Rotation options: 0=portrait (height > width), 1=landscape (width > height)
- // 2=portrait inverted, 3=landscape inverted
- // Rotation 1 gives us 160 pixels wide by 128 pixels tall on this 1.8 inch screen
- tft.setRotation(1);
- // Fill entire display with black background color (RGB 0, 0, 0)
- // This clears any residual data from previous power cycles or display operation
- // Ensures clean, blank slate before displaying any content
- tft.fillScreen(ST7735_BLACK);
- // Send initialization confirmation to serial monitor for debugging
- // Helps verify display initialization succeeded during power-on diagnostics
- Serial.println("[DISPLAY] Initialized: ST7735S 1.8\", 128x160 pixels, landscape mode");
- Serial.println("[DISPLAY] Display rotation: landscape (1)");
- Serial.println("[DISPLAY] Background color: black (0, 0, 0)");
- Serial.println("[DISPLAY] Ready for content output");
- }
- // Display initialization message on ST7735S screen
- // Shows "CLOCK" title and "Initializing..." message during device startup
- // Provides visual feedback to user that device is starting up
- void displayInitializationUI() {
- // Fill screen with black background for clean, professional appearance
- // Removes any previous content and provides contrast for text
- tft.fillScreen(ST7735_BLACK);
- // Set text color to white for maximum contrast against black background
- // White text is easy to read during startup sequence
- tft.setTextColor(ST7735_WHITE);
- // Set text size to 2 (2x magnification from default size)
- // Larger text is more visible and conveys importance of initialization message
- tft.setTextSize(2);
- // Position text cursor at x=15, y=40 for centered title display
- // Sets the starting position for the next text output
- tft.setCursor(15, 40);
- // Print "CLOCK" title on display to identify device function
- tft.println("CLOCK");
- // Reduce text size to 1 for status message below title
- tft.setTextSize(1);
- // Position cursor for status message below the title
- tft.setCursor(20, 75);
- // Print "Initializing..." to show device is in startup process
- tft.println("Initializing...");
- // Wait 1.5 seconds to allow user to see initialization message
- // Prevents screen from changing too quickly during startup sequence
- delay(1500);
- // Send debug message to serial monitor confirming initialization display
- Serial.println("[UI] Initialization screen displayed on ST7735S");
- }
- // Hard reset system clock to 2024-03-16 baseline before NTP synchronization
- // This ensures system has a valid time reference point for NTP sync to work correctly
- // Without this baseline, system clock may be too far in past/future for NTP to process
- void resetSystemClock() {
- // Display clock reset UI on screen to show user what's happening
- displayClockResetUI();
- // Send clock reset start message to serial monitor with timestamp details
- Serial.println();
- printDebugSeparator();
- Serial.println("[CLOCK RESET] Starting hard reset of system clock...");
- Serial.println("[CLOCK RESET] Setting baseline to: 2024-03-16 00:00:00 UTC");
- // Create timeval structure for system time setting
- // timeval contains seconds and microseconds since Unix epoch
- struct timeval tv;
- // Set seconds to baseline timestamp (2024-03-16 00:00:00 UTC)
- tv.tv_sec = BASELINE_TIMESTAMP;
- // Set microseconds to zero for clean baseline
- tv.tv_usec = 0;
- // Get current system time before reset for comparison in debug output
- time_t timeBeforeReset = time(nullptr);
- struct tm* tmBeforeReset = localtime(&timeBeforeReset);
- // Print current system time before reset
- Serial.print("[CLOCK RESET] Time BEFORE reset: ");
- Serial.println(asctime(tmBeforeReset));
- // Perform actual system clock reset using settimeofday()
- // This sets the ESP32-S3 internal RTC to the baseline timestamp
- // Returns 0 on success, -1 on failure (should always succeed on ESP32-S3)
- int resetResult = settimeofday(&tv, NULL);
- // Check if clock reset was successful
- if (resetResult == 0) {
- // Clock reset succeeded - get new time and display it
- Serial.println("[CLOCK RESET] System clock reset successful!");
- // Small delay to allow clock update to take effect
- delay(100);
- // Get system time after reset for verification
- time_t timeAfterReset = time(nullptr);
- struct tm* tmAfterReset = localtime(&timeAfterReset);
- // Print system time after reset for verification
- Serial.print("[CLOCK RESET] Time AFTER reset: ");
- Serial.println(asctime(tmAfterReset));
- // Calculate and display time difference for verification
- long timeDifference = timeAfterReset - timeBeforeReset;
- Serial.print("[CLOCK RESET] Time adjustment: ");
- Serial.print(timeDifference);
- Serial.println(" seconds");
- } else {
- // Clock reset failed - send error message
- Serial.println("[CLOCK RESET] ERROR: System clock reset failed!");
- Serial.println("[CLOCK RESET] NTP sync may not work correctly");
- }
- Serial.println("[CLOCK RESET] Baseline clock reset complete, ready for NTP sync");
- printDebugSeparator();
- }
- // Display clock reset status message on ST7735S screen
- // Shows user that system clock is being reset to baseline value
- // This UI appears during the clock reset operation before NTP sync
- void displayClockResetUI() {
- // Fill screen with black background for clean display
- tft.fillScreen(ST7735_BLACK);
- // Set text color to yellow to indicate reset operation in progress
- // Yellow provides good visibility and indicates a state-change operation
- tft.setTextColor(ST7735_YELLOW);
- // Set text size to 2 for prominent message
- tft.setTextSize(2);
- tft.setCursor(10, 40);
- // Print "CLOCK" label on display
- tft.println("CLOCK");
- // Reduce text size to 1 for status message below title
- tft.setTextSize(1);
- tft.setTextColor(ST7735_WHITE);
- tft.setCursor(10, 75);
- // Print "Resetting..." message
- tft.println("Resetting to");;
- tft.setCursor(10, 85);
- tft.println("2024-03-16...");
- // Display reset message for visibility during operation
- delay(1500);
- // Send debug message to serial monitor
- Serial.println("[UI] Clock reset screen displayed on ST7735S");
- }
- // Connect ESP32-S3 to WiFi network with credential verification
- // Attempts WiFi connection with timeout, displays status on screen and serial monitor
- // Handles both success and failure cases with appropriate visual feedback
- void connectToWiFi() {
- // Clear screen with black background to prepare for WiFi connection display
- tft.fillScreen(ST7735_BLACK);
- // Display WiFi connection attempt message and animation on screen
- displayWiFiStatusUI();
- // Send WiFi connection attempt message to serial monitor for debugging
- Serial.println();
- printDebugSeparator();
- Serial.println("[WiFi] Attempting WiFi connection...");
- Serial.print("[WiFi] SSID: ");
- Serial.println(ssid);
- Serial.print("[WiFi] Password: ");
- Serial.println(password);
- // Set WiFi mode to STA (Station) to enable connection to existing WiFi network
- // STA mode allows ESP32-S3 to connect as a client to access point (router)
- WiFi.mode(WIFI_STA);
- // Initiate WiFi connection with network SSID and password
- // WiFi.begin() starts the connection process but does not wait for completion
- WiFi.begin(ssid, password);
- // Wait for WiFi connection with timeout to prevent indefinite blocking
- // Maximum wait: 40 attempts × 500ms = 20 seconds
- // If connection fails after timeout, proceed to next step anyway
- int attempts = 0;
- Serial.print("[WiFi] Connection progress: ");
- while (WiFi.status() != WL_CONNECTED && attempts < 40) {
- delay(500);
- // Print dot to serial monitor to show connection attempt progress
- Serial.print(".");
- attempts++;
- }
- Serial.println();
- // Check if WiFi connection succeeded by examining WiFi status
- if (WiFi.status() == WL_CONNECTED) {
- // WiFi connection successful - send detailed information to serial monitor
- Serial.println("[WiFi] WiFi connected successfully!");
- Serial.print("[WiFi] Connection attempts: ");
- Serial.println(attempts);
- Serial.print("[WiFi] Assigned IP address: ");
- Serial.println(WiFi.localIP());
- Serial.print("[WiFi] Signal strength (RSSI): ");
- Serial.print(WiFi.RSSI());
- Serial.println(" dBm");
- // Clear screen and display WiFi success message in green color
- tft.fillScreen(ST7735_BLACK);
- tft.setTextColor(ST7735_GREEN);
- tft.setTextSize(2);
- tft.setCursor(10, 50);
- tft.println("WiFi OK");
- // Display assigned IP address on screen below success message
- tft.setTextSize(1);
- tft.setTextColor(ST7735_WHITE);
- tft.setCursor(10, 80);
- tft.print("IP:");
- tft.setCursor(10, 90);
- tft.println(WiFi.localIP());
- // Display WiFi success message for 2 seconds before proceeding to NTP sync
- delay(2000);
- } else {
- // WiFi connection failed after timeout - send error message to serial monitor
- Serial.println("[WiFi] ERROR: Failed to connect to WiFi network");
- Serial.print("[WiFi] Connection attempts: ");
- Serial.println(attempts);
- Serial.print("[WiFi] WiFi status code: ");
- Serial.println(WiFi.status());
- // Clear screen and display failure message in red color
- tft.fillScreen(ST7735_BLACK);
- tft.setTextColor(ST7735_RED);
- tft.setTextSize(2);
- tft.setCursor(10, 50);
- tft.println("WiFi FAIL");
- // Display troubleshooting message below failure message
- tft.setTextSize(1);
- tft.setTextColor(ST7735_WHITE);
- tft.setCursor(10, 80);
- tft.println("Check SSID/PWD");
- // Display failure message for 2 seconds before proceeding
- // Device continues to operate without WiFi connection if NTP sync not required
- delay(2000);
- }
- printDebugSeparator();
- }
- // Display WiFi connection status message during connection attempt
- // Shows user that device is attempting to connect to WiFi network
- // This UI appears while the WiFi connection is in progress
- void displayWiFiStatusUI() {
- // Set text color to white for good visibility against black background
- tft.setTextColor(ST7735_WHITE);
- // Set larger text size (2) for title emphasis
- // Size 2 provides 2x magnification from default character size
- tft.setTextSize(2);
- tft.setCursor(10, 40);
- // Print "WiFi" label on display
- tft.println("WiFi");
- // Reduce text size to 1 for status message below title
- tft.setTextSize(1);
- tft.setCursor(20, 75);
- // Print "Connecting..." to show WiFi connection is in progress
- tft.println("Connecting...");
- }
- // Synchronize system time with NTP server via internet connection
- // Sets system clock to match NTP server time, displays status on screen
- // This ensures accurate time display synchronized with network time protocol
- void syncTimeWithNTP() {
- // Display NTP synchronization status on screen to inform user
- displayNTPSyncUI();
- // Send NTP sync start message to serial monitor for debugging
- Serial.println();
- printDebugSeparator();
- Serial.println("[NTP] Starting NTP time synchronization...");
- Serial.print("[NTP] NTP Server: ");
- Serial.println(ntpServer);
- Serial.print("[NTP] GMT Offset: ");
- Serial.print(gmtOffset_sec);
- Serial.println(" seconds");
- Serial.print("[NTP] Daylight Offset: ");
- Serial.print(daylightOffset_sec);
- Serial.println(" seconds");
- // Get time before NTP sync for comparison
- time_t timeBefore = time(nullptr);
- struct tm* tmBefore = localtime(&timeBefore);
- Serial.print("[NTP] Time BEFORE sync: ");
- Serial.println(asctime(tmBefore));
- // Configure time synchronization with NTP server and timezone offset
- // configTime() sets up time sync with specified NTP server
- // gmtOffset_sec: offset from UTC in seconds (0 = UTC+0)
- // daylightOffset_sec: daylight saving time offset in seconds (0 = none)
- configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
- // Wait for time to be synchronized from NTP server with timeout
- Serial.print("[NTP] Sync progress: ");
- time_t now = time(nullptr);
- int attempts = 0;
- // Poll system time until it's been set from NTP server
- // time_t value > 86400 (24 hours) indicates time has been updated from network
- // Wait maximum 50 attempts × 500ms = 25 seconds for NTP response
- while (now < 24 * 3600 && attempts < 50) {
- delay(500);
- // Print dot to serial monitor showing sync attempt progress
- Serial.print(".");
- now = time(nullptr);
- attempts++;
- }
- // Print newline to complete serial monitor output formatting
- Serial.println();
- // Check if NTP sync was successful
- if (now > 24 * 3600) {
- // NTP sync successful - get and display synchronized time
- Serial.println("[NTP] NTP synchronization successful!");
- // Get current synchronized time and display in human-readable format
- struct tm timeinfo = *localtime(&now);
- Serial.print("[NTP] Time AFTER sync: ");
- Serial.println(asctime(&timeinfo));
- // Display detailed time breakdown
- Serial.print("[NTP] Synced Date: ");
- Serial.printf("%04d-%02d-%02d ",
- timeinfo.tm_year + 1900,
- timeinfo.tm_mon + 1,
- timeinfo.tm_mday);
- Serial.printf("Time: %02d:%02d:%02d UTC\n",
- timeinfo.tm_hour,
- timeinfo.tm_min,
- timeinfo.tm_sec);
- // Calculate time difference between before and after
- long timeDifference = now - timeBefore;
- Serial.print("[NTP] Sync attempts needed: ");
- Serial.println(attempts);
- Serial.print("[NTP] Time difference: ");
- Serial.print(timeDifference);
- Serial.println(" seconds");
- // Display NTP sync success on ST7735S screen in green color
- tft.fillScreen(ST7735_BLACK);
- tft.setTextColor(ST7735_GREEN);
- tft.setTextSize(2);
- tft.setCursor(15, 50);
- // Print "NTP SYNC" label on display
- tft.println("NTP SYNC");
- // Display confirmation message below title in white text
- tft.setTextSize(1);
- tft.setTextColor(ST7735_WHITE);
- tft.setCursor(20, 85);
- // Print "Time acquired" message
- tft.println("Time acquired");
- } else {
- // NTP sync failed - send error message
- Serial.println("[NTP] ERROR: NTP synchronization timeout!");
- Serial.print("[NTP] Sync attempts made: ");
- Serial.println(attempts);
- Serial.println("[NTP] Current system time may be inaccurate");
- // Display NTP sync failure on screen in red color
- tft.fillScreen(ST7735_BLACK);
- tft.setTextColor(ST7735_RED);
- tft.setTextSize(2);
- tft.setCursor(20, 50);
- // Print "NTP FAIL" label on display
- tft.println("NTP FAIL");
- // Display error message below title
- tft.setTextSize(1);
- tft.setTextColor(ST7735_WHITE);
- tft.setCursor(20, 85);
- // Print failure reason
- tft.println("Timeout");
- }
- // Display NTP result message for 1.5 seconds before clearing to show time
- delay(1500);
- Serial.println("[NTP] NTP synchronization phase complete");
- printDebugSeparator();
- }
- // Display NTP synchronization in progress message on screen
- // Shows user that device is synchronizing time with NTP server
- // This UI appears while waiting for NTP time synchronization to complete
- void displayNTPSyncUI() {
- // Fill screen with black background for clean display appearance
- tft.fillScreen(ST7735_BLACK);
- // Set text color to white for good contrast against black background
- tft.setTextColor(ST7735_WHITE);
- // Set text size to 2 for larger, more visible title
- tft.setTextSize(2);
- tft.setCursor(15, 40);
- // Print "NTP" label on display
- tft.println("NTP");
- // Reduce text size to 1 for status message below title
- tft.setTextSize(1);
- tft.setCursor(20, 75);
- // Print "Syncing time..." message to show NTP sync is in progress
- tft.println("Syncing time...");
- }
- // Get current time as formatted HH:MM:SS string from system clock
- // Returns time string synchronized via NTP from the system's internal RTC
- // Format produces zero-padded two-digit hours, minutes, and seconds (e.g., "09:05:03")
- String getCurrentTimeString() {
- // Get current time from system clock (synchronized via NTP during setup)
- // time(nullptr) returns seconds elapsed since Unix epoch (January 1, 1970 00:00:00 UTC)
- // This value is updated continuously by system RTC after NTP sync
- time_t now = time(nullptr);
- // Convert time_t value to local time structure with hour, minute, second fields
- // localtime() applies configured timezone offsets to create local time representation
- // Returns pointer to static tm structure containing breakdown of time
- struct tm* timeinfo = localtime(&now);
- // Create character buffer to hold formatted time string
- // Buffer size 9: 8 characters for "HH:MM:SS" + 1 null terminator
- char timeString[9];
- // Format time as HH:MM:SS with zero-padding for single-digit values
- // %02d ensures always two digits, padding with leading zero if needed
- // Examples: 09:05:03 (correct), NOT 9:5:3 (would be without padding)
- // sprintf safely formats the string into the buffer with conversion specifiers
- sprintf(timeString, "%02d:%02d:%02d",
- timeinfo->tm_hour, // Hours (0-23): midnight=0, noon=12, 11PM=23
- timeinfo->tm_min, // Minutes (0-59): from 00 to 59
- timeinfo->tm_sec); // Seconds (0-59): from 00 to 59
- // Convert character array to String object for display compatibility
- // String class provides convenient handling for display operations
- return String(timeString);
- }
- // Get current date and time as full formatted string with date and time details
- // Returns formatted string like "2024-03-16 12:34:56"
- String getFormattedTimeString() {
- // Get current time from system clock
- time_t now = time(nullptr);
- // Convert to local time structure
- struct tm* timeinfo = localtime(&now);
- // Create character buffer for formatted date-time string
- char buffer[20];
- // Format as YYYY-MM-DD HH:MM:SS for detailed display
- sprintf(buffer, "%04d-%02d-%02d %02d:%02d:%02d",
- timeinfo->tm_year + 1900, // Year (add 1900 since tm stores years since 1900)
- timeinfo->tm_mon + 1, // Month (add 1 since tm stores months 0-11)
- timeinfo->tm_mday, // Day of month (1-31)
- timeinfo->tm_hour, // Hour (0-23)
- timeinfo->tm_min, // Minute (0-59)
- timeinfo->tm_sec); // Second (0-59)
- return String(buffer);
- }
- // Update and display current time on ST7735S screen
- // Gets current time from system clock and displays it in cyan color
- // Called every second (via TIME_UPDATE_INTERVAL) to continuously show current time
- void displayCurrentTime() {
- // Get formatted current time string in HH:MM:SS format from system clock
- // This function calls getCurrentTimeString() to get properly formatted time
- String timeStr = getCurrentTimeString();
- // Get full formatted time string for serial debug output
- String fullTimeStr = getFormattedTimeString();
- // Clear only the time display area to avoid flickering entire screen
- // fillRect(x, y, width, height, color) erases rectangular region
- // Coordinates: x=0, y=0 (top-left), width=128 (full width), height=50 (top half)
- // This preserves any content below the time display area
- tft.fillRect(0, 0, 128, 50, ST7735_BLACK);
- // Set text color to cyan (bright blue-green, RGB: 0, 255, 255)
- // Cyan provides excellent contrast against black background
- // Creates modern, clean appearance for time display
- tft.setTextColor(ST7735_CYAN);
- // Set large text size (2) for prominent time display
- // Size 2 means 2x magnification of default character dimensions
- // Each character becomes taller and wider for better visibility
- tft.setTextSize(2);
- // Position time at top-center of display for maximum visibility
- // setCursor(x, y) sets starting position for next text output
- // X position 18 centers the 8-character time string horizontally
- // Y position 15 places it near the top of display with small margin
- tft.setCursor(18, 15);
- // Print the time string in HH:MM:SS format to the ST7735S display
- // println() outputs the string and moves cursor to next line
- tft.println(timeStr);
- // Send current time to serial monitor for debugging and verification
- Serial.print("[DISPLAY] Time updated: ");
- Serial.println(fullTimeStr);
- }
- // Print debug separator line for serial output organization
- // Makes serial debug output more readable by separating sections with clear markers
- void printDebugSeparator() {
- // Print a line of dashes to visually separate debug sections
- Serial.println("====================================================");
- }
- /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment