Simple test¶
Ensure your device works with this simple test that prints out the time from NTP.
1# SPDX-FileCopyrightText: 2022 Scott Shawcroft for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Print out time based on NTP."""
5
6import time
7
8import socketpool
9import wifi
10
11import adafruit_ntp
12
13# Get wifi details and more from a secrets.py file
14try:
15 from secrets import secrets
16except ImportError:
17 print("WiFi secrets are kept in secrets.py, please add them there!")
18 raise
19
20wifi.radio.connect(secrets["ssid"], secrets["password"])
21
22pool = socketpool.SocketPool(wifi.radio)
23ntp = adafruit_ntp.NTP(pool, tz_offset=0)
24
25while True:
26 print(ntp.datetime)
27 time.sleep(1)
Set RTC¶
Sync your CircuitPython board’s realtime clock (RTC) with time from NTP.
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 time
7
8import rtc
9import socketpool
10import wifi
11
12import adafruit_ntp
13
14# Get wifi details and more from a secrets.py file
15try:
16 from secrets import secrets
17except ImportError:
18 print("WiFi secrets are kept in secrets.py, please add them there!")
19 raise
20
21wifi.radio.connect(secrets["ssid"], secrets["password"])
22
23pool = socketpool.SocketPool(wifi.radio)
24ntp = adafruit_ntp.NTP(pool, tz_offset=0)
25
26# NOTE: This changes the system time so make sure you aren't assuming that time
27# doesn't jump.
28rtc.RTC().datetime = ntp.datetime
29
30while True:
31 print(time.localtime())
32 time.sleep(1)
Simple test with CPython¶
Test the library in CPython using socket
.
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)
13
14while True:
15 print(ntp.datetime)
16 time.sleep(1)