element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products & Partners
    Products & Partners
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
    About the element14 Community
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      •  Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
My Project Is Trash
  • Challenges & Projects
  • Design Challenges
  • My Project Is Trash
  • More
  • Cancel
My Project Is Trash
Forum TRS-06: Lights, a Clock & Spaghetti fit for a Lil’ Raccoon
  • News
  • Forum
  • Projects
  • Enroll
  • Leaderboard
  • Files
  • Members
  • More
  • Cancel
  • New
Join My Project Is Trash to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • Replies 0 replies
  • Subscribers 2 subscribers
  • Views 2 views
  • Users 0 members are here
  • esp32
  • TRASH_PROJECT_NAME
  • camdenboss
  • raspberry pi pico
  • drilling
  • 3D Printing
  • my-project-is-trash
  • soldering
  • hammond
  • design-challenge
Related

TRS-06: Lights, a Clock & Spaghetti fit for a Lil’ Raccoon

Gough Lui
Gough Lui 12 minutes ago

In the last post, I focused on getting the Analog Devices CN0569 evaluation kit running as a proximity sensor for my project. Since then, the raccoons have been busy being hands-on, trying to get parts of the system built in time for the looming deadline.

image

That being said, the raccoons did not account for the fact the end-of-year is a busy time with a number of commitments, nor did they account for the fact that Sydney is under a heatwave, having sweltered through at least three days of 35°C or above temperatures, reaching 40°C on one day, without much reprieve in sight in the coming weeks. Too bad raccoons only have limited access to air conditioning … they can only afford so much electricity from returning plastic bottles and must otherwise hide in cool shady corners whenever they can.

What’s the Time, Mr. Wolf?

For the main system that would remain inside the house, monitoring the bins, I decided that it would be important to have a time display, because if all-else-fails, at least I can say I’ve built a clock! As I had the old failed project of a display for my U1461 multimeter based around a monochrome LCD and a Raspberry Pi Pico W (RP2040 platform), I decided to convert this into a clock.

My requirements were simple – a clock that never needed to be set, which would connect via Wi-Fi and fetch time from NTP from a local time-server on my network every 15 minutes or so, falling back to an internet time-server only if the local server was not reachable (I like to be a good citizen and not burden the volunteer NTP servers online where possible). If it was using an internet time-server, a small pixel in the bottom left would be made dark to indicate this. It should be aware of time-zones and adjust automatically for daylight savings time in Sydney, Australia. It would be nice of it to display the day-of-the-week, date, month, year and UTC time as well.

Because this clock is “independent” of the remainder of the system, it will function with just power. The main reason I chose to do this is because of limited primary display real-estate – if the main display had to also display the date and time, the font would get quite small and it would be a challenge to fit it all in. So instead, the system would comprise of two screens – the bottom of which is always dedicated to time. Rather than try to desolder the display from an already completed and working assembly and struggle to fan-out an SPI interface to two displays from one microcontroller (with the risk of signal integrity issues), I’ll instead take it for granted that if both boards are synchronised to NTP, they’ll both be “in-sync” enough that there’s no real need for the two systems to communicate between each other.

image

I drew a rough sketch – that would be my “bin-ssion control” concept. I already had an early basic clock sketch, but I decided to ask ChatGPT’s GPT-6 Luna to spruce it up a bit by rendering a custom font to better utilise the screen real-estate, to implement time-zone awareness and to implement an animated “flying pixel” across the top to indicate each second as it passed.

[[PicoW_ST7565_NetworkClock_AnimatedTopPixel.ino]]

// Raspberry Pi Pico W + ST7565-based Monochrome LCD NTP Network Clock
// by Gough Lui for element14 Communities "My Project is Trash" Design
// Challenge Nov 2026

// Repurposes an old board intended for U1461 display replacement, but
// did not consider the Z-height issue, thus the intended design would
// not fit in the case. Instead, now repurposed as a time display.

// AI Disclosure: OpenAI ChatGPT GPT-6 Luna was used to implement an
// NTP client for this sketch and to rasterise a free font for the
// display. Sketch Wi-Fi functionality and U8g2 configurations were
// hand-done by me. Use of an existing NTP library is possible, but was
// not taken because of its undefined server fail-over characteristics.

#include <WiFi.h>
#include <WiFiUdp.h>
#include <SPI.h>
#include <U8g2lib.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

U8G2_ST7565_NHD_C12864_F_4W_HW_SPI u8g2(
    U8G2_R2,
     17,
     26,
     27
); // Values for my particular board and screen combination

const char* WIFI_SSID = "YOUR_SSID";
const char* WIFI_PASSWORD = "YOUR_PASSWORD";
const char* NTP_SERVER_PRIMARY = "YOUR_LOCAL_NTP_SERVER";
const char* NTP_SERVER_BACKUP = "pool.ntp.org";
const char* TIMEZONE = "AEST-10AEDT,M10.1.0,M4.1.0/3";
const unsigned long WIFI_RETRY_INTERVAL_MS = 15000UL;
const unsigned long NTP_RETRY_INTERVAL_MS = 60000UL;
const int DNS_TIMEOUT_MS = 5000;
const unsigned long NTP_SYNC_INTERVAL_MS = 15UL * 60UL * 1000UL;
const uint16_t NTP_LOCAL_PORT = 2390;
const uint16_t NTP_SERVER_PORT = 123;
const uint8_t NTP_PACKET_SIZE = 48;
const uint32_t NTP_UNIX_OFFSET = 2208988800UL;
const time_t MIN_VALID_TIMESTAMP = 1700000000;

const int DISPLAY_WIDTH = 128;
const int DISPLAY_HEIGHT = 64;
const int DIVIDER_X = 80;
const int LEFT_WIDTH = 79;
const int LEFT_CENTER_X = LEFT_WIDTH / 2;
const int RIGHT_CENTER_X = 103;
const int RIGHT_TEXT_WIDTH = 44;
const int UTC_DIVIDER_Y = 49;
const uint32_t ANIMATION_TRAVEL_MS = 950UL;

bool wifiWasConnected = false;
unsigned long lastWiFiAttemptMs = 0;

WiFiUDP ntpUdp;
bool ntpUdpReady = false;
bool ntpUdpBeginAttempted = false;
uint8_t activeNtpServer = 0;
uint8_t lastSuccessfulNtpServer = 0;
bool ntpEverSynced = false;
bool ntpRequestPending = false;
bool ntpPacketSent = false;
unsigned long ntpRequestStartedMs = 0;
unsigned long lastUdpBeginAttemptMs = 0;
unsigned long lastSuccessfulNtpSyncMs = 0;
IPAddress activeNtpServerIP;

int lastDisplayedSecond = -1;
unsigned long lastWaitingDisplayMs = 0;
int lastAnimationPixelX = -1;

void startNtpAttempt(uint8_t serverIndex);
bool processNtpResponse();
void drawWaitingDisplay();
void updateDisplay();

bool isTimeValid() {
    return time(nullptr) > MIN_VALID_TIMESTAMP;
}

void startWiFi() {
    Serial.println();
    Serial.println("Starting Wi-Fi...");

    WiFi.mode(WIFI_STA);

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    lastWiFiAttemptMs = millis();
}

void maintainWiFi() {
    if (WiFi.status() == WL_CONNECTED) {
        if (!wifiWasConnected) {
            wifiWasConnected = true;
            Serial.println();
            Serial.println("Wi-Fi connected!");
            Serial.print("IP address: ");
            Serial.println(WiFi.localIP());
        }
        return;
    }

    if (wifiWasConnected) {
        wifiWasConnected = false;
        Serial.println();
        Serial.println("Wi-Fi connection lost.");
    }

    unsigned long now = millis();

    if (now - lastWiFiAttemptMs >= WIFI_RETRY_INTERVAL_MS) {
        Serial.println("Retrying Wi-Fi...");
        WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
        lastWiFiAttemptMs = now;
    }
}

const char* getNtpServerName(uint8_t serverIndex) {
    return (serverIndex == 0)
        ? NTP_SERVER_PRIMARY
        : NTP_SERVER_BACKUP;
}

void clearNtpPackets() {
    while (ntpUdp.parsePacket() > 0) {
        while (ntpUdp.available() > 0) {
            ntpUdp.read();
        }
    }
}

