ntp 服务器可以自己选择,可以使用爬虫爬去时间也可以用 NTP 服务器同步,将 wifi_connect()函数最后一行 get_time_py 换成 get_time()即可
直接上程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
from machine import Pin,RTC import network import time import ntptime
def wifi_connect(): wifi_led=Pin(18,Pin.OUT) wlan = network.WLAN(network.STA_IF) wlan.active(True) start_time=time.time()
if not wlan.isconnected(): print("当前无线未联网,正在连接中....") wlan.connect('XXXXXXXX','XXXXXXXX') while not wlan.isconnected(): wifi_led.value(0) time.sleep_ms(1000) wifi_led.value(1) time.sleep_ms(1000) print("正在尝试连接到wifi....") print(time.time())
if time.time()-start_time>15: print("連接失敗!!!請檢查無綫網名稱和密碼是否正確...") break
if wlan.isconnected(): wifi_led.value(1) IP_info=wlan.ifconfig() print("##################################################") print("已連接WIFI,信息如下:") print("IP地址:"+IP_info[0]) print("子網掩碼:"+IP_info[1]) print("網関:"+IP_info[2]) print("DNS:"+IP_info[3]) print("##################################################") get_time_py()
def get_time(): print("同步時間") print() print("同步前本地時間:%s" %str(time.localtime())) print("##") ntptime.NTP_DELTA = 3155644800
ntptime.host = 'edu.ntp.org.cn'
ntptime.settime() print("同步后本地時間:%s" %str(time.localtime())) print("##################################################") rtc = RTC() print(rtc.datetime())
def get_time_py(): time_api_url = """http://quan.suning.com/getSysTime.do""" r = request.get(time_api_url) content = r.text print('爬取時間...') time = re.search( r'{"sysTime2":"(.*?)-(.*?)-(.*?) (.*?):(.*?):(.*?)","sysTime1":"', content ) print(r.text[13:29]) print(int(r.text[27:29])) print(int(r.text[23:26])) mm = int(r.text[27:29]) hh = int(r.text[23:26]) rtc = RTC() time_date = rtc.datetime() print('重置時間!') rtc.datetime((time_date[0], time_date[1], time_date[2], time_date[3], hh, mm, time_date[6], time_date[7])) rtc.datetime()
wifi_connect()
|