【得捷电子Follow me第1期】任务3 网络时间同步
[复制链接]
一,先来个连接网络,
开机第一次连接需要等待一段时间,如果连接上了,会打印IP地址,见下图。
代码如下:
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('---', '---')
while not wlan.isconnected() and wlan.status() >= 0:
print("Waiting to connect:")
time.sleep(1)
print(wlan.ifconfig())
第二:通过网络获取时间,并显示
实验五
代码如下:
import network
import time
from time import sleep
from machine import RTC
import ntptime
from machine import Pin, I2C
from SSD1306 import SSD1306_I2C
import framebuf
# import ufont
WIDTH = 128 # oled display width
HEIGHT = 64 # oled display height
i2c = I2C(1) # Init I2C using I2C0 defaults, SCL=Pin(GP9), SDA=Pin(GP8), freq=400000
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c) # Init oled display
ssid='xxxxx'
passwd='xxxxxx'
wlan = None
max_wait = 10
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, passwd)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
status = wlan.ifconfig()
print('ip = ' + status[0])
def sync_ntp():
ntptime.NTP_DELTA = 3155644800 # 可选 UTC+8偏移时间(秒),不设置就是UTC0
ntptime.host = 'ntp1.aliyun.com' # 可选,ntp服务器,默认是"pool.ntp.org"
ntptime.settime() # 修改设备时间,到这就已经设置好了
oled.fill(0) # clear
oled.text("NTP Time:", 0, 0)
oled.show()
while True:
rtc = RTC()
print(rtc.datetime())
oled.fill(0) # clear
oled.text("NTP Time:", 0, 0)
#s = ','.join(str(i) for i in rtc.datetime())
s = str(rtc.datetime()[0]) + '-' + str(rtc.datetime()[1]) + '-' + str(rtc.datetime()[2])
oled.text(s, 10, 16)
s = str(rtc.datetime()[4]) + '-' + str(rtc.datetime()[5]) + '-' + str(rtc.datetime()[6])
oled.text(s, 10, 32)
s = "IP:" + str(status[0])
oled.text(s, 0, 48)
oled.show()
sleep(1)
后记:
SSD1306一开始导入库,无法识别,导致一直编译不过去,但是经过几次重装系统,终于也能编译过去,可能是通过软件的--工具--软件包管理进行安装一次的缘故吧,我也是猜测,一直没搞明白。有哪些网友能解惑的留言给我一下,谢谢。
|