void startNtpAttempt(uint8_t serverIndex) {
    if (WiFi.status() != WL_CONNECTED || !ntpUdpReady) {
        return;
    }

    activeNtpServer = (serverIndex == 0) ? 0 : 1;

    ntpRequestPending = true;
    ntpPacketSent = false;

    const char* serverName = getNtpServerName(activeNtpServer);

    Serial.println();
    Serial.println("Starting NTP request...");
    Serial.print("Selected server: ");
    Serial.println(activeNtpServer == 0 ? "PRIMARY" : "BACKUP");
    Serial.print("Server address: ");
    Serial.println(serverName);

    IPAddress serverIP;

    if (!serverIP.fromString(serverName)) {
        int dnsResult = WiFi.hostByName(
            serverName,
            serverIP,
            DNS_TIMEOUT_MS
        );

        if (dnsResult != 1) {
            Serial.println("NTP DNS lookup failed.");
            ntpRequestStartedMs = millis();
            return;
        }
    }

    activeNtpServerIP = serverIP;

    Serial.print("Resolved server IP: ");
    Serial.println(activeNtpServerIP);

    clearNtpPackets();

    uint8_t packet[NTP_PACKET_SIZE] = {0};
    packet[0] = 0x23;

    if (ntpUdp.beginPacket(serverIP, NTP_SERVER_PORT) != 1) {
        Serial.println("Unable to start UDP packet.");
        ntpRequestStartedMs = millis();
        return;
    }

    size_t bytesWritten = ntpUdp.write(packet, NTP_PACKET_SIZE);
    int sendResult = ntpUdp.endPacket();

    if (bytesWritten != NTP_PACKET_SIZE || sendResult != 1) {
        Serial.println("NTP UDP transmission failed.");
        ntpRequestStartedMs = millis();
        return;
    }

    ntpPacketSent = true;
    ntpRequestStartedMs = millis();

    Serial.println("NTP request transmitted.");
}

bool processNtpResponse()
{   // Direct NTP parsing to allow for fail-over mechanism
    int packetSize = ntpUdp.parsePacket();

    if (packetSize <= 0)
    {
        return false;
    }

    if (packetSize < NTP_PACKET_SIZE)
    {
        while (ntpUdp.available() > 0)
        {
            ntpUdp.read();
        }
        return false;
    }

    uint8_t packet[NTP_PACKET_SIZE];
    int bytesRead = ntpUdp.read(packet, NTP_PACKET_SIZE);

    while (ntpUdp.available() > 0)
    {
        ntpUdp.read();
    }

    if (bytesRead != NTP_PACKET_SIZE)
    {
        return false;
    }

    if (ntpUdp.remotePort() != NTP_SERVER_PORT ||
        ntpUdp.remoteIP() != activeNtpServerIP)
    {
        Serial.println("Ignoring response from unexpected source.");
        return false;
    }

    uint8_t leapIndicator = (packet[0] >> 6) & 0x03;
    uint8_t version = (packet[0] >> 3) & 0x07;
    uint8_t mode = packet[0] & 0x07;
    uint8_t stratum = packet[1];

    if (mode != 4 || version < 3)
    {
        Serial.println("Invalid NTP response mode/version.");
        return false;
    }

    if (leapIndicator == 3)
    {
        Serial.println("NTP server reports unsynchronised time.");
        return false;
    }

    if (stratum == 0 || stratum > 15)
    {
        Serial.println("Invalid NTP server stratum.");
        return false;
    }

    uint32_t ntpSeconds =
        ((uint32_t)packet[40] << 24) |
        ((uint32_t)packet[41] << 16) |
        ((uint32_t)packet[42] << 8)  |
        ((uint32_t)packet[43]);

    uint32_t ntpFraction =
        ((uint32_t)packet[44] << 24) |
        ((uint32_t)packet[45] << 16) |
        ((uint32_t)packet[46] << 8)  |
        ((uint32_t)packet[47]);

    if (ntpSeconds <= NTP_UNIX_OFFSET)
    {
        Serial.println("Invalid NTP timestamp.");
        return false;
    }

    uint64_t unixSeconds =
        (uint64_t)ntpSeconds - NTP_UNIX_OFFSET;

    if (unixSeconds < (uint64_t)MIN_VALID_TIMESTAMP)
    {
        Serial.println("NTP timestamp is too old.");
        return false;
    }

    uint32_t microseconds = (uint32_t)(
        ((uint64_t)ntpFraction * 1000000ULL) >> 32
    );

    struct timeval tv;
    tv.tv_sec = (time_t)unixSeconds;
    tv.tv_usec = (suseconds_t)microseconds;

    if (settimeofday(&tv, nullptr) != 0)
    {
        Serial.println("Unable to set system clock.");
        return false;
    }

    ntpRequestPending = false;
    ntpPacketSent = false;
    ntpEverSynced = true;
    lastSuccessfulNtpServer = activeNtpServer;
    lastSuccessfulNtpSyncMs = millis();

    Serial.println();
    Serial.println("NTP synchronisation successful!");
    Serial.print("Successful server: ");
    Serial.println(getNtpServerName(lastSuccessfulNtpServer));
    Serial.print("Unix timestamp: ");
    Serial.println((long)time(nullptr));

    lastDisplayedSecond = -1;

    return true;
}

void maintainNTP() {
    unsigned long now = millis();
    if (WiFi.status() != WL_CONNECTED) {
        if (ntpUdpReady) {
            ntpUdp.stop();
            ntpUdpReady = false;
        }
        ntpUdpBeginAttempted = false;
        ntpRequestPending = false;
        ntpPacketSent = false;
        return;
    }

    if (!ntpUdpReady) {
        if (!ntpUdpBeginAttempted ||
            now - lastUdpBeginAttemptMs >= 5000UL) {
            ntpUdpBeginAttempted = true;
            lastUdpBeginAttemptMs = now;
            Serial.println("Initialising NTP UDP socket...");
            if (ntpUdp.begin(NTP_LOCAL_PORT)) {
                ntpUdpReady = true;
                Serial.println("NTP UDP socket ready.");
                startNtpAttempt(0);
            } else {
                Serial.println("NTP UDP socket initialisation failed.");
            }
        }
        return;
    }

    if (ntpRequestPending) {
        if (ntpPacketSent && processNtpResponse()) {
            return;
        }
        if (now - ntpRequestStartedMs >= NTP_RETRY_INTERVAL_MS) {
            Serial.println();
            Serial.println("NTP server timed out.");
            uint8_t nextServer = (activeNtpServer == 0) ? 1 : 0;
            Serial.print("Switching to ");
            Serial.println(nextServer == 0 ? "PRIMARY server." : "BACKUP server.");
            startNtpAttempt(nextServer);
        }
        return;
    }
    if (!ntpEverSynced) {
        startNtpAttempt(0);
        return;
    }
    if (now - lastSuccessfulNtpSyncMs >= NTP_SYNC_INTERVAL_MS) {
        Serial.println();
        Serial.println("NTP watchdog triggered; checking primary server.");
        startNtpAttempt(0);
    }
}

void drawCentered(
    const char* text,
    const uint8_t* font,
    int centerX,
    int baselineY
)
{
    u8g2.setFont(font);

    int textWidth = u8g2.getStrWidth(text);
    int startX = centerX - textWidth / 2;

    u8g2.drawStr(startX, baselineY, text);
}

/*  Purpose-built bold monospaced clock glyphs, rasterised
  from DejaVu Sans Mono Bold and embedded in the sketch.
  Each glyph is 13 x 26 pixels, with a 15-pixel character
  advance. Five characters therefore occupy 73 pixels.

  DejaVu Sans is derived from Bitstream Vera.
  Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.
  DejaVu changes are in the public domain.
  Bitstream Vera is a trademark of Bitstream, Inc.

  Bitstream Vera license:

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of the fonts accompanying this license
  ("Fonts") and associated documentation files (the "Font
  Software"), to reproduce and distribute the Font Software,
  including without limitation the rights to use, copy, merge,
  publish, distribute, and/or sell copies of the Font Software,
  and to permit persons to whom the Font Software is furnished
  to do so, subject to the following conditions:

  The above copyright and trademark notices and this permission
  notice shall be included in all copies of one or more of the
  Font Software typefaces.

  The Font Software may be modified, altered, or added to, and
  in particular the designs of glyphs or characters in the Fonts
  may be modified and additional glyphs or characters may be added
  to the Fonts, only if the fonts are renamed to names not containing
  either the words "Bitstream" or the word "Vera".

  This License becomes null and void to the extent applicable to
  Fonts or Font Software that has been modified and is distributed
  under the "Bitstream Vera" names.

  The Font Software may be sold as part of a larger software package
  but no copy of one or more of the Font Software typefaces may be
  sold by itself.

  THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
  OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
  BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR
  OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL,
  OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT
  SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.

  Except as contained in this notice, the names of GNOME, the GNOME
  Foundation, and Bitstream Inc. shall not be used in advertising or
  otherwise to promote the sale, use or other dealings in this Font
  Software without prior written authorisation.

  Full license: https://dejavu-fonts.github.io/License.html
*/

