例程讲解14-WiFi-Shield->ntp 获取当前时间

# NTP Example
#
# 这个例子展示了如何使用WiFi扩展板或OpenMV RT自带WIFI的NTP获取当前时间。

import network
import socket
import struct
import time

SSID = ""  # Network SSID 
KEY = ""  # Network key

TIMESTAMP = 2208988800

if time.gmtime(0)[0] == 2000:
    TIMESTAMP += 946684800

# 初始化wlan模块并连接到网络
print("Trying to connect... (This may take a while)...")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, KEY)

while not wlan.isconnected():
    print('Trying to connect to "{:s}"...'.format(SSID))
    time.sleep_ms(1000)

# 我们现在通过DHCP应该有一个有效的IP
print("WiFi Connected ", wlan.ifconfig())

# 创建新的套接字
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 通过DNS获取地址信息
addr = socket.getaddrinfo("pool.ntp.org", 123)[0][4]

# 发送查询
client.sendto("\x1b" + 47 * "\0", addr)
data, address = client.recvfrom(1024)

# 打印时间
t = struct.unpack(">IIIIIIIIIIII", data)[10] - TIMESTAMP
print("Year:%d Month:%d Day:%d Time: %d:%d:%d" % (time.localtime(t)[0:6]))

星瞳科技OpenMV官方中文文档函数讲解:

results matching ""

    No results matching ""