M5Stack学习笔记(7)—— 同NTP服务器同步时间

M5Stack里的时钟可以自动和NTP服务器同步时间。

首先设置Wifi连接,才能够连上wifi,这个在设置菜单里有,官方教程有详细介绍。
https://docs.m5stack.com/#/en/quick_start/m5core/m5stack_core_get_started_MicroPython

设置好wifi之后,就可以在MicroPython中连接wifi了。
在MicroPython代码中连上wifi的语句是:

import wifisetup
wifisetup.auto_connect()

注意:这里如果在REPL执行会暴露SSID和相对应的密码。

连接wifi成功之后就可以和NTP服务器同步时间啦。

>>> rtc = machine.RTC()
>>> rtc.ntp_sync(server = "ntp.aliyun.com",tz='CST-8')
>>> rtc.synced()
False
>>> rtc.synced()
True
>>> time.gmtime()
(2019, 6, 9, 11, 5, 45, 1, 160)
>>> time.localtime()
(2019, 6, 9, 19, 5, 45, 1, 160)
>>> time.strftime('%Y/%m/%d %H:%M:%S',time.localtime())
'2019/06/09 19:05:46'
>>>
  • 上面NTP服务器用的是阿里云的NTP服务器,也可以用其他的,只要稳定工作连接可靠的服务器即可。NTP服务器网上一搜一大把。
  • tz='CST-8’的意思是,当前时间为CST(中国标准时),格林威治时间比当前时区的时间延后8个小时。
  • rtc.synced()可以检查是否已同步
  • time.gmtime()是GMT时间
  • time.localtime()是当前时区的时间
  • time.strftime可以得到格式化的时间字符串

M5Stack可以有准确时间后,我就把上次记录温度的程序改了下,加入了准确时间的数据。保存数据的文件名也以启动程序时的日期时间命名。

from m5stack import *
from m5ui import *
import units
import wifisetup
wifisetup.auto_connect()

rtc = machine.RTC()
rtc.ntp_sync(server = "ntp.aliyun.com",tz='CST-8')
while not rtc.synced():
    print("Waiting time synced with NTC server.")
    wait(0.2)


clear_bg(0x0)
env0 = units.ENV(units.PORTA)


flag_rec  = False
flag_disp = True
inteval   = 30  # seconds
filename  = '/sd/' + time.strftime('%Y%m%d_%H%M%S',time.localtime())+'.csv'

if 'sd' in os.listdir('/'):
    flag_sd  = True
    sd_info  = 'SD Mounted'
    sd_color = 0x00FF00
else:
    flag_sd  = False
    sd_info  = 'SD Not Mounted'
    sd_color = 0xFFFF00  


btnA    = M5Button(name="ButtonA", text="Rec", visibility=True)
btnB    = M5Button(name="ButtonB", text="SD", visibility=True)
btnC    = M5Button(name="ButtonC", text="Display", visibility=True)

label_t  = M5TextBox(0, 0, "Text", lcd.FONT_DejaVu24,0xFFFFFF, rotate=0)
label_h  = M5TextBox(0, 25, "Text", lcd.FONT_DejaVu24,0xFFFFFF, rotate=0)
label_p  = M5TextBox(0, 50, "Text", lcd.FONT_DejaVu24,0xFFFFFF, rotate=0)
label_s  = M5TextBox(0, 100, "REC stopped.", lcd.FONT_DejaVu24,0xFFFF00, rotate=0)
label_mt = M5TextBox(0, 150, sd_info, lcd.FONT_DejaVu24, 0xFFFF00, rotate=0)


def buttonA_pressed():
    # Rec Start/Stop
    global flag_disp
    global flag_rec
    global flag_sd
    if flag_disp and flag_sd:
        if flag_rec:
            flag_rec = False
            label_s.setText("REC stopped.")
            label_s.setColor(0xFFFF00)
        else:
            flag_rec = True
            label_s.setText("REC started.")
            label_s.setColor(0xFF0000)


def buttonC_pressed():
    # Display On/Off
    global flag_disp
    if flag_disp:
        flag_disp = False
        clear_bg(0x0)
        lcd.setBrightness(0)      
    else:
        flag_disp = True
        lcd.setBrightness(50)
        clear_bg(0x222222)
        
        label_t.show()
        label_h.show()
        label_p.show()
        label_s.show()
        label_mt.show()
        

def buttonB_pressed():
    # Display On/Off
    global flag_disp
    global flag_sd
    global flag_rec
    if flag_disp:
        if flag_sd and (not flag_rec):
            flag_sd = False
            label_mt.setText("SD Not Mounted")
            label_mt.setColor(0xFFFF00)
            os.umountsd()

        else:
            flag_sd = True
            label_mt.setText("SD Mounted")
            label_mt.setColor(0x00FF00)
            os.mountsd()

def save_tofile(rec_string):
    f = open(filename,'a+')
    f.write(rec_string)
    f.close()


buttonA.wasPressed(callback = buttonA_pressed)
buttonC.wasPressed(callback = buttonC_pressed)
buttonB.wasPressed(callback = buttonB_pressed)

timesec_start = round(time.time())
time_tick     = timesec_start - inteval

#save_tofile("SEC,TEMP,HUMI,PRES\n")

while True:
    label_t.setText("TEMP: " + str(env0.temperature()))
    label_h.setText("HUMI: " + str(env0.humidity()))
    label_p.setText("PRES: " + str(env0.pressure()))

    if flag_rec:
        if time.time() - time_tick >= inteval:
            save_tofile("%s,%s,%s,%s\n" % (time.strftime('%Y/%m/%d %H:%M:%S',time.localtime()), str(env0.temperature()), str(env0.humidity()), str(env0.pressure())))
            time_tick = time.time()

    wait(1)

你可能感兴趣的:(M5Stack学习笔记(7)—— 同NTP服务器同步时间)