static const char CLOCK_GLYPH_CHARS[] = "0123456789:APM";
static const uint8_t CLOCK_GLYPHS[][52] = {
    {
        0x00, 0x00, 0xE0, 0x00, 0xF0, 0x03, 0xF8, 0x03, 0xFC, 0x07, 0xBC, 0x07, 0x1C,
        0x07, 0x1C, 0x0F, 0x1C, 0x0F, 0x1E, 0x0E, 0x5E, 0x0E, 0xCE, 0x0E, 0xEE, 0x0E,
        0xCE, 0x0E, 0x4E, 0x0E, 0x1E, 0x0E, 0x1E, 0x0E, 0x1C, 0x0F, 0x1C, 0x0F, 0x1C,
        0x07, 0xBC, 0x07, 0xFC, 0x07, 0xF8, 0x03, 0xF0, 0x03, 0xE0, 0x00, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xF0, 0x01, 0xFC, 0x01, 0xFC, 0x01, 0xFC, 0x01, 0xEC, 0x01, 0xC0,
        0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x01,
        0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0,
        0x01, 0xE0, 0x01, 0xFC, 0x0F, 0xFC, 0x0F, 0xFC, 0x0F, 0xFC, 0x0F, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xF8, 0x00, 0xFC, 0x03, 0xFC, 0x03, 0xFC, 0x07, 0x84, 0x07, 0x00,
        0x07, 0x00, 0x07, 0x00, 0x07, 0x00, 0x07, 0x00, 0x07, 0x80, 0x07, 0x80, 0x03,
        0xC0, 0x01, 0xE0, 0x01, 0xE0, 0x00, 0xF0, 0x00, 0x70, 0x00, 0x38, 0x00, 0x1C,
        0x00, 0x1C, 0x00, 0xFE, 0x07, 0xFE, 0x07, 0xFE, 0x07, 0xFE, 0x07, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xF8, 0x01, 0xFC, 0x03, 0xFC, 0x07, 0xFC, 0x07, 0x8C, 0x07, 0x00,
        0x07, 0x00, 0x07, 0x00, 0x07, 0xF0, 0x07, 0xF0, 0x03, 0xF0, 0x01, 0xF0, 0x03,
        0xE0, 0x07, 0x00, 0x07, 0x00, 0x0F, 0x00, 0x0E, 0x00, 0x0E, 0x00, 0x0E, 0x00,
        0x0F, 0x86, 0x07, 0xFE, 0x07, 0xFE, 0x07, 0xFE, 0x03, 0xF8, 0x00, 0x00, 0x00
    },
    {
        0x00, 0x00, 0x80, 0x03, 0x80, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xE0, 0x03, 0xE0,
        0x03, 0xF0, 0x03, 0xB0, 0x03, 0xB0, 0x03, 0xB8, 0x03, 0x98, 0x03, 0x9C, 0x03,
        0x8C, 0x03, 0x8E, 0x03, 0x8E, 0x07, 0xFE, 0x0F, 0xFE, 0x0F, 0xFE, 0x0F, 0xFE,
        0x0F, 0x80, 0x03, 0x80, 0x03, 0x80, 0x03, 0x80, 0x03, 0x80, 0x03, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xFC, 0x07, 0xFC, 0x07, 0xFC, 0x07, 0xFC, 0x07, 0x1C, 0x00, 0x1C,
        0x00, 0x1C, 0x00, 0x1C, 0x00, 0xFC, 0x00, 0xFC, 0x01, 0xFC, 0x03, 0xFC, 0x07,
        0xFC, 0x07, 0x00, 0x07, 0x00, 0x0F, 0x00, 0x0E, 0x00, 0x0E, 0x00, 0x0F, 0x00,
        0x07, 0x84, 0x07, 0xFC, 0x07, 0xFE, 0x03, 0xFC, 0x03, 0xF8, 0x00, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xC0, 0x03, 0xF0, 0x07, 0xF8, 0x07, 0xF8, 0x07, 0x3C, 0x04, 0x1C,
        0x00, 0x1C, 0x00, 0xDC, 0x01, 0xFC, 0x03, 0xFE, 0x07, 0xFE, 0x07, 0xFE, 0x0F,
        0x1E, 0x0F, 0x1E, 0x0E, 0x1E, 0x0E, 0x1C, 0x0E, 0x1C, 0x0E, 0x1C, 0x0E, 0x1C,
        0x0F, 0x3C, 0x0F, 0xFC, 0x07, 0xF8, 0x07, 0xF0, 0x03, 0xE0, 0x01, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xFE, 0x0F, 0xFE, 0x0F, 0xFE, 0x0F, 0xFE, 0x07, 0x00, 0x07, 0x00,
        0x07, 0x80, 0x07, 0x80, 0x03, 0x80, 0x03, 0x80, 0x03, 0xC0, 0x03, 0xC0, 0x01,
        0xC0, 0x01, 0xC0, 0x01, 0xE0, 0x01, 0xE0, 0x00, 0xE0, 0x00, 0xE0, 0x00, 0xF0,
        0x00, 0x70, 0x00, 0x70, 0x00, 0x70, 0x00, 0x78, 0x00, 0x38, 0x00, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xE0, 0x01, 0xF8, 0x03, 0xF8, 0x07, 0xFC, 0x07, 0x3C, 0x07, 0x1C,
        0x07, 0x1C, 0x06, 0x1C, 0x06, 0x1C, 0x07, 0xFC, 0x07, 0xF8, 0x03, 0xF0, 0x03,
        0xF8, 0x03, 0xFC, 0x07, 0x1C, 0x07, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x1E,
        0x0E, 0x3C, 0x0F, 0xFC, 0x07, 0xFC, 0x07, 0xF8, 0x03, 0xF0, 0x01, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xF0, 0x00, 0xF8, 0x03, 0xFC, 0x03, 0xFC, 0x07, 0x9C, 0x07, 0x1E,
        0x07, 0x0E, 0x07, 0x0E, 0x0F, 0x0E, 0x0F, 0x0E, 0x0F, 0x0E, 0x0F, 0x1E, 0x0F,
        0xBC, 0x0F, 0xFC, 0x0F, 0xFC, 0x0F, 0xF8, 0x0F, 0x70, 0x06, 0x00, 0x07, 0x00,
        0x07, 0x8C, 0x07, 0xFC, 0x03, 0xFC, 0x03, 0xFC, 0x01, 0xF8, 0x00, 0x00, 0x00
    },
    {
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x00, 0xF0,
        0x01, 0xF0, 0x01, 0xF0, 0x01, 0xF0, 0x01, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x00, 0xF0, 0x01, 0xF0, 0x01, 0xF0,
        0x01, 0xF0, 0x01, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xE0, 0x01, 0xF0, 0x01, 0xF0, 0x01, 0xF0, 0x01, 0xF0, 0x01, 0xF0,
        0x03, 0xB8, 0x03, 0xB8, 0x03, 0xB8, 0x03, 0xB8, 0x03, 0x38, 0x03, 0x18, 0x07,
        0x1C, 0x07, 0x3C, 0x07, 0xFC, 0x07, 0xFC, 0x07, 0xFC, 0x07, 0xFC, 0x0F, 0x0E,
        0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x1E, 0x0F, 0x1C, 0x00, 0x00
    },
    {
        0x00, 0x00, 0xFC, 0x01, 0xFC, 0x03, 0xFC, 0x07, 0xFC, 0x0F, 0x1C, 0x0F, 0x1C,
        0x0E, 0x1C, 0x0E, 0x1C, 0x0E, 0x1C, 0x0E, 0x1C, 0x0E, 0x1C, 0x0F, 0xFC, 0x0F,
        0xFC, 0x0F, 0xFC, 0x07, 0xFC, 0x03, 0xFC, 0x00, 0x1C, 0x00, 0x1C, 0x00, 0x1C,
        0x00, 0x1C, 0x00, 0x1C, 0x00, 0x1C, 0x00, 0x1C, 0x00, 0x1C, 0x00, 0x00, 0x00
    },
    {
        0x00, 0x00, 0x1E, 0x0F, 0x1E, 0x0F, 0x1E, 0x0F, 0x1E, 0x0F, 0x1E, 0x0F, 0xBE,
        0x0F, 0xBE, 0x0F, 0xBE, 0x0F, 0xBE, 0x0D, 0xFE, 0x0D, 0xEE, 0x0D, 0xEE, 0x0C,
        0xEE, 0x0C, 0xEE, 0x0C, 0xEE, 0x0C, 0xCE, 0x0C, 0x0E, 0x0C, 0x0E, 0x0C, 0x0E,
        0x0C, 0x0E, 0x0C, 0x0E, 0x0C, 0x0E, 0x0C, 0x0E, 0x0C, 0x0E, 0x0C, 0x00, 0x00
    },
};
const int CLOCK_GLYPH_WIDTH = 13;
const int CLOCK_GLYPH_HEIGHT = 26;
const int CLOCK_GLYPH_ADVANCE = 15;
const int CLOCK_LINE_CHARACTERS = 5;
const int CLOCK_LINE_WIDTH =
    CLOCK_GLYPH_WIDTH +
    (CLOCK_LINE_CHARACTERS - 1) * CLOCK_GLYPH_ADVANCE;

const uint8_t* getClockGlyph(char character) {
    const char* found = strchr(CLOCK_GLYPH_CHARS, character);

    if (found == nullptr) {
        return nullptr;
    }

    size_t index = (size_t)(found - CLOCK_GLYPH_CHARS);
    return CLOCK_GLYPHS[index];
}

void drawClockLine(const char* text, int topY, bool separateMeridiem = false) {
    if (strlen(text) != CLOCK_LINE_CHARACTERS) {
        Serial.print("Clock line has unexpected length: ");
        Serial.println(text);
        return;
    }

    const int lineWidth = CLOCK_LINE_WIDTH + (separateMeridiem ? 2 : 0);
    const int startX = (LEFT_WIDTH - lineWidth) / 2;
    int x = startX;

    u8g2.setBitmapMode(1);

    for (int i = 0; i < CLOCK_LINE_CHARACTERS; ++i) {
        const uint8_t* glyph = getClockGlyph(text[i]);

        if (glyph != nullptr) {
            u8g2.drawXBM(
                x,
                topY,
                CLOCK_GLYPH_WIDTH,
                CLOCK_GLYPH_HEIGHT,
                glyph
            );
        }

        x += CLOCK_GLYPH_ADVANCE;

        if (separateMeridiem && i == 2) {
            x += 2;
        }
    }

    u8g2.setBitmapMode(0);
}

