ESP32-联网、同步时间


前言

提示:ESP32模块RTC的精度存在一定的缺陷,每过7:45h便会有秒级别的误差溢出,所以esp上,官方建议每隔7小时进行一次时间的校准。


一、WIFI联网

ESP32支持WIFI网络

二、通过网络同步时间

1.创建代码

代码如下(示例):

import ntptime
import network,time
from machine import RTC,Pin
rtc = RTC()

print("同步前本地时间:%s" %str(time.localtime()))

led=Pin(2,Pin.OUT)

# 联WIFI
def WIFI_Connect():

    wlan = network.WLAN(network.STA_IF) #STA模式
    wlan.active(True)                   #激活接口
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('WIFI_NAME', 'WIFI_password') #输入WIFI账号密码
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('WIFI Connected Timeout!')
                break
    if wlan.isconnected():
        print('connected!')
        print('network information:', wlan.ifconfig())

# 同步时间
def sync_ntp():
     ntptime.NTP_DELTA = 3155644800   # 可选 UTC+8偏移时间(秒),不设置就是UTC0
     ntptime.host = 'ntp1.aliyun.com'  # 可选,ntp服务器,默认是"pool.ntp.org"
     try:
         ntptime.settime()   # 修改设备时间,到这就已经设置好了
     except:
         for i in range(6):
            led.value(1)              #turn off 0是亮
            time.sleep(0.1)
            led.value(0)             
            time.sleep(0.1)
         print('同步失败')

if __name__ == '__main__':
    WIFI_Connect()
    sync_ntp()
    print(rtc.datetime())
    print("同步后本地时间:%s" %str(time.localtime()))

2.保存运行

代码运行如下(示例):

>>> %Run -c $EDITOR_CONTENT
同步前本地时间:(2022, 1, 2, 0, 54, 7, 6, 2)
connected!
network information: ('192.168.123.18', '255.255.255.0', '192.168.123.1', '192.168.123.1')
(2022, 1, 2, 6, 0, 54, 10, 303)
同步后本地时间:(2022, 1, 2, 0, 54, 10, 6, 2)

总结

提示:由于是通过网络同步时间,为防止网络不稳定,需要加入容错处理。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值