Simple test
Ensure your device works with this simple test that prints out the time from NTP.
examples/ntp_simpletest.py
1# SPDX-FileCopyrightText: 2022 Scott Shawcroft for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Print out time based on NTP."""
5
6import os
7import time
8
9import socketpool
10import wifi
11
12import adafruit_ntp
13
14# Get wifi AP credentials from a settings.toml file
15wifi_ssid = os.getenv("CIRCUITPY_WIFI_SSID")
16wifi_password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
17if wifi_ssid is None:
18 print("WiFi credentials are kept in settings.toml, please add them there!")
19 raise ValueError("SSID not found in environment variables")
20
21try:
22 wifi.radio.connect(wifi_ssid, wifi_password)
23except ConnectionError:
24 print("Failed to connect to WiFi with provided credentials")
25 raise
26
27pool = socketpool.SocketPool(wifi.radio)
28ntp = adafruit_ntp.NTP(pool, tz_offset=0, cache_seconds=3600)
29
30while True:
31 print(ntp.datetime)
32 time.sleep(1)
Set RTC
Sync your CircuitPython board’s realtime clock (RTC) with time from NTP.
examples/ntp_set_rtc.py
1# SPDX-FileCopyrightText: 2022 Scott Shawcroft for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Example demonstrating how to set the realtime clock (RTC) based on NTP time."""
5
6import os
7import time
8
9import rtc
10import socketpool
11import wifi
12
13import adafruit_ntp
14
15# Get wifi AP credentials from a settings.toml file
16wifi_ssid = os.getenv("CIRCUITPY_WIFI_SSID")
17wifi_password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
18if wifi_ssid is None:
19 print("WiFi credentials are kept in settings.toml, please add them there!")
20 raise ValueError("SSID not found in environment variables")
21
22try:
23 wifi.radio.connect(wifi_ssid, wifi_password)
24except ConnectionError:
25 print("Failed to connect to WiFi with provided credentials")
26 raise
27
28pool = socketpool.SocketPool(wifi.radio)
29ntp = adafruit_ntp.NTP(pool, tz_offset=0, cache_seconds=3600)
30
31# NOTE: This changes the system time so make sure you aren't assuming that time
32# doesn't jump.
33rtc.RTC().datetime = ntp.datetime
34
35while True:
36 print(time.localtime())
37 time.sleep(1)
Simple test with CPython
Test the library in CPython using socket.
examples/ntp_cpython.py
1# SPDX-FileCopyrightText: 2022 Scott Shawcroft for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Tests NTP with CPython socket"""
5
6import socket
7import time
8
9import adafruit_ntp
10
11# Don't use tz_offset kwarg with CPython because it will adjust automatically.
12ntp = adafruit_ntp.NTP(socket, cache_seconds=3600)
13
14while True:
15 print(ntp.datetime)
16 time.sleep(1)