from machine import Pin, I2C
import ssd1306
import machine,utime,time,network,urequests,ujson,gc
from machine import Timer
nyear=2000;nmonth=1;ndate=1;nhour=1;nmin=1;nsec=1; nweek=1;unumber=0;newT=0
# sub-program section
def go_wifi():
try:
wifi.active(False)
wifi.active(True)
wifi.connect('Wokwi-GUEST','') ## wifi ssid and password
print('start to connect wifi')
for i in range(20):
print('try to connect wifi in {}s'.format(i))
utime.sleep(1)
if wifi.isconnected():
break
if wifi.isconnected():
print('WiFi connection OK!')
print('Network Config=',wifi.ifconfig())
else:
print('WiFi connection Error')
except Exception as e: print(e)
def get_net_time():
clk_url='http://worldtimeapi.org/api/timezone/asia/taipei'
global nyear,nmonth,ndate,nhour,nmin,nsec,nweek,newT,nsecd
try:
gc.collect()
clk_response= urequests.get(clk_url) # get network time json
if clk_response.status_code == 200:
json_data=ujson.loads(clk_response.text)['datetime']
week_data=ujson.loads(clk_response.text)['day_of_week']
nyear=int(json_data[0:4]) #get year
nmonth =int(json_data[5:7]) #get month
ndate=int(json_data[8:10])
nhour=int(json_data[11:13])
nmin=int(json_data[14:16])
nsec=int(json_data[17:19])
nsecd=int(json_data[20:26])
nweek=int(week_data)
print("Time_Update Okay")
newT=1
clk_response.close()
else :
clk_response.close()
newT=0
print("update fail")
except Exception as e:
print(e)
print('get net error !')
newT=0
go_wifi()
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('yuchi', 20, 2)
oled.show()
wifi= network.WLAN(network.STA_IF)
go_wifi()
get_net_time()
newT=0
rtc = machine.RTC()
rtc.init((nyear,nmonth,ndate,nweek,nhour,nmin,nsec,nsecd))
print(rtc.datetime())
print("Clock Start!")
# main-loop section
while 1:
utime.sleep(0.1)
oled.fill(0)
#print(rtc.datetime())
oled.text('Yuchi', 40, 2)
ymd = 'Y/M/D:' + str(rtc.datetime()[0])+'/'+ str(rtc.datetime()[1])+'/'+ str(rtc.datetime()[2])
oled.text(ymd, 0, 15)
week = 'Week:' + str(rtc.datetime()[3]+1)
oled.text(week, 0, 30)
HMS = 'H:M:S ' + str(rtc.datetime()[4])+':'+ str(rtc.datetime()[5])+':'+ str(rtc.datetime()[6])
oled.text(HMS, 10, 45)
oled.show()
if rtc.datetime()[6] == 0:
wifi= network.WLAN(network.STA_IF)
go_wifi()
get_net_time()
newT=0
rtc = machine.RTC()
rtc.init((nyear,nmonth,ndate,nweek,nhour,nmin,nsec,nsecd))
print(rtc.datetime())
print("Clock Restart!")