void drawLocalTime(const struct tm& localTime) {
    char mainTime[8];
    char secondsBuffer[8];

    strftime(mainTime, sizeof(mainTime), "%I:%M", &localTime);
    strftime(secondsBuffer, sizeof(secondsBuffer), ":%S%p", &localTime);

    drawClockLine(mainTime, 3);
    drawClockLine(secondsBuffer, 34, true);
}

void drawCalendar(const struct tm& localTime) {
    char dayBuffer[8];
    char dateBuffer[16];
    char yearBuffer[8];

    strftime(dayBuffer, sizeof(dayBuffer), "%a", &localTime);
    strftime(dateBuffer, sizeof(dateBuffer), "%d %b", &localTime);
    strftime(yearBuffer, sizeof(yearBuffer), "%Y", &localTime);

    for (char* p = dayBuffer; *p; ++p) {
        *p = (char)toupper((unsigned char)*p);
    }

    for (char* p = dateBuffer; *p; ++p) {
        *p = (char)toupper((unsigned char)*p);
    }

    const uint8_t* calendarFont = u8g2_font_7x13_mr;

    drawCentered(dayBuffer, calendarFont, RIGHT_CENTER_X, 13);
    drawCentered(dateBuffer, calendarFont, RIGHT_CENTER_X, 29);
    drawCentered(yearBuffer, calendarFont, RIGHT_CENTER_X, 45);
}

void drawUTCTime(const struct tm& utcTime) {
    char utcBuffer[8];
    strftime(utcBuffer, sizeof(utcBuffer), "%H:%M", &utcTime);

    drawCentered(
        utcBuffer,
        u8g2_font_7x13_mr,
        RIGHT_CENTER_X,
        63
    );
}

void drawRotatedUTCLabel() {
    u8g2.setFont(u8g2_font_5x8_mr);
    u8g2.setFontDirection(3);
    u8g2.drawStr(126, 63, "UTC");
    u8g2.setFontDirection(0);
}

void drawNtpIndicator() {
    if (ntpEverSynced && lastSuccessfulNtpServer == 1)
    {
        u8g2.drawPixel(0, DISPLAY_HEIGHT - 1);
    }
}

int getAnimationPixelX(uint32_t elapsedMs) {
    if (elapsedMs >= ANIMATION_TRAVEL_MS)
    {
        return DISPLAY_WIDTH - 1;
    }

    return (int)(
        ((uint64_t)elapsedMs * (DISPLAY_WIDTH - 1)) /
        ANIMATION_TRAVEL_MS
    );
}

void updateAnimationPixel(int newX) {
    if (newX < 0) {
        newX = 0;
    } else if (newX >= DISPLAY_WIDTH) {
        newX = DISPLAY_WIDTH - 1;
    }

    if (newX == lastAnimationPixelX) {
        return;
    }

    if (lastAnimationPixelX >= 0) {
        u8g2.setDrawColor(0);
        u8g2.drawPixel(lastAnimationPixelX, 0);
    }

    u8g2.setDrawColor(1);
    u8g2.drawPixel(newX, 0);

    u8g2.sendBuffer();

    lastAnimationPixelX = newX;
}

void drawClockDisplay(
    const struct tm& localTime,
    const struct tm& utcTime,
    int animationPixelX
)
{
    u8g2.clearBuffer();
    u8g2.setDrawColor(1);
    u8g2.setFontDirection(0);
    u8g2.setFontPosBaseline();

    u8g2.drawVLine(DIVIDER_X, 2, DISPLAY_HEIGHT - 4);

    drawLocalTime(localTime);

    drawCalendar(localTime);

    u8g2.drawHLine(82, UTC_DIVIDER_Y, 40);

    drawUTCTime(utcTime);
    drawRotatedUTCLabel();

    drawNtpIndicator();

    if (animationPixelX < 0) {
        animationPixelX = 0;
    } else if (animationPixelX >= DISPLAY_WIDTH) {
        animationPixelX = DISPLAY_WIDTH - 1;
    }

    u8g2.setDrawColor(1);
    u8g2.drawPixel(animationPixelX, 0);
    lastAnimationPixelX = animationPixelX;

    u8g2.sendBuffer();
}

void drawWaitingDisplay() {
    u8g2.clearBuffer();
    u8g2.setDrawColor(1);
    u8g2.setFontDirection(0);
    u8g2.setFontPosBaseline();

    if (WiFi.status() == WL_CONNECTED) {
        drawCentered(
            "WAITING FOR NTP",
            u8g2_font_helvB10_tf,
            DISPLAY_WIDTH / 2,
            27
        );

        drawCentered(
            "SYNCHRONISING",
            u8g2_font_6x10_tf,
            DISPLAY_WIDTH / 2,
            43
        );
    } else {
        drawCentered(
            "CONNECTING",
            u8g2_font_helvB12_tf,
            DISPLAY_WIDTH / 2,
            27
        );

        drawCentered(
            "TO WI-FI",
            u8g2_font_helvB10_tf,
            DISPLAY_WIDTH / 2,
            43
        );
    }

    drawNtpIndicator();

    int animationPixelX = getAnimationPixelX(
        (uint32_t)(millis() % 1000UL)
    );

    u8g2.setDrawColor(1);
    u8g2.drawPixel(animationPixelX, 0);
    lastAnimationPixelX = animationPixelX;

    u8g2.sendBuffer();
}

void updateDisplay() {
    if (!isTimeValid()) {
        unsigned long nowMs = millis();

        if (nowMs - lastWaitingDisplayMs >= 1000UL) {
            lastWaitingDisplayMs = nowMs;
            drawWaitingDisplay();
        }

        int animationPixelX = getAnimationPixelX(
            (uint32_t)(nowMs % 1000UL)
        );

        updateAnimationPixel(animationPixelX);
        return;
    }

    struct timeval currentTime;

    if (gettimeofday(&currentTime, nullptr) != 0) {
        return;
    }

    time_t now = currentTime.tv_sec;

    struct tm localTime;
    struct tm utcTime;

    localtime_r(&now, &localTime);
    gmtime_r(&now, &utcTime);

    uint32_t elapsedMs =
        (uint32_t)(currentTime.tv_usec / 1000L);

    int animationPixelX = getAnimationPixelX(elapsedMs);

    if (localTime.tm_sec != lastDisplayedSecond) {
        lastDisplayedSecond = localTime.tm_sec;

        drawClockDisplay(
            localTime,
            utcTime,
            animationPixelX
        );
    } else {
        updateAnimationPixel(animationPixelX);
    }
}

void setup() {
    Serial.begin(115200);
    setenv("TZ", TIMEZONE, 1);
    tzset();

    // Init display interface
    SPI.setRX(16);
    SPI.setTX(19);
    SPI.setSCK(18);
    SPI.begin();

    // Init display
    u8g2.begin();
    u8g2.setPowerSave(0);
    u8g2.setContrast(160);
    u8g2.setFontDirection(0);
    u8g2.setFontPosBaseline();
    u8g2.setFontRefHeightAll();
    u8g2.clearBuffer();
    u8g2.sendBuffer();

    drawWaitingDisplay();
    startWiFi();
}

void loop() {
    maintainWiFi();
    maintainNTP();
    updateDisplay();

    delay(2);
}

The code above relies on the U8g2 library and the correct display initialisation routine was determined by trial and error.

image

In the end, I got it working just how I liked and it’s been running for weeks without skipping a beat. Running off a 10,000mAh power bank, it managed to last about three days, suggesting it’s not particularly power hungry on its own – probably drawing just under 200mA at 5V.

image

It definitely beats what the raccoons were using before … a sundial, under the cover of moonlight! It seems so much of technology simply doesn’t work well at night …

Who Ordered the Spaghetti?

Ordinarily, I would approach design from the perspective of getting a breadboard prototype sorted out first, then translate that into a schematic which can be laid out as a PCB design which could then be fabricated and assembled. But unfortunately, with the tight timings for this design challenge alongside my full-time work, weekend family and hobby commitments, it’s been a tight squeeze.

As a result, I decided not to make PCBs for this design challenge. Instead, I’d construct my circuits in a relatively old-fashioned way, relying mainly on Dupont wire connections and occasional strips of Veroboard.

image

As a result, what you’ll be seeing might resemble spaghetti. It’s perhaps a little unsightly, but with a bit of care, such a design can still work rather reliably – especially if you’re careful about getting all the connections in the right place first, then perhaps applying hot-glue and/or electrical tape to help secure them into place and insulate any exposed conductive parts. Aside from that, there is also always the option of encapsulating everything (i.e. potting) the circuit and connections, thus making it virtually “everything-proof”. Instead, as I consider these designs to still be in need of refinement, I’d rather leave them as-is so they can be reconfigured as needed.

Preparing Camdenboss LED Indicators & Other Parts

As someone who loved to build kits, getting down to soldering is quite an enjoyable break from life. It’s almost like meditation …

image

Sitting behind my Weller WXsmart, I’ve been slowly building up (almost) everything that’s needed for the inside unit.

image

For each of the Camdenboss LED indicators, I chose an appropriate series resistor for use at 3.3V. With some finesse, I soldered the resistor and lead wires in-line, although this is not the “strongest” connection, it will suffice.

image

With my limited supply of heatshrink, I covered all the connections, leaving the other end as bare wire for now.

image

All nine units are prepared …

image image

… and so are two momentary push-buttons and an alert speaker.

image

With an hour of time, I sat down with my hand-held crimping tool and hand-terminated every Dupont wire connection for all of the wires. Thus, I now had an easy way to connect these components to the microcontroller board or to each other.

image

While I had the iron out, I also fitted header pins to the accelerometer breakout board.

image

I prepared one of the Camdenboss microswitches for use as a bin-lid position sensor, with a long length of flexible silicone sheathed wiring for longevity and flexibility. I terminated the end in one of the four-position pluggable terminal blocks.

image

As I didn’t have a PCB, I figured that with some slight bending of two pins, I could “make” the 3mm pitch connections fit a 2.54mm pin grid well enough to be usable.

image

Four pins at 3mm is 12mm span, while five pins at 2.54mm is 12.7mm. A kludge, but it will work for now. It essentially adapts it to 2.54mm header pins so I can use Dupont wire connections again.

image

Connections will have to be split out, so I built a few of these simple bus-bar modules which have four buses. That would work well for I2C or even for multi-voltage power (e.g. 5V, 3.3V, GND).

Measure Once, Drill Once … Unless Your Bit Breaks!

Usually, the adage recommends that you measure twice, but raccoons are pretty lazy and just want to get it right the first time. That’s why they decide to use technology for help …

image

With a bit of Microsoft Word table trickery, I could get a grid of just the right size for positioning my LEDs.

image

Hammering in a centre punch gave the drill a good position to start drilling the holes from …

image

But polycarbonate is a very strong plastic and Hammond Manufacturing makes cases of good quality … so my 3mm Chinese-made titanium-coated high-speed steel drill bit I was using for pilot holes snapped!

image

Sure, I drilled some other holes aside from just these in plastic, but I didn’t expect plastic to ultimately be the death of such a drill bit. Anyway, with another bit from a different set, I continued on.

image

Eventually, all of the drilling for the LEDs were completed.

image

The LEDs were simply fitted by pushing them through from the outside. They wedged themselves pretty nicely into the holes.

image

With the addition of some label tape, now it truly looks like some kind of home-built contraption.

Houston to Bin-ssion Control, Do You Copy?

To complete the build, there are a few more things that are needed – for example, securing the LCDs and speaker.

image image image

For that, I had to go drawing up a 3D printing design in TinkerCad, something akin to a frame to hold the whole assembly as I had no screws that would fit the holes that were precariously close to the edges of the screen. Likewise, a bracket would be used to hold the speaker in place, also 3D printed. In case anyone’s interested, the exact designs are here:

trs06-3dprinting-files.zip

image

While I did manage to print them out in the end, it was not without needing to fix a fault or two with my 3D printer, which is getting a bit old. This time, the Bowden pulled out of the fitting near the extruder gear, leaving my filament without any drive. Thankfully, I had another fitting on hand – all those retractions had broken off all of the teeth inside the fitting!

image image

image image

Thanks to my very careful use of calipers, the frames fit around the screens like a glove!

image

The one for the speaker worked quite well too – it’s purposefully slightly shorter than the speaker so that the sealing edge foam can compress against the case, forming a seal.

image image

To get the LCD for the main system operational, I used a ribbon of Dupont wire. I made a special adapter for a 39-ohm resistor for the LCD backlight. I later covered this in heatshrink.

image

I even crimped Dupont connections to capacitors to add them onto the bus module, smoothing out the 3.3V and 5V rails. All the LED positives were connected to 3.3V, while the 5V was tapped off for the clock LCD with room to spare for the sound driver board once that is built. The other function of the bus is to common all the grounds.

image

But because of all that is happening on the base unit, the microcontroller board is really busy. No I/O expansion here – each LED is getting its own pin. How very luxurious.

image

Because I had some odd frame sizes, I resorted to drawing shapes in Microsoft Word of the exact same size as the mounting hole locations, centre-punching it and drilling through the lid.

image

The resulting positioning was extremely accurate, to the point that the “rounded” corners of the print started to collide with one another making it a tight fit. Nevertheless, it bolted nicely into place.

image image

I decided to mount the speaker facing up for the best sound-radiating potential, but unfortunately, as I didn’t have an easy way to make a 27mm diameter hole in polycarbonate, I resorted to drilling random small holes and nibbling away at the plastic to get it as close as I could. It’s not pretty, but it’s close enough.

To demonstrate this, I got ChatGPT GPT-6 Luna to mix up an LED test sketch with the U8g2 GraphicsDemo example sketch to show that bin-ssion control is almost ready –

[[ESP32S3_LED_U8G2_Graphics_Demonstration.ino]]

// ESP32-S3 LED + U8g2 Graphics Demonstration
// by Gough Lui for element14 Communities "My Project is Trash" Design
// Challenge Dec 2026

// AI Disclosure: OpenAI ChatGPT GPT-6 Luna was used to implement this
// demonstration sketch based upon the U8g2 GraphicsTest example and
// basic LED control based upon specifications I provided which include
// a range of modes which can be cycled through using the two push-button
// inputs. The original comments are left intact for educational value.

/*
  The original U8g2 GraphicsTest drawing sequence runs continuously on the
  ST7565 NHD C12864 display while the LED patterns and button controls run.
  The display page interval is scheduled with millis(); there are no delay()
  calls in this combined sketch.

  Push-button controls:
    BUTTON_1 (GPIO 13): next demonstration mode
    BUTTON_2 (GPIO 14): previous demonstration mode

  Both buttons use INPUT_PULLUP and are therefore active LOW.
  Connect each button between its GPIO and GND.

  LEDs are common-anode / active-LOW:
    LOW  = LED on
    HIGH = LED off

  Demonstration modes:
    1. Random on/off
    2. One LED chase around
    3. All on
    4. All off
    5. All Red, then All Green, then All Blue
    6. Slow Flashing Red, Breathing Blue, Fast Flashing Green

  Timing and effects are non-blocking; there are no delay() calls.
  The blue breathing effect uses hardware LEDC PWM. The three blue LEDs
  share one LEDC channel because they always breathe together, keeping the
  channel usage within the ESP32-S3's available LEDC resources.

  Compatible with Arduino-ESP32 core 2.x and 3.x (including newer 3.x APIs).
*/

#include <Arduino.h>
#include <esp_arduino_version.h>
#include <math.h>
#include <SPI.h>
#include <U8g2lib.h>

// ST7565 NHD C12864, hardware SPI, rotated 180 degrees.
U8G2_ST7565_NHD_C12864_F_4W_HW_SPI u8g2(
  U8G2_R2, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8);

// -----------------------------------------------------------------------------
// Pin definitions
// -----------------------------------------------------------------------------

#define BUTTON_1 13
#define BUTTON_2 14

#define LED_ALARM_RED   39
#define LED_DATA_GREEN  40
#define LED_LID_BLUE    41
#define LED_70PC_GREEN  42
#define LED_80PC_BLUE   2
#define LED_90PC_RED    1
#define LED_ORIENT_GREEN 21
#define LED_RBIN_RED    47
#define LED_YBIN_BLUE   48

// LED index order used by the arrays and animation modes.
static const uint8_t LED_COUNT = 9;
static const uint8_t ledPins[LED_COUNT] = {
  LED_ALARM_RED,
  LED_DATA_GREEN,
  LED_LID_BLUE,
  LED_70PC_GREEN,
  LED_80PC_BLUE,
  LED_90PC_RED,
  LED_ORIENT_GREEN,
  LED_RBIN_RED,
  LED_YBIN_BLUE
};

// LED indices grouped by their physical colour.
static const uint8_t redLEDs[]   = { 0, 5, 7 };
static const uint8_t greenLEDs[] = { 1, 3, 6 };
static const uint8_t blueLEDs[]  = { 2, 4, 8 };
static const uint8_t COLOUR_LED_COUNT = 3;

// -----------------------------------------------------------------------------
// Timing and PWM settings
// -----------------------------------------------------------------------------

static const uint32_t BUTTON_DEBOUNCE_MS = 100;
static const uint32_t RANDOM_UPDATE_MS   = 250;
static const uint32_t CHASE_STEP_MS      = 120;
static const uint32_t COLOUR_STEP_MS     = 750;

