Make a highly accurate Circuit Python Matrix Panel clock quick and easy with a Matrix Portal S3 microcontroller and a 64x32 Matrix Panel.
Skill Level: Beginner
Powering the Matrix Portal S3
You can power 1 panel with the the Matrix Portal S3 and included power cable.
If you want to add additional panels you will need to provide an external power supply such as a Meanwell 5V 18Amp power supply. Each panel requires approximately 4 Amps of power. There are many power supplies to choose from. It must be a 5V power supply but how many watts and amps will depend on how many panels you want to add. The power supply choice becomes simple if you allot 4 Amps per panel. I have a playground note on a 12-panel Matrix Portal S3 project. If you want to add more panels that article is a very good resource.
Installing Circuit Python
First and foremost you'll want to install Circuit Python or update it. You can find the latest UF2 for the Matrix Portal S3 here. You must use Google Chrome if you want to use the online web installer/updater. Google Chrome is the only browser to support Web Serial. Firefox does not support it.
Get Updated Library Bundle
Now lets grab some necessary libraries for this project and transfer them to the /lib directory on your CIRCUITPY drive. All libraries can be found in the Circuit Python Library Bundle. The bundle is updated daily so when starting on a new project it's a good idea to get the latest bundle. Libraries can be either a folder (containing multiple helper .mpy files) or a single .mpy file.
Using Libraries
Download and unzip the bundle to your desktop. Then drag and drop libraries in the /lib directory to the /lib directory on your CIRCUITPY USB drive. Only transfer libraries that you will be actively using to save storage space on your CIRCUITPY drive.
You use the libraries in your code.py script with `import`. We will be turning the Matrix Panel into a 64x32 pixel display. Displayio is the graphical library for Circuit Python. It is powerful and allows for layering of images and text. Displayio will treat it almost the same as a 64x32 TFT display. With any displayio project the first thing you want to do is set
displayio.release_displays()
This re-initializes (wipes & makes ready) the display on every reload of the entire script. A common mistake is forgetting to put that at the top of the script and the display never reloads properly.
Then we setup the Wifi socket pool, connection manager, and adafruit_requests. All scripts that have an online feature to them in one way or another will always require adafruit_requests regardless of the protocol, including NTP.
The libraries you'll need from the bundle are:
- adafruit_bitmap_font
- adafruit_bus_device
- adafruit_display_text
- adafruit_connection_manager
- adafruit_ntp
- adafruit_requests
- neopixel
The rest of the imports such as os, time, board, displayio, etc.. are modules that are built into Circuit Python itself and can be imported at any time.
import os import time import board import microcontroller import displayio import terminalio import rgbmatrix import framebufferio import wifi import adafruit_connection_manager import adafruit_requests import rtc import adafruit_ntp from adafruit_display_text import label from adafruit_bitmap_font import bitmap_font displayio.release_displays() # Initalize Wifi, Socket Pool, Request Session pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio) requests = adafruit_requests.Session(pool)
RGBMatrix & Framebufferio
We will not be using the MatrixPortal or Portalbase helper libraries here. Instead we'll make the script more efficient by using only the libraries necessary for turning a Matrix Panel into a display. If you have a Matrix Portal S3 please realize that the MatrixPortal & Portalbase libraries are not necessary to do basic tasks such as getting the time from an NTP server. In fact, those helper libraries rely on RGBMatrix, Framebufferio, Adafruit_NTP, and Adafruit_Requests. We're simply cutting out an unnecessary middle man from the equation.
Ensure you fill out settings.toml with your wifi credentials. This project requires the Matrix Portal S3 to go online for NTP updates.
# Use settings.toml for credentials
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
Custom Configuration Variables
Next is setting some constants (or variables) to make life a bit easier. It's a good idea to put all configuration constants and variables at the top of your script gathered in one place to make finding them easier when you're coding.
Bit Depth is how many colors you want available. For a clock with no background you only need a bit depth of 1 or 2. If you intend to add BMP images then you might want 4,5, or 6 bit color.
You will see pictures later in this playground note that shows the difference between 12 hour and 24 hour time format. Simply edit the variable to 12 or 24 here to change the format.
TZ_OFFSET = -5 # time zone offset in hours from UTC Time_Format = "24" # 12 hour (AM/PM) or 24 hour (military) clock sleep_time = 60 # NTP poll time interval in seconds DISPLAY_WIDTH = 64 DISPLAY_HEIGHT = 32 DISPLAY_ROTATION = 0 BIT_DEPTH = 4 AUTO_REFRESH = True DEBUG_TIME = False # For manually testing times
Instantiating the Matrix
These settings are standard for a 64x32 panel. If you're using a 64x64 panel you might have to modify it to add the additional Address E pin.
matrix = rgbmatrix.RGBMatrix(
width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, bit_depth=BIT_DEPTH,
rgb_pins=[
board.MTX_R1,
board.MTX_G1,
board.MTX_B1,
board.MTX_R2,
board.MTX_G2,
board.MTX_B2],
addr_pins=[board.MTX_ADDRA, board.MTX_ADDRB, board.MTX_ADDRC, board.MTX_ADDRD],
clock_pin=board.MTX_CLK,
latch_pin=board.MTX_LAT,
output_enable_pin=board.MTX_OE,
doublebuffer=True)
Next is where some magic happens as the Matrix Panel is associated with a displayio object using framebufferio. The frame buffer becomes the display, pixel colors are run as a buffer stream. You don't need to know how it works only that the matrix panel can now be used by displayio.
display = framebufferio.FramebufferDisplay(matrix, auto_refresh=AUTO_REFRESH, rotation=DISPLAY_ROTATION)
NTP & RTC
Now we setup the NTP request. NTP is an internet based time server. All an NTP server does is respond to a request with the current time. The actual NTP server IP/URL and functions are pulled from the adafruit_ntp library. You can use a different NTP server but that is not covered in this playground note.
# Publicly Open NTP Time Server # No AdafruitIO credentials required ntp = adafruit_ntp.NTP(pool, tz_offset=TZ_OFFSET)
Timestamp Formatting
These are custom helper functions I've written to make time conversion and label formatting easier.
Time formatting uses Struct Time. You can read more about Circuit Python struct time formatting here. You can easily customize how you want date or time displayed using struct time formatting.
Ignore the phantom green lettering. It's due to a reflection on my camera lens.
def time_calc(input_time):
"""Converts seconds to minutes/hours/days"""
if input_time < 60:
return f"{input_time:.0f} seconds"
if input_time < 3600:
return f"{input_time / 60:.0f} minutes"
if input_time < 86400:
return f"{input_time / 60 / 60:.1f} hours"
return f"{input_time / 60 / 60 / 24:.2f} days"
# Custom timestamp functions use struct time format
# You can easily change them to your preferred format
# https://docs.circuitpython.org/en/latest/shared-bindings/time/index.html#time.struct_time
def _format_datetime(datetime):
""" F-String formatted struct time conversion"""
return (f"{datetime.tm_mon:02}/" +
f"{datetime.tm_mday:02}/" +
f"{datetime.tm_year:02} " +
f"{datetime.tm_hour:02}:" +
f"{datetime.tm_min:02}:" +
f"{datetime.tm_sec:02}")
def _format_min(datetime):
""" Get the current minute"""
return (f"{datetime.tm_min:02}")
def _format_sec(datetime):
""" Get the current second"""
return (f"{datetime.tm_sec:02}")
def _format_time(datetime, format="12"):
""" Time is 12 hour or 24 hour format"""
if format == "12":
hour = datetime.tm_hour % 12
min = datetime.tm_min
if hour == 0:
hour = 12
am_pm = "AM"
if datetime.tm_hour / 12 >= 1:
am_pm = "PM"
if DEBUG_TIME:
# Set debug to True & change these to test different times
debug_hour = "09"
debug_min = "09"
return (f"{debug_hour:01}:{debug_min:02} {am_pm}")
else:
return (f"{hour:01}:{min:02} {am_pm}")
if format == "24":
return (f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}")
Quick Colors
I always add a small list of commonly used colors to every display related script. It makes life much easier than looking up hex color codes. You can add more colors using hex color codes.
# Quick Colors for Labels TEXT_BLACK = 0x000000 TEXT_BLUE = 0x0000FF TEXT_CYAN = 0x00FFFF TEXT_GRAY = 0x8B8B8B TEXT_GREEN = 0x00FF00 TEXT_LIGHTBLUE = 0x90C7FF TEXT_MAGENTA = 0xFF00FF TEXT_ORANGE = 0xFFA500 TEXT_PURPLE = 0x800080 TEXT_RED = 0xFF0000 TEXT_TEAL = 0xB2D8D8 TEXT_WHITE = 0xFFFFFF TEXT_YELLOW = 0xFFFF00
Custom Fonts, Labels, and Groups
If you want to use custom fonts they must be in .bdf or .pcf format. Upload the file to your CIRCUITPY device and then specifying the path to the font. I usually create a directory in my CIRCUITPY drive named "fonts".
Labels are how text information is displayed on the matrix panel. If you want to learn more about labels, updating labels, and label x/y placement please read Learn Guide: Circuit Python Text Library.
Groups are how you create layers upon layers of elements on a display. If you want to learn more about groups & layers Learn Guide: Circuit Python Display Support Using Displayio
# To use custom font uncomment below and change terminalio.FONT
#font_IBMPlex = bitmap_font.load_font("/fonts/IBMPlexMono-Medium-24_jep.bdf")
clock_label = label.Label(terminalio.FONT)
clock_label.anchor_point = (0.5, 0.5)
clock_label.anchored_position = (DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2)
clock_label.scale = 1
clock_label.color = TEXT_ORANGE
# Groups Setup
main_group = displayio.Group()
main_group.append(clock_label)
display.root_group = main_group
NIST Time
While developing this project it took a while before I figured out that my PC's clock was actually wrong and a few seconds ahead of NIST. If you compare the time on the Matrix Panel clock to NIST time you'll see that it is extremely accurate and in my case more accurate than the time on my PC.
Initial Time Synchronization
When the program is first run it will retrieve the NTP time and set the RTC. This happens only once and before the infinite loop. When the time appears on the Matrix Panel it should be the correct time to the second.
now = time.localtime()
current_datestamp = "{}".format(_format_datetime(now))
try:
rtc.RTC().datetime = ntp.datetime
print(f"Initial Synchronize: {current_datestamp}")
time.sleep(1)
except OSError as e:
print(f"RTC or NTP Error: {e}")
Infinite Loop
Lastly we create a while True: loop that runs anything inside of it forever in a sequential loop.
Clock Label
The time from NTP is updated on the display using clock_label.text.
Microcontroller Reset Failsafe
time.monotonic will drift by a few seconds every day. To prevent that I reset the board once every 24 hours. This can help improve the accuracy by resetting the board once a day.
Synchronize RTC with NTP
We want to keep the RTC updated by polling the NTP occasionally. I have it programmed to synchronize with the NTP server every hour on the hour. This is expressed when the clock reaches 00 minutes and 00 seconds.
print("===============================")
while True:
now = time.localtime()
if DEBUG_TIME:
print(f"Now: {now}")
time.sleep(0.5)
board_uptime = time.monotonic()
current_datestamp = "{}".format(_format_datetime(now))
current_time = "{}".format(_format_time(now, format=Time_Format))
current_min = "{}".format(_format_min(now))
current_sec = "{}".format(_format_sec(now))
clock_label.text = f"{current_time}"
if DEBUG_TIME:
print(f"Monotonic: {time.monotonic()}")
print(f"Current Time: {current_time}")
print(f"Current Min:Sec: {current_min}:{current_sec}")
print("Board Uptime: ", time_calc(board_uptime))
print("===============================")
if board_uptime > 86400:
print("24 Hour Uptime Restart")
microcontroller.reset()
# Synchronize RTC from NTP every 1 hour on the hour
if current_min == "00" and current_sec == "00":
try:
rtc.RTC().datetime = ntp.datetime
print(f"Synchronized Time: {current_datestamp}")
time.sleep(1)
except OSError as e:
print(f"RTC or NTP Error: {e}")
# SPDX-FileCopyrightText: 2025 DJDevon3
# SPDX-License-Identifier: MIT
# Coded for Circuit Python 9.2.3
"""Matrix Portal S3 NTP Clock"""
import os
import time
import board
import microcontroller
import displayio
import terminalio
import rgbmatrix
import framebufferio
import wifi
import adafruit_connection_manager
import adafruit_requests
import rtc
import adafruit_ntp
from adafruit_display_text import label
from adafruit_bitmap_font import bitmap_font
displayio.release_displays()
# Initalize Wifi, Connection Manager, Request Session
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
requests = adafruit_requests.Session(pool)
# Use settings.toml for credentials
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
DISPLAY_WIDTH = 64
DISPLAY_HEIGHT = 32
DISPLAY_ROTATION = 0
BIT_DEPTH = 4
AUTO_REFRESH = True
DEBUG_TIME = False # For manually testing times
TZ_OFFSET = -5 # time zone offset in hours from UTC
Time_Format = "24" # 12 hour (AM/PM) or 24 hour (military) clock
# Instantiate 64x32 Matrix Panel
matrix = rgbmatrix.RGBMatrix(
width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, bit_depth=BIT_DEPTH,
rgb_pins=[
board.MTX_R1,
board.MTX_G1,
board.MTX_B1,
board.MTX_R2,
board.MTX_G2,
board.MTX_B2],
addr_pins=[board.MTX_ADDRA, board.MTX_ADDRB, board.MTX_ADDRC, board.MTX_ADDRD],
clock_pin=board.MTX_CLK,
latch_pin=board.MTX_LAT,
output_enable_pin=board.MTX_OE,
doublebuffer=True)
# Associate RGB matrix as a Display so we can use displayio
display = framebufferio.FramebufferDisplay(
matrix, auto_refresh=AUTO_REFRESH,
rotation=DISPLAY_ROTATION
)
# Publicly Open NTP Time Server
# No AdafruitIO credentials required
ntp = adafruit_ntp.NTP(pool, tz_offset=TZ_OFFSET)
def time_calc(input_time):
"""Converts seconds to minutes/hours/days"""
if input_time < 60:
return f"{input_time:.0f} seconds"
if input_time < 3600:
return f"{input_time / 60:.0f} minutes"
if input_time < 86400:
return f"{input_time / 60 / 60:.1f} hours"
return f"{input_time / 60 / 60 / 24:.2f} days"
# Custom timestamp functions use struct time format
# You can easily change them to your preferred format
# https://docs.circuitpython.org/en/latest/shared-bindings/time/index.html#time.struct_time
def _format_datetime(datetime):
""" F-String formatted struct time conversion"""
return (f"{datetime.tm_mon:02}/" +
f"{datetime.tm_mday:02}/" +
f"{datetime.tm_year:02} " +
f"{datetime.tm_hour:02}:" +
f"{datetime.tm_min:02}:" +
f"{datetime.tm_sec:02}")
def _format_min(datetime):
""" Get the current minute"""
return (f"{datetime.tm_min:02}")
def _format_sec(datetime):
""" Get the current second"""
return (f"{datetime.tm_sec:02}")
def _format_time(datetime, format="12"):
""" Time is 12 hour or 24 hour format"""
if format == "12":
hour = datetime.tm_hour % 12
min = datetime.tm_min
if hour == 0:
hour = 12
am_pm = "AM"
if datetime.tm_hour / 12 >= 1:
am_pm = "PM"
if DEBUG_TIME:
# Set debug to True & change these to test different times
debug_hour = "09"
debug_min = "09"
return (f"{debug_hour:01}:{debug_min:02} {am_pm}")
else:
return (f"{hour:01}:{min:02} {am_pm}")
if format == "24":
return (f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}")
# Quick Colors for Labels
TEXT_BLACK = 0x000000
TEXT_BLUE = 0x0000FF
TEXT_CYAN = 0x00FFFF
TEXT_GRAY = 0x8B8B8B
TEXT_GREEN = 0x00FF00
TEXT_LIGHTBLUE = 0x90C7FF
TEXT_MAGENTA = 0xFF00FF
TEXT_ORANGE = 0xFFA500
TEXT_PURPLE = 0x800080
TEXT_RED = 0xFF0000
TEXT_TEAL = 0xB2D8D8
TEXT_WHITE = 0xFFFFFF
TEXT_YELLOW = 0xFFFF00
# To use custom font uncomment below and change terminalio.FONT
# font_IBMPlex = bitmap_font.load_font("/fonts/IBMPlexMono-Medium-24_jep.bdf")
clock_label = label.Label(terminalio.FONT)
clock_label.anchor_point = (0.5, 0.5)
clock_label.anchored_position = (DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2)
clock_label.scale = 1
clock_label.color = TEXT_RED
# Groups Setup
main_group = displayio.Group()
main_group.append(clock_label)
display.root_group = main_group
now = time.localtime()
current_datestamp = "{}".format(_format_datetime(now))
try:
rtc.RTC().datetime = ntp.datetime
print(f"Initial Synchronize: {current_datestamp}")
time.sleep(1)
except OSError as e:
print(f"RTC or NTP Error: {e}")
print("===============================")
while True:
now = time.localtime()
if DEBUG_TIME:
print(f"Now: {now}")
time.sleep(0.5)
board_uptime = time.monotonic()
current_datestamp = "{}".format(_format_datetime(now))
current_time = "{}".format(_format_time(now, format=Time_Format))
current_min = "{}".format(_format_min(now))
current_sec = "{}".format(_format_sec(now))
clock_label.text = f"{current_time}"
if DEBUG_TIME:
print(f"Monotonic: {time.monotonic()}")
print(f"Current Time: {current_time}")
print(f"Current Min:Sec: {current_min}:{current_sec}")
print("Board Uptime: ", time_calc(board_uptime))
print("===============================")
if board_uptime > 86400:
print("24 Hour Uptime Restart")
microcontroller.reset()
# Synchronize RTC from NTP every 1 hour on the hour
if current_min == "00" and current_sec == "00":
try:
rtc.RTC().datetime = ntp.datetime
print(f"Synchronized Time: {current_datestamp}")
time.sleep(1)
except OSError as e:
print(f"RTC or NTP Error: {e}")
Fonts and code updates can be found in my Github Repository.
This page (Circuit Python Matrix Portal S3 NTP Clock) was last updated on January 29, 2025.