ntp_simpletest.py
1 import time 2 import board 3 import busio 4 from digitalio import DigitalInOut 5 from adafruit_esp32spi import adafruit_esp32spi 6 from adafruit_ntp import NTP 7 8 # If you are using a board with pre-defined ESP32 Pins: 9 esp32_cs = DigitalInOut(board.ESP_CS) 10 esp32_ready = DigitalInOut(board.ESP_BUSY) 11 esp32_reset = DigitalInOut(board.ESP_RESET) 12 13 # If you have an externally connected ESP32: 14 # esp32_cs = DigitalInOut(board.D9) 15 # esp32_ready = DigitalInOut(board.D10) 16 # esp32_reset = DigitalInOut(board.D5) 17 18 spi = busio.SPI(board.SCK, board.MOSI, board.MISO) 19 esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) 20 21 print("Connecting to AP...") 22 while not esp.is_connected: 23 try: 24 esp.connect_AP(b"WIFI_SSID", b"WIFI_PASS") 25 except RuntimeError as e: 26 print("could not connect to AP, retrying: ", e) 27 continue 28 29 # Initialize the NTP object 30 ntp = NTP(esp) 31 32 # Fetch and set the microcontroller's current UTC time 33 # keep retrying until a valid time is returned 34 while not ntp.valid_time: 35 ntp.set_time() 36 print("Failed to obtain time, retrying in 5 seconds...") 37 time.sleep(5) 38 39 # Get the current time in seconds since Jan 1, 1970 40 current_time = time.time() 41 print("Seconds since Jan 1, 1970: {} seconds".format(current_time)) 42 43 # Convert the current time in seconds since Jan 1, 1970 to a struct_time 44 now = time.localtime(current_time) 45 print(now) 46 47 # Pretty-parse the struct_time 48 print( 49 "It is currently {}/{}/{} at {}:{}:{} UTC".format( 50 now.tm_mon, now.tm_mday, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec 51 ) 52 )