【MicroPython ESP32】通过ntptime模块获取NTP获取网络时间

20240720235403816-image

 

话不多说·,直接上代码,亲测没问题

import time
import ntptime
import network



# 使用NTP同步RTC
while True:  # 时间校准
    try:
        print('Syncing time...')
        ntptime.settime()
        print('Time sync successful')
        break
    except:
        print('Time sync failed, retrying...')
        time.sleep(1)

def get_ip_address():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('Connecting to network...')
        wlan.connect('Xiaomi_FANFAN', 'yangfan0522')  # 修改为您的SSID和密码
        while not wlan.isconnected():
            time.sleep(1)  # 等待网络连接
    ip_address = wlan.ifconfig()[0]
    return ip_address

try:
    ip_address = get_ip_address()
except Exception as e:
    print(f"Error getting IP address: {e}")
    ip_address = 'No IP'

# 预定义时间和IP地址显示区域
time_rect = (0, 80, 320, 60)  # (x, y, width, height) of the time display area
ip_rect = (0, 140, 320, 20)   # (x, y, width, height) of the IP address display area
get_ip_address()
while True:
    mytime = time.localtime()

    # 获取小时、分钟和秒,并添加零前缀
    hours = (mytime[3] + 8) % 24
    minutes = mytime[4]
    seconds = mytime[5]

    hours_str = f'{hours:02d}'
    minutes_str = f'{minutes:02d}'
    seconds_str = f'{seconds:02d}'


    print(f'{hours_str}:{minutes_str}:{seconds_str}')


    time.sleep(1)
© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容