// Mode 6 timing:
// Red:   1 second on, 1 second off (0.5 Hz full cycle).
// Green: 125 ms on, 125 ms off (4 Hz full cycle).
// Blue:  4 second breathing cycle.
static const uint32_t RED_HALF_PERIOD_MS   = 1000;
static const uint32_t GREEN_HALF_PERIOD_MS = 125;
static const uint32_t BLUE_BREATH_PERIOD_MS = 4000;
static const uint32_t BLUE_PWM_UPDATE_MS    = 20;

static const uint32_t PWM_FREQUENCY_HZ = 5000;
static const uint8_t PWM_RESOLUTION_BITS = 8;
static const uint8_t PWM_CHANNEL = 0;  // Shared by the three blue LEDs.

#if defined(ESP_ARDUINO_VERSION_MAJOR) && (ESP_ARDUINO_VERSION_MAJOR >= 3)
  #define USE_ESP32_LEDC_V3 1
  // Arduino-ESP32 3.x uses 2^resolution as the full-duty value.
  static const uint32_t PWM_FULL_DUTY = (1UL << PWM_RESOLUTION_BITS);
#else
  #define USE_ESP32_LEDC_V3 0
  // Arduino-ESP32 2.x uses 2^resolution - 1 as the full-duty value.
  static const uint32_t PWM_FULL_DUTY = (1UL << PWM_RESOLUTION_BITS) - 1UL;
#endif

// -----------------------------------------------------------------------------
// Demonstration modes
// -----------------------------------------------------------------------------

enum DemoMode : uint8_t {
  MODE_RANDOM = 0,
  MODE_CHASE,
  MODE_ALL_ON,
  MODE_ALL_OFF,
  MODE_COLOUR_CYCLE,
  MODE_RGB_EFFECTS,
  MODE_COUNT
};

static const char * const modeNames[MODE_COUNT] = {
  "Random on/off",
  "One LED chase around",
  "All on",
  "All off",
  "All Red / Green / Blue",
  "Slow Red / Breathing Blue / Fast Green"
};

// -----------------------------------------------------------------------------
// Button debouncing
// -----------------------------------------------------------------------------

struct DebouncedButton {
  uint8_t pin;
  bool rawState;
  bool stableState;
  uint32_t lastRawChangeMs;
};

DebouncedButton buttonNext;
DebouncedButton buttonPrevious;

void beginButton(DebouncedButton &button, uint8_t pin, uint32_t now) {
  button.pin = pin;
  pinMode(pin, INPUT_PULLUP);

  const bool initialState = digitalRead(pin);
  button.rawState = initialState;
  button.stableState = initialState;
  button.lastRawChangeMs = now;
}

// Returns true once when a debounced button press is detected.
// Both the press and release transitions are debounced.
bool buttonWasPressed(DebouncedButton &button, uint32_t now) {
  const bool sampledState = digitalRead(button.pin);

  if (sampledState != button.rawState) {
    button.rawState = sampledState;
    button.lastRawChangeMs = now;
  }

  if ((uint32_t)(now - button.lastRawChangeMs) >= BUTTON_DEBOUNCE_MS &&
      button.stableState != button.rawState) {
    button.stableState = button.rawState;

    // INPUT_PULLUP means LOW is the pressed state.
    if (button.stableState == LOW) {
      return true;
    }
  }

  return false;
}

// -----------------------------------------------------------------------------
// LED output helpers
// -----------------------------------------------------------------------------

// Cached digital state prevents unnecessary GPIO writes.
bool ledIsOn[LED_COUNT] = { false };

// True while the three blue LED pins are attached to the shared PWM channel.
bool bluePwmAttached = false;

// Current mode and animation timers.
DemoMode currentMode = MODE_RANDOM;
uint32_t modeStartedMs = 0;
uint32_t lastEffectUpdateMs = 0;
uint32_t lastBluePwmUpdateMs = 0;
uint8_t chaseIndex = 0;
uint8_t colourPhase = 0;

void writeLedDigital(uint8_t ledIndex, bool turnOn) {
  if (ledIndex >= LED_COUNT) {
    return;
  }

  if (ledIsOn[ledIndex] == turnOn) {
    return;
  }

  // Common-anode LED: LOW sinks current and illuminates the LED.
  digitalWrite(ledPins[ledIndex], turnOn ? LOW : HIGH);
  ledIsOn[ledIndex] = turnOn;
}

void writeAllDigital(bool turnOn) {
  for (uint8_t i = 0; i < LED_COUNT; ++i) {
    writeLedDigital(i, turnOn);
  }
}

void writeColourGroupDigital(const uint8_t *indices, bool turnOn) {
  for (uint8_t i = 0; i < COLOUR_LED_COUNT; ++i) {
    writeLedDigital(indices[i], turnOn);
  }
}

// -----------------------------------------------------------------------------
// Shared blue LED PWM
// -----------------------------------------------------------------------------

bool attachBluePwm() {
  if (bluePwmAttached) {
    return true;
  }

  // First establish a known inactive digital state before handing the pins
  // to the LEDC peripheral.
  for (uint8_t i = 0; i < COLOUR_LED_COUNT; ++i) {
    const uint8_t index = blueLEDs[i];
    pinMode(ledPins[index], OUTPUT);
    digitalWrite(ledPins[index], HIGH);
    ledIsOn[index] = false;
  }

#if USE_ESP32_LEDC_V3
  uint8_t attachedCount = 0;
  for (uint8_t i = 0; i < COLOUR_LED_COUNT; ++i) {
    const uint8_t pin = ledPins[blueLEDs[i]];

    // All three pins share one channel, so they receive the same PWM duty.
    if (!ledcAttachChannel(pin, PWM_FREQUENCY_HZ,
                           PWM_RESOLUTION_BITS, PWM_CHANNEL)) {
      Serial.printf("ERROR: Could not attach LEDC PWM to GPIO %u\n", pin);

      // Clean up any pins attached earlier in this loop.
      for (uint8_t j = 0; j < attachedCount; ++j) {
        ledcDetach(ledPins[blueLEDs[j]]);
      }
      return false;
    }
    ++attachedCount;
  }
#else
  const double actualFrequency = ledcSetup(
    PWM_CHANNEL, PWM_FREQUENCY_HZ, PWM_RESOLUTION_BITS);

  if (actualFrequency <= 0.0) {
    Serial.println("ERROR: Could not configure LEDC PWM channel");
    return false;
  }

  for (uint8_t i = 0; i < COLOUR_LED_COUNT; ++i) {
    ledcAttachPin(ledPins[blueLEDs[i]], PWM_CHANNEL);
  }
#endif

  bluePwmAttached = true;
  lastBluePwmUpdateMs = 0;
  return true;
}

void writeBluePwmBrightness(uint8_t brightness) {
  if (!bluePwmAttached) {
    return;
  }

  // The LEDs are common-anode, so the PWM polarity is inverted:
  // brightness 0   -> output HIGH (off)
  // brightness 255 -> output LOW  (fully on)
  const uint32_t duty =
    ((uint32_t)(255U - brightness) * PWM_FULL_DUTY + 127U) / 255U;

#if USE_ESP32_LEDC_V3
  // Writing the channel updates every pin attached to that shared channel.
  ledcWriteChannel(PWM_CHANNEL, duty);
#else
  ledcWrite(PWM_CHANNEL, duty);
#endif
}

void detachBluePwm() {
  if (!bluePwmAttached) {
    return;
  }

  // Set the shared PWM output to off before detaching.
  writeBluePwmBrightness(0);

#if USE_ESP32_LEDC_V3
  for (uint8_t i = 0; i < COLOUR_LED_COUNT; ++i) {
    ledcDetach(ledPins[blueLEDs[i]]);
  }
#else
  for (uint8_t i = 0; i < COLOUR_LED_COUNT; ++i) {
    ledcDetachPin(ledPins[blueLEDs[i]]);
  }
#endif

  // Explicitly leave the common-anode pins driven HIGH when off.
  for (uint8_t i = 0; i < COLOUR_LED_COUNT; ++i) {
    const uint8_t index = blueLEDs[i];
    pinMode(ledPins[index], OUTPUT);
    digitalWrite(ledPins[index], HIGH);
    ledIsOn[index] = false;
  }

  bluePwmAttached = false;
}

// -----------------------------------------------------------------------------
// Mode handling
// -----------------------------------------------------------------------------

void printCurrentMode() {
  Serial.printf("Mode %u/%u: %s\n",
                (unsigned int)currentMode + 1,
                (unsigned int)MODE_COUNT,
                modeNames[currentMode]);
}

void enterMode(DemoMode newMode, uint32_t now) {
  // Ensure any previous PWM mode is shut down before changing pin ownership.
  detachBluePwm();

  currentMode = newMode;
  modeStartedMs = now;
  lastEffectUpdateMs = now;
  lastBluePwmUpdateMs = now - BLUE_PWM_UPDATE_MS;
  chaseIndex = 0;
  colourPhase = 0;

  // Put every LED into a known OFF state before applying the new mode.
  writeAllDigital(false);

  // Establish an immediate, visible starting pattern for the static/simple
  // modes rather than waiting for their first animation timer interval.
  switch (currentMode) {
    case MODE_RANDOM:
      for (uint8_t i = 0; i < LED_COUNT; ++i) {
        writeLedDigital(i, random(0, 2) == 1);
      }
      break;

    case MODE_CHASE:
      chaseIndex = 0;
      writeLedDigital(chaseIndex, true);
      break;

    case MODE_ALL_ON:
      writeAllDigital(true);
      break;

    case MODE_COLOUR_CYCLE:
      writeColourGroupDigital(redLEDs, true);
      break;

    case MODE_RGB_EFFECTS:
      if (attachBluePwm()) {
        writeBluePwmBrightness(0);
      } else {
        Serial.println("WARNING: Blue breathing PWM unavailable; blue LEDs will remain off.");
      }
      break;

    case MODE_ALL_OFF:
    default:
      // The all-off state was already established above.
      break;
  }

  printCurrentMode();
}

void selectNextMode(uint32_t now) {
  const uint8_t next = ((uint8_t)currentMode + 1U) % MODE_COUNT;
  enterMode((DemoMode)next, now);
}

void selectPreviousMode(uint32_t now) {
  const uint8_t previous = ((uint8_t)currentMode + MODE_COUNT - 1U) % MODE_COUNT;
  enterMode((DemoMode)previous, now);
}

// -----------------------------------------------------------------------------
// Individual mode updates (all non-blocking)
// -----------------------------------------------------------------------------

void updateRandomMode(uint32_t now) {
  if ((uint32_t)(now - lastEffectUpdateMs) < RANDOM_UPDATE_MS) {
    return;
  }
  lastEffectUpdateMs = now;

  for (uint8_t i = 0; i < LED_COUNT; ++i) {
    writeLedDigital(i, random(0, 2) == 1);
  }
}

void updateChaseMode(uint32_t now) {
  if ((uint32_t)(now - lastEffectUpdateMs) < CHASE_STEP_MS) {
    return;
  }
  lastEffectUpdateMs = now;

  // Turn off the previous LED, advance, and illuminate exactly one LED.
  writeLedDigital(chaseIndex, false);
  chaseIndex = (chaseIndex + 1U) % LED_COUNT;
  writeLedDigital(chaseIndex, true);
}

void updateColourCycleMode(uint32_t now) {
  if ((uint32_t)(now - lastEffectUpdateMs) >= COLOUR_STEP_MS) {
    lastEffectUpdateMs = now;
    colourPhase = (colourPhase + 1U) % 3U;
  }

  // Each phase illuminates all LEDs of one colour and turns the rest off.
  writeColourGroupDigital(redLEDs, colourPhase == 0);
  writeColourGroupDigital(greenLEDs, colourPhase == 1);
  writeColourGroupDigital(blueLEDs, colourPhase == 2);
}

void updateRgbEffectsMode(uint32_t now) {
  const uint32_t elapsed = now - modeStartedMs;

  // Slow red flash: 1 second on, 1 second off.
  const bool redOn = ((elapsed / RED_HALF_PERIOD_MS) % 2U) == 0U;
  writeColourGroupDigital(redLEDs, redOn);

  // Fast green flash: 125 ms on, 125 ms off.
  const bool greenOn = ((elapsed / GREEN_HALF_PERIOD_MS) % 2U) == 0U;
  writeColourGroupDigital(greenLEDs, greenOn);

  // Smooth blue breathing: a four-second cosine cycle, from off to full
  // brightness and back to off. Hardware PWM runs independently of loop().
  if (bluePwmAttached &&
      (uint32_t)(now - lastBluePwmUpdateMs) >= BLUE_PWM_UPDATE_MS) {
    lastBluePwmUpdateMs = now;

    const float phase = (float)(elapsed % BLUE_BREATH_PERIOD_MS) *
                        (2.0f * PI / (float)BLUE_BREATH_PERIOD_MS);
    const float level = 0.5f - (0.5f * cosf(phase));
    const uint8_t brightness = (uint8_t)(level * 255.0f + 0.5f);
    writeBluePwmBrightness(brightness);
  }
}

void updateCurrentMode(uint32_t now) {
  switch (currentMode) {
    case MODE_RANDOM:
      updateRandomMode(now);
      break;

    case MODE_CHASE:
      updateChaseMode(now);
      break;

    case MODE_ALL_ON:
      // The state is established on mode entry; nothing to do here.
      break;

    case MODE_ALL_OFF:
      // The state is established on mode entry; nothing to do here.
      break;

    case MODE_COLOUR_CYCLE:
      updateColourCycleMode(now);
      break;

    case MODE_RGB_EFFECTS:
      updateRgbEffectsMode(now);
      break;

    default:
      enterMode(MODE_RANDOM, now);
      break;
  }
}


// -----------------------------------------------------------------------------
// U8g2 GraphicsTest sequence
//
// The drawing routines below are adapted from the U8g2 full-buffer
// GraphicsTest example by Oliver Kraus (olikraus).
// Source: https://github.com/olikraus/u8g2/tree/master/sys/arduino/u8g2_full_buffer/GraphicsTest
// License: BSD 2-Clause; copyright and permission notice are retained below.
//
// Unlike the original example, this version does not call delay(100). The
// display test page is redrawn at a fixed interval from loop(), allowing the
// LED animations and debounced buttons to be serviced between display frames.
// -----------------------------------------------------------------------------

/*
  Copyright (c) 2016, olikraus@gmail.com
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

static const uint32_t GRAPHICS_FRAME_INTERVAL_MS = 100;
static uint8_t graphicsDrawState = 0;
static uint32_t lastGraphicsFrameMs = 0;

void graphicsPrepare() {
  u8g2.setFont(u8g2_font_6x10_tf);
  u8g2.setFontRefHeightExtendedText();
  u8g2.setDrawColor(1);
  u8g2.setFontPosTop();
  u8g2.setFontDirection(0);
}

void graphicsBoxFrame(uint8_t a) {
  u8g2.drawStr(0, 0, "drawBox");
  u8g2.drawBox(5, 10, 20, 10);
  u8g2.drawBox(10 + a, 15, 30, 7);
  u8g2.drawStr(0, 30, "drawFrame");
  u8g2.drawFrame(5, 40, 20, 10);
  u8g2.drawFrame(10 + a, 45, 30, 7);
}

void graphicsDiscCircle(uint8_t a) {
  u8g2.drawStr(0, 0, "drawDisc");
  u8g2.drawDisc(10, 18, 9);
  u8g2.drawDisc(24 + a, 16, 7);
  u8g2.drawStr(0, 30, "drawCircle");
  u8g2.drawCircle(10, 48, 9);
  u8g2.drawCircle(24 + a, 46, 7);
}

void graphicsRoundedFrame(uint8_t a) {
  u8g2.drawStr(0, 0, "drawRFrame/Box");
  u8g2.drawRFrame(5, 10, 40, 30, a + 1);
  u8g2.drawRBox(50, 10, 25, 40, a + 1);
}

void graphicsString(uint8_t a) {
  u8g2.setFontDirection(0);
  u8g2.drawStr(30 + a, 31, " 0");
  u8g2.setFontDirection(1);
  u8g2.drawStr(30, 31 + a, " 90");
  u8g2.setFontDirection(2);
  u8g2.drawStr(30 - a, 31, " 180");
  u8g2.setFontDirection(3);
  u8g2.drawStr(30, 31 - a, " 270");
}

void graphicsLine(uint8_t a) {
  u8g2.drawStr(0, 0, "drawLine");
  u8g2.drawLine(7 + a, 10, 40, 55);
  u8g2.drawLine(7 + a * 2, 10, 60, 55);
  u8g2.drawLine(7 + a * 3, 10, 80, 55);
  u8g2.drawLine(7 + a * 4, 10, 100, 55);
}

void graphicsTriangle(uint8_t a) {
  const uint16_t offset = a;
  u8g2.drawStr(0, 0, "drawTriangle");
  u8g2.drawTriangle(14, 7, 45, 30, 10, 40);
  u8g2.drawTriangle(14 + offset, 7 - offset,
                    45 + offset, 30 - offset,
                    57 + offset, 10 - offset);
  u8g2.drawTriangle(57 + offset * 2, 10,
                    45 + offset * 2, 30,
                    86 + offset * 2, 53);
  u8g2.drawTriangle(10 + offset, 40 + offset,
                    45 + offset, 30 + offset,
                    86 + offset, 53 + offset);
}

void graphicsAsciiPage1() {
  char s[2] = " ";
  u8g2.drawStr(0, 0, "ASCII page 1");
  for (uint8_t y = 0; y < 6; ++y) {
    for (uint8_t x = 0; x < 16; ++x) {
      s[0] = (char)(y * 16 + x + 32);
      u8g2.drawStr(x * 7, y * 10 + 10, s);
    }
  }
}

void graphicsAsciiPage2() {
  char s[2] = " ";
  u8g2.drawStr(0, 0, "ASCII page 2");
  for (uint8_t y = 0; y < 6; ++y) {
    for (uint8_t x = 0; x < 16; ++x) {
      s[0] = (char)(y * 16 + x + 160);
      u8g2.drawStr(x * 7, y * 10 + 10, s);
    }
  }
}

void graphicsUnicode(uint8_t a) {
  u8g2.drawStr(0, 0, "Unicode");
  u8g2.setFont(u8g2_font_unifont_t_symbols);
  u8g2.setFontPosTop();
  u8g2.drawUTF8(0, 24, "\xE2\x98\x80 \xE2\x98\x81");  // sun and cloud

  if (a <= 3) {
    u8g2.drawUTF8(a * 3, 36, "\xE2\x98\x82");        // umbrella
  } else {
    u8g2.drawUTF8(a * 3, 36, "\xE2\x98\x94");        // umbrella with rain
  }
}

#define GRAPHICS_CROSS_WIDTH  24
#define GRAPHICS_CROSS_HEIGHT 24
static const unsigned char graphicsCrossBits[] U8X8_PROGMEM = {
  0x00, 0x18, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00,
  0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00,
  0x00, 0x81, 0x00, 0x00, 0x81, 0x00, 0xC0, 0x00, 0x03,
  0x38, 0x3C, 0x1C, 0x06, 0x42, 0x60, 0x01, 0x42, 0x80,
  0x01, 0x42, 0x80, 0x06, 0x42, 0x60, 0x38, 0x3C, 0x1C,
  0xC0, 0x00, 0x03, 0x00, 0x81, 0x00, 0x00, 0x81, 0x00,
  0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00,
  0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x18, 0x00
};

#define GRAPHICS_CROSS_BLOCK_WIDTH  14
#define GRAPHICS_CROSS_BLOCK_HEIGHT 14
static const unsigned char graphicsCrossBlockBits[] U8X8_PROGMEM = {
  0xFF, 0x3F, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20,
  0x01, 0x20, 0x01, 0x20, 0xC1, 0x20, 0xC1, 0x20,
  0x01, 0x20, 0x01, 0x20, 0x01, 0x20, 0x01, 0x20,
  0x01, 0x20, 0xFF, 0x3F
};

void graphicsBitmapOverlay(uint8_t a) {
  const uint8_t frameSize = 28;
  u8g2.drawStr(0, 0, "Bitmap overlay");
  u8g2.drawStr(0, frameSize + 12, "Solid / transparent");

  u8g2.setBitmapMode(false);
  u8g2.drawFrame(0, 10, frameSize, frameSize);
  u8g2.drawXBMP(2, 12, GRAPHICS_CROSS_WIDTH,
                GRAPHICS_CROSS_HEIGHT, graphicsCrossBits);
  if (a & 4) {
    u8g2.drawXBMP(7, 17, GRAPHICS_CROSS_BLOCK_WIDTH,
                  GRAPHICS_CROSS_BLOCK_HEIGHT, graphicsCrossBlockBits);
  }

  u8g2.setBitmapMode(true);
  u8g2.drawFrame(frameSize + 5, 10, frameSize, frameSize);
  u8g2.drawXBMP(frameSize + 7, 12, GRAPHICS_CROSS_WIDTH,
                GRAPHICS_CROSS_HEIGHT, graphicsCrossBits);
  if (a & 4) {
    u8g2.drawXBMP(frameSize + 12, 17, GRAPHICS_CROSS_BLOCK_WIDTH,
                  GRAPHICS_CROSS_BLOCK_HEIGHT, graphicsCrossBlockBits);
  }
}

void graphicsBitmapModes(bool transparent) {
  const uint8_t frameSize = 24;
  u8g2.drawBox(0, frameSize * 0.5, frameSize * 5, frameSize);
  u8g2.drawStr(frameSize * 0.5, 50, "Black");
  u8g2.drawStr(frameSize * 2, 50, "White");
  u8g2.drawStr(frameSize * 3.5, 50, "XOR");

  u8g2.setBitmapMode(transparent);
  u8g2.drawStr(0, 0, transparent ? "Transparent bitmap" : "Solid bitmap");
  u8g2.setDrawColor(0);
  u8g2.drawXBMP(frameSize * 0.5, 24, GRAPHICS_CROSS_WIDTH,
                GRAPHICS_CROSS_HEIGHT, graphicsCrossBits);
  u8g2.setDrawColor(1);
  u8g2.drawXBMP(frameSize * 2, 24, GRAPHICS_CROSS_WIDTH,
                GRAPHICS_CROSS_HEIGHT, graphicsCrossBits);
  u8g2.setDrawColor(2);
  u8g2.drawXBMP(frameSize * 3.5, 24, GRAPHICS_CROSS_WIDTH,
                GRAPHICS_CROSS_HEIGHT, graphicsCrossBits);
}

void graphicsDrawCurrentPage() {
  graphicsPrepare();

  switch (graphicsDrawState >> 3) {
    case 0:  graphicsBoxFrame(graphicsDrawState & 7); break;
    case 1:  graphicsDiscCircle(graphicsDrawState & 7); break;
    case 2:  graphicsRoundedFrame(graphicsDrawState & 7); break;
    case 3:  graphicsString(graphicsDrawState & 7); break;
    case 4:  graphicsLine(graphicsDrawState & 7); break;
    case 5:  graphicsTriangle(graphicsDrawState & 7); break;
    case 6:  graphicsAsciiPage1(); break;
    case 7:  graphicsAsciiPage2(); break;
    case 8:  graphicsUnicode(graphicsDrawState & 7); break;
    case 9:  graphicsBitmapModes(false); break;
    case 10: graphicsBitmapModes(true); break;
    case 11: graphicsBitmapOverlay(graphicsDrawState & 7); break;
  }
}

void updateGraphicsTest(uint32_t now) {
  if ((uint32_t)(now - lastGraphicsFrameMs) < GRAPHICS_FRAME_INTERVAL_MS) {
    return;
  }

  lastGraphicsFrameMs = now;

  u8g2.clearBuffer();
  graphicsDrawCurrentPage();
  u8g2.sendBuffer();

  ++graphicsDrawState;
  if (graphicsDrawState >= (12U * 8U)) {
    graphicsDrawState = 0;
  }
}

// -----------------------------------------------------------------------------
// Arduino setup() and loop()
// -----------------------------------------------------------------------------

void setup() {
  Serial.begin(115200);

  // Start with all common-anode LEDs off (GPIO HIGH).
  for (uint8_t i = 0; i < LED_COUNT; ++i) {
    pinMode(ledPins[i], OUTPUT);
    digitalWrite(ledPins[i], HIGH);
    ledIsOn[i] = false;
  }

  const uint32_t now = millis();
  beginButton(buttonNext, BUTTON_1, now);
  beginButton(buttonPrevious, BUTTON_2, now);

  randomSeed((uint32_t)micros());

  // Initialise the ST7565 display. The display test then runs independently
  // of the selected LED demonstration mode.
  u8g2.begin();
  u8g2.setContrast(160);
  lastGraphicsFrameMs = millis() - GRAPHICS_FRAME_INTERVAL_MS;

  Serial.println();
  Serial.println("ESP32-S3 LED + U8g2 Graphics Demonstration");
  Serial.println("BUTTON_1 = next mode; BUTTON_2 = previous mode");
  Serial.println("Buttons are INPUT_PULLUP: connect each button between GPIO and GND.");

  // Start in mode 1. The initial random pattern is generated on its first tick.
  enterMode(MODE_RANDOM, now);
}

void loop() {
  const uint32_t now = millis();

  const bool nextPressed = buttonWasPressed(buttonNext, now);
  const bool previousPressed = buttonWasPressed(buttonPrevious, now);

  // If both buttons become pressed during the same loop pass, ignore the
  // ambiguous combination rather than moving forward and backward at once.
  if (nextPressed && !previousPressed) {
    selectNextMode(now);
  } else if (previousPressed && !nextPressed) {
    selectPreviousMode(now);
  }

  updateCurrentMode(now);
  updateGraphicsTest(now);
}

Here’s a short silent video showing it in action.

You don't have permission to edit metadata of this video.
Edit media
x
image
Upload Preview
image

Conclusion

It’s nice to get hands-on and build things again, even if the wired construction is a bit like visual spaghetti. At least, it seems to be mostly working so far, although it is still not quite complete, with the audio driving board still yet to be built for bin-ssion control. It was a nice break from life to be soldering, stripping and crimping each and every wire, hammering in a centre punch and drilling holes, praying it would be in the right place and drawing up simple 3D printed designs.

While the inside unit is almost completed, the outside unit still needs some accelerometer investigations and a mechanical design. I’ve decided not to implement the VOC gas sensor because it seems to need a baselining procedure periodically and that would be difficult to achieve inside a closed bin. But even then, the outside unit still needs something to be fitted to once built …

image

As a result, this raccoon is asking Santa to deliver him a wheelie bin … full or empty doesn’t matter. As long as it’s a bin, it will do! Will there be a wheelie bin waiting, or will there just be a sack of coal? I guess we’ll find out later … but perhaps a little more time wouldn’t hurt either …

AI Disclosure: AI has been used in the generation of a number of images in this post which involve raccoons. AI has not been used to generate or modify any of the text or photographs of products and electronic items. AI has been used to apply debugging modifications and edit/optimise pre-existing example code and prior-developed sketches. AI has not been used to perform manual tasks (e.g. wire stripping, heatshrinking, soldering, plugging/unplugging connections – there’s no robots here, so I’ve got to be the robot).

  • Sign in to reply
  • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2026 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube