1147|1

19

帖子

0

TA的资源

一粒金砂(中级)

楼主
 

【得捷电子Follow me第1期】三:联网和时间同步 + ntp DELTA更新 [复制链接]

  本帖最后由 sss421 于 2023-6-3 23:52 编辑

联网和时间同步内容在第一次公开课有比较 详细的介绍

wifi模块为板载模块,不需要硬件连接部分

wifi模块 连网部分实现如下:

import network
import time
ssid = 'XXX'
password = 'XXXXX'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# 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)
# Handle connection error
if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('connected')
    status = wlan.ifconfig()
    print('ip = ' + status[0])


联网成功后会打印当前获得的IP

raw REPL; CTRL-B to exit

>OK

 

waiting for connection...

waiting for connection...

waiting for connection...

waiting for connection...

waiting for connection...

waiting for connection...

connected

ip = 192.168.2.115

下面是加上OLED的显示 代码


import network
import time
ssid = 'xxx'
password = 'xxx'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# 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)
# Handle connection error
if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('connected')
    status = wlan.ifconfig()
    print('ip = ' + status[0])
# 在这里写上你的代码 :-)
import ntptime
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     ntptime.settime()   # 修改设备时间,到这就已经设置好了
sync_ntp()
from machine import RTC
from time import sleep
i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000)  # Grove - OLED Display 0.96" (SSD1315)
oled = SSD1306_I2C(128, 64, i2c)
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())
    oled.text(s, 0, 16)
    oled.show()
    sleep(1)

 

 

最终效果:

waiting for connection...

waiting for connection...

connected

ip = 192.168.2.115

(2023, 6, 1, 3, 14, 55, 21, 0)

(2023, 6, 1, 3, 14, 55, 22, 0)

(2023, 6, 1, 3, 14, 55, 23, 0)

(2023, 6, 1, 3, 14, 55, 24, 0)

(2023, 6, 1, 3, 14, 55, 25, 0)

(2023, 6, 1, 3, 14, 55, 26, 0)

(2023, 6, 1, 3, 14, 55, 27, 0)

(2023, 6, 1, 3, 14, 55, 28, 0)

(2023, 6, 1, 3, 14, 55, 29, 0)

(2023, 6, 1, 3, 14, 55, 30, 0)

 

 

 

更新,发现UTC修改不生效了,在大佬协助下,发现是utptime库更新导致的

    EPOCH_YEAR = utime.gmtime(0)[0]
    if EPOCH_YEAR == 2000:
        # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 3155673600
    elif EPOCH_YEAR == 1970:
        # (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 2208988800
    else:
        raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))

增加了对不同EPOCH_YEAR的支持,这就导致取巧的NTP_DELTA设置无效了

个性了ntptime库,增加了一个UTC_DELTA的变量,最终代码如下:

from ssd1306 import SSD1306_I2C
import network
import time

ssid = 'xxx'
password = 'xxxx'

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)

# 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)

# Handle connection error
if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('connected')
    status = wlan.ifconfig()
    print('ip = ' + status[0])
# 在这里写上你的代码 :-)
import ntptime
def sync_ntp():
     ntptime.UTC_DELTA = 28800 # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     ntptime.settime()   # 修改设备时间,到这就已经设置好了

sync_ntp()

from machine import RTC,I2C,Pin
from time import sleep

i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000)  # Grove - OLED Display 0.96" (SSD1315)
oled = SSD1306_I2C(128, 64, i2c)
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())
    oled.text(s, 0, 16)
    oled.show()
    sleep(1)

修改后的ntptime.py

import utime

try:
    import usocket as socket
except:
    import socket
try:
    import ustruct as struct
except:
    import struct

# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
host = "pool.ntp.org"
# The NTP socket timeout can be configured at runtime by doing: ntptime.timeout = 2
timeout = 1


def time():
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1B
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.settimeout(timeout)
        res = s.sendto(NTP_QUERY, addr)
        msg = s.recv(48)
    finally:
        s.close()
    val = struct.unpack("!I", msg[40:44])[0]

    EPOCH_YEAR = utime.gmtime(0)[0]
    if EPOCH_YEAR == 2000:
        # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 3155673600
    elif EPOCH_YEAR == 1970:
        # (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 2208988800
    else:
        raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))
    
    try:
        UTC_DELTA
    except NameError:
        pass
    else:
        NTP_DELTA = NTP_DELTA - UTC_DELTA

    return val - NTP_DELTA


# There's currently no timezone support in MicroPython, and the RTC is set in UTC time.
def settime():
    t = time()
    import machine

    tm = utime.gmtime(t)
    machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))

 

最新回复

这代码也够长了啊   详情 回复 发表于 2023-6-3 10:51
点赞 关注
 
 

回复
举报

6861

帖子

0

TA的资源

五彩晶圆(高级)

沙发
 

这代码也够长了啊

 
 
 

回复
您需要登录后才可以回帖 登录 | 注册

查找数据手册?

EEWorld Datasheet 技术支持

相关文章 更多>>
关闭
站长推荐上一条 1/9 下一条

 
EEWorld订阅号

 
EEWorld服务号

 
汽车开发圈

About Us 关于我们 客户服务 联系方式 器件索引 网站地图 最新更新 手机版

站点相关: 国产芯 安防电子 汽车电子 手机便携 工业控制 家用电子 医疗电子 测试测量 网络通信 物联网

北京市海淀区中关村大街18号B座15层1530室 电话:(010)82350740 邮编:100190

电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号 Copyright © 2005-2025 EEWORLD.com.cn, Inc. All rights reserved
快速回复 返回顶部 返回列表