Network Time Protocol allows for getting the time from specific time servers on a local network or internet.
The example code below assumes you have a settings.toml file in the CIRCUITPY root directory which contains the SSID and password for the local WiFi network, as discussed earlier in this guide.
# SPDX-FileCopyrightText: 2022 Scott Shawcroft for Adafruit Industries
# SPDX-License-Identifier: MIT
"""Print out time based on NTP."""
import os
import time
import socketpool
import wifi
import adafruit_ntp
# Get wifi AP credentials from a settings.toml file
wifi_ssid = os.getenv("CIRCUITPY_WIFI_SSID")
wifi_password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
if wifi_ssid is None:
print("WiFi credentials are kept in settings.toml, please add them there!")
raise ValueError("SSID not found in environment variables")
try:
wifi.radio.connect(wifi_ssid, wifi_password)
except ConnectionError:
print("Failed to connect to WiFi with provided credentials")
raise
pool = socketpool.SocketPool(wifi.radio)
ntp = adafruit_ntp.NTP(pool, tz_offset=0, cache_seconds=3600)
while True:
print(ntp.datetime)
time.sleep(1)
The following code looks for a WiFi capable chip. It it doesn't find one, it looks for the WizNet 5k library and sets up the microcontroller to Ethernet SPI connection.
This code uses the adafruit_ntp and adafruit_connection_manager modules.
# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries
# SPDX-FileCopyrightText: 2024 anecdata for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
"""Print out time based on NTP, using connection manager"""
import adafruit_connection_manager
import adafruit_ntp
# determine which radio is available
try:
import os
import wifi
# adjust method to get credentials as necessary...
wifi_ssid = os.getenv("CIRCUITPY_WIFI_SSID")
wifi_password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
radio = wifi.radio
while not radio.connected:
radio.connect(wifi_ssid, wifi_password)
except ImportError:
import board
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
from digitalio import DigitalInOut
# adjust with busio.SPI() as necessary...
spi = board.SPI()
# adjust pin for the specific board...
eth_cs = DigitalInOut(board.D10)
radio = WIZNET5K(spi, eth_cs)
# get the socket pool from connection manager
socket = adafruit_connection_manager.get_radio_socketpool(radio)
# adjust tz_offset for locale, only ping NTP server every hour
ntp = adafruit_ntp.NTP(socket, tz_offset=-5, cache_seconds=3600)
print(ntp.datetime)
Resources
ReadTheDocs
Examples
Page last edited January 22, 2025
Text editor powered by tinymce.