# Real-time clock using MicroPython
# https://www.hackster.io/kamaluddinkhan/creating-a-real-time-clock-on-encropi-using-micropython-176fe4
from machine import I2C
from machine import Pin, UART,SPI
import sys
import utime
import network
import ntptime
import st7789
import ds1307
import wlan
# import vga1_8x16 as font1
# import vga1_16x16 as font2
import vga1_16x32 as font
INTERVAL = 1000 # millisecond
# Timezone offset (India = UTC +8:00)
UTC_OFFSET = 28800 # 8 * 60 * 60
DISP_WIDTH = 240
DISP_HEIGHT = 240
#sec min hour week day month year
CurrentTime = b'\x00\x50\x14\x05\x21\x06\x22' #00:00:10 friday 03/03/2022
week = ["Sun","Mon","Tues","Wed","Thur","Fri","Sat"];
if(sys.platform=="esp32"):
disp_sck = 18 # default SCK of SPI(1)
disp_mosi = 23 # default MOSI of SPI(1)
disp_miso = 19 # not use
disp_res = 4
disp_dc = 2
disp_cs = 5
disp_blk = 22
# 初始化 SPI
disp_spi = SPI(1, baudrate=20000000, sck=Pin(disp_sck), mosi=Pin(disp_mosi), miso=Pin(disp_miso))
I2C_SDA =21 # GPIO21(I2C SDA)
I2C_SCL =22 # GPIO22(I2C SCL)
# Initialize I2C on GP16 (SDA) and GP17 (SCL)
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=400000) #initializing the I2C method for ESP32
elif(sys.platform=="rp2"):
disp_sck = 18 # default SCK of SPI(0)
disp_mosi = 19 # default MOSI of SPI(0)
disp_miso = 16 # not use
disp_res = 20
disp_dc = 21
disp_cs = 17
disp_blk = 22
# 初始化 SPI
disp_spi = SPI(0, baudrate=24000000, polarity=0, phase=0, bits=8, sck=Pin(disp_sck), mosi=Pin(disp_mosi), miso=None)
I2C_SDA =14 # GPIO14(I2C SDA)
I2C_SCL =15 # GPIO15(I2C SCL)
# Initialize I2C on GP14 (SDA) and GP15 (SCL)
i2c = I2C(1, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=400000)
def info():
# tft.init()
utime.sleep(0.2)
tft.text(font,"RP2040 RTC", 15,20)
tft.fill_rect(15, 60, 210,10, st7789.RED)
tft.text(font,"Real Time", 15,70,st7789.YELLOW)
tft.text(font,"Clock", 15,100,st7789.YELLOW)
tft.fill_rect(15, 140, 210, 10, st7789.BLUE)
utime.sleep(2)
tft.fill(0) #clear screen
def sync_time_with_retry():
try:
print("Syncing with NTP server...")
ntptime.settime() # UTC time
timer = utime.localtime(utime.time() + UTC_OFFSET)
print("Time synchronized.")
return timer
except OSError as e:
# print("Error syncing time:", e)
if e.args[0] == 110: # ETIMEDOUT
print("ETIMEDOUT error during time sync. Retrying in 5 seconds...")
utime.sleep(5)
sync_time_with_retry() # Recursive call to retry
else:
print(f"An unexpected error occurred: {e}")
# Start Function
if __name__ == '__main__':
tft = st7789.ST7789(disp_spi,
DISP_WIDTH, DISP_HEIGHT,
reset=Pin(disp_res, Pin.OUT),
cs=Pin(disp_cs, Pin.OUT),
dc=Pin(disp_dc, Pin.OUT),
backlight=Pin(disp_blk, Pin.OUT),
rotation=0)
print(st7789.__name__, tft.width, "x", tft.height)
info()
rtc = ds1307.DS1307(i2c)
now = (2018, 3, 24, 6, 13, 45, 21, 0)
rtc.datetime(now)
# ========== CONNECT WIFI ==========
wlan.connect_wifi() # Connecting to WiFi Router
# ========== NTP TIME SYNC ==========
print("Syncing time from NTP...")
timer = sync_time_with_retry() # Synchronize the time
rtc.datetime((timer[0], timer[1], timer[2], timer[6] + 1, timer[3], timer[4], timer[5], 0))
lastTime = utime.ticks_ms()
# ========== MAIN LOOP ==========
while True:
try:
currTime = utime.ticks_ms()
if (currTime - lastTime > INTERVAL):
lastTime = currTime
tm = rtc.datetime()
# t = utime.time() + UTC_OFFSET
# tm = utime.localtime(t)
year = "{:04d}".format(tm[0])
month = "{:02d}".format(tm[1])
day = "{:02d}".format(tm[2])
hour = "{:02d}".format(tm[4])
minute = "{:02d}".format(tm[5])
second = "{:02d}".format(tm[6])
# SERIAL PRINT
str_date = year + ":" + month + ":" + day
str_time = hour + ":" + minute + ":" + second
print("Date: " + str_date, end='')
print("; Time: " + str_time)
# DISPLAY
tft.text(font,"Date: ", 15,16,st7789.WHITE)
tft.text(font,str_date, 15,56,st7789.WHITE)
tft.fill_rect(15, 96, 210,10, st7789.RED)
tft.text(font,"Time: ", 15,112,st7789.WHITE)
tft.text(font,str_time, 15,152,st7789.YELLOW)
tft.fill_rect(15, 190, 210, 10, st7789.BLUE)
utime.sleep_ms(100)
except KeyboardInterrupt: # 使用者中斷執行(通常是輸入^C)
pass
Loading
st7789
st7789