【本文发布于https://blog.youkuaiyun.com/Stack_/article/details/119578455,未经许可不得转载,转载须注明出处】
【注意】需要去掉中文注释后上传,否则可能无法上传或运行出错
【注意】以下代码基于3.0.0源代码编译的固件而编写,旧版本的固件可能无法运行
编写代码前的准备
ESP8266和Node MCU扫盲与开发入门
--NTP服务器列表,可百度到
@ 优快云 Tyrion.Mon
NTP_SERVERS = { "ntp.aliyun.com",
"time.asia.apple.com",
"cn.ntp.org.cn",
"time.windows.com",
"cn.pool.ntp.org"
}
--[[以下为WiFi连接配置--]]
wifi.setmode(wifi.STATION) --for when the device is connected to a WiFi router
station_config = {}
station_config.ssid = "你的2.4GWiFi名称"
station_config.pwd = "你的WiFi密码"
station_config.auto = true --自动连接
wifi.sta.config(station_config)
--[[以下为NTP同步--]]
--同步成功处理
function StpSync_OK(sec, usec, server, info)
print('ntp sync', sec, usec, server)
Timer_SyncNTP:interval(3600000)--[[change registered timer's expiry interval, 初次校准成功后更改为每一小时校准一次 PS:参数最大值6870947 (1:54:30.947)--]]
end
--同步失败处理
function StpSync_Fail()
print('ntp sync failed!')
end
--检查WiFi连接并输出
function ConnectCheck()
if (wifi.sta.getip() == nil) then
print("wifi Connecting...")
else
print("wifi Connected, IP is "..wifi.sta.getip())
end
end
--发起同步
function NtpSync()
if (wifi.sta.getip() == nil) then
print("wifi Connecting...")
else
print("wifi Connected, IP is "..wifi.sta.getip())
sntp.sync(NTP_SERVERS, StpSync_OK, StpSync_Fail)
--[[sntp.sync()的第一个参数:服务器.可以是单个,也可以是{服务器列表}--]]
--[[sntp.sync()的第二个参数,校时成功后已自动写入RTC寄存器,并调用此回调函数--]]
--[[sntp.sync()的第三个参数,校时失败的处理--]]
end
end
--打印本地时间
function printTime()
tm = rtctime.epoch2cal(rtctime.get() + 8 * 3600)
print(string.format("%04d/%02d/%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"]))
end
--[[创建定时任务--]]
Timer_ConnectCheck = tmr.create()
Timer_ConnectCheck:register(1000, tmr.ALARM_AUTO, ConnectCheck)
Timer_ConnectCheck:start()
Timer_SyncNTP = tmr.create()
Timer_SyncNTP:register(5000, tmr.ALARM_AUTO, NtpSync) --[[上电之后第一次校时的定时不能太短,否则会出错,未明--]]
Timer_SyncNTP:start()
Timer_Print = tmr.create()
Timer_Print:register(1000, tmr.ALARM_AUTO, printTime)
Timer_Print:start()
wifi Connecting...
1970/01/01 08:00:00
1970/01/01 08:00:00
1970/01/01 08:00:00
1970/01/01 08:00:00
1970/01/01 08:00:00
wifi Connected, IP is 192.168.43.202
1970/01/01 08:00:00
1970/01/01 08:00:00
1970/01/01 08:00:00
ntp sync 1628678432 98286 17.253.84.125
2021/08/11 18:40:32
2021/08/11 18:40:33
2021/08/11 18:40:34
WiFi连接路由器API之设置模式
WiFi连接路由器API之配置WIFI
定时器API – 创建定时器
定时器API – 注册定时器
定时器API – 更改定时器触发间隔
SNTP获取到的一般是UTC时间