Skip to content

Instantly share code, notes, and snippets.

@anthonyclarka2
Created February 20, 2022 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyclarka2/43fc067a75895d4cc9221bad3fb0a8f4 to your computer and use it in GitHub Desktop.
Save anthonyclarka2/43fc067a75895d4cc9221bad3fb0a8f4 to your computer and use it in GitHub Desktop.
Sets the time of the Adafruit DS3231 realtime clock (RTC) via the Adafruit API time service
import ssl
import wifi
import socketpool
import adafruit_requests
import secrets
import adafruit_ds3231
import board
import time
# Sets the time of the DS3231 realtime clock (RTC) from Adafruit
# https://www.adafruit.com/product/3013
# https://circuitpython.readthedocs.io/projects/ds3231/en/latest/index.html
# https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/overview
# Get wifi details and more from a secrets.py file
# Format of file is:
# secrets = {
# "ssid": "YOUR_SSID_HERE",
# "password": "WIFI_PASSWORD_HERE",
# 'aio_username' : 'ADAFRUIT_IO_USERNAME_HERE',
# 'aio_key' : 'ADAFRUIT_IO_API_KEY_HERE',
# 'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
# }
# You will need an adafruit.io API key:
# https://io.adafruit.com/
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# Get our username, key and desired timezone
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]
location = secrets.get("timezone", None)
TIME_URL = "https://io.adafruit.com/api/v2/%s/integrations/time/strftime?x-aio-key=%s" % (aio_username, aio_key)
TIME_URL += "&fmt=%25s"
i2c = board.I2C() # uses board.SCL and board.SDA
rtc = adafruit_ds3231.DS3231(i2c)
print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!"%secrets["ssid"])
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
response = requests.get(TIME_URL)
print(response.text)
remote_time = time.localtime(int(response.text))
print(remote_time)
rtc.datetime = remote_time
current = rtc.datetime
print('The current time is: {}/{}/{} {:02}:{:02}:{:02}'.format(current.tm_mon, current.tm_mday, current.tm_year, current.tm_hour, current.tm_min, current.tm_sec))
@anthonyclarka2
Copy link
Author

You will need a CircuitPython compatible board from Adafruit. The one I used was the Metro ESP32-S2: https://www.adafruit.com/product/4775

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment