ESP32+MicroPython+SSD1036 0.96寸OLED实现天气时钟2.0

优化点:

1、_thread线程改成定时器

ESP32支持4个定时器Timer(0 1 2 3)

The ESP32 port has four hardware timers. Use the machine.Timer class with a timer ID from 0 to 3 (inclusive):

from machine import Timer

tim0 = Timer(0)
tim0.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(0))

tim1 = Timer(1)
tim1.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(1))

2、RTC时钟

The RTC is an independent clock that keeps track of the date and time.

Example usage:

rtc = machine.RTC()
rtc.datetime((2020, 1, 21, 2, 10, 32, 36, 0))
print(rtc.datetime())

3、10分钟定时同步NTP时间

def sync_ntp(prt=False):
    for i in range(1,11):
        try:  
            """通过网络校准时间"""
            ntptime.NTP_DELTA = 3155644800  # 可选 UTC+8偏移时间(秒),不设置就是UTC0
            ntptime.host = 'pool.ntp.org'  # 可选,ntp服务器,默认是"pool.ntp.org" 这里使用阿里服务器
            ntptime.settime()  # 修改设备时间,到这就已经设置好了
            print("set ntp time ok!")
            if prt:
                oled.fill(0)  #清空屏幕
                oled.text("set ntp time ok!", 10, 10)
                oled.show()
                time.sleep(1)
            break
        except OSError as e:  
            if e.errno == 116:  # [Errno 116] ETIMEDOUT  
                print("Connection timed out. Retrying...")  
                # Handle the timeout situation, e.g., retry the operation  
            else:  
                # Handle other OSError exceptions  
                print("An error occurred:", e)   
            oled.fill(0)  #清空屏幕
            oled.text("set ntp time timed out. Retrying...", 10, 10)
            oled.show()
            time.sleep(1)

最后直接上mian.py

from lib import urequests
from machine import Pin,I2C
from machine import SoftI2C
from machine import Timer
from machine import RTC
from ssd1306 import SSD1306_I2C #从ssd1306模块中导入SSD1306_I2C子模块
import time,ntptime,network
import ujson
import sys
import _thread
import re  

#创建RTC对象
rtc=RTC()

#创建软件I2C对象
i2c = SoftI2C(sda=Pin(23), scl=Pin(18))
#创建OLED对象,OLED分辨率、I2C接口
oled = SSD1306_I2C(128, 64, i2c)

#定义LED控制对象
led1=Pin(15,Pin.OUT)
led1.value(0)
# 心知天气API申请:https://seniverse.yuque.com
# API_KEY = 'S9hoa4Wza9Hcs2uX_'
#接口;https://api.seniverse.com/v3/weather/now.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c
# LOCATION = 'zhuzhou'
# URL = 'https://api.seniverse.com/v3/weather/now.json'
# UNIT = 'c'
# LANGUAGE = 'zh-Hans'

#路由器WIFI账号和密码
ssid="FAST_0DB8"
password="xxxxxxx"

#WIFI连接
def wifi_connect():
    wlan=network.WLAN(network.STA_IF)  #STA模式
    wlan.active(True)  #激活
    #start_time=time.time()  #记录时间做超时判断
    
    cnt = 0
    if not wlan.isconnected():
        print("conneting to network...")
        oled.fill(0)  #清空屏幕
        oled.text("conneting to wifi...", 10, 10)
        oled.show()
        time.sleep(1)

        wlan.connect(ssid,password)  #输入 WIFI 账号密码
        
        while not wlan.isconnected():
            cnt += 1
            led1.value(1)
            time.sleep(0.5)
            led1.value(0)
            time.sleep(0.5)
            print("cnt", cnt)
            #超时判断,15 秒没连接成功判定为超时
            if cnt > 15:
                print("WIFI Connect Timeout!")
                oled.fill(0)  #清空屏幕
                oled.text("WIFI Connect Timeout!", 10, 10)
                oled.show()
                time.sleep(1)
                return False
        return True 
    else:
        print("network information:", wlan.ifconfig())
        oled.fill(0)  #清空屏幕
        oled.text("WIFI Connect OK!", 10, 10)
        oled.show()
        time.sleep(1)
        return True

def sync_ntp(prt=False):
    for i in range(1,11):
        try:  
            """通过网络校准时间"""
            ntptime.NTP_DELTA = 3155644800  # 可选 UTC+8偏移时间(秒),不设置就是UTC0
            ntptime.host = 'pool.ntp.org'  # 可选,ntp服务器,默认是"pool.ntp.org" 这里使用阿里服务器
            ntptime.settime()  # 修改设备时间,到这就已经设置好了
            print("set ntp time ok!")
            if prt:
                oled.fill(0)  #清空屏幕
                oled.text("set ntp time ok!", 10, 10)
                oled.show()
                time.sleep(1)
            break
        except OSError as e:  
            if e.errno == 116:  # [Errno 116] ETIMEDOUT  
                print("Connection timed out. Retrying...")  
                # Handle the timeout situation, e.g., retry the operation  
            else:  
                # Handle other OSError exceptions  
                print("An error occurred:", e)   
            oled.fill(0)  #清空屏幕
            oled.text("set ntp time timed out. Retrying...", 10, 10)
            oled.show()
            time.sleep(1)

def fetchWeather():
    result = urequests.get("https://api.seniverse.com/v3/weather/now.json?key=S9hoa4Wza9Hcs2uX_&location=shenzhen&language=zh-Hans&unit=c")       
    return result.text

class CWeather:
    def __init__(self, addr="", weather="", temperature=""):
        self.addr = addr
        self.weather = weather
        self.temperature = temperature

g_weather = CWeather()

def threadFetchWeather(tim0):
    global g_weather
    
    print("=======================threadFetchWeather=========================")
    result = urequests.get("https://api.seniverse.com/v3/weather/now.json?key=S9hoa4Wza9Hcs2uX_&location=shenzhen&language=zh-Hans&unit=c") 
    text = result.text
    result.close()
    
    print("text", text)
    j=ujson.loads(text)
    print(j['results'][0]['location']['name'])
    print(j['results'][0]['now']['text'])
    print(j['results'][0]['now']['temperature'])
    print(j['results'][0]['last_update'])
    print("\r\n\r\n")
  
    g_weather.addr=j['results'][0]['location']['name']
    g_weather.weather=j['results'][0]['now']['text']
    g_weather.temperature=j['results'][0]['now']['temperature']
    
    sync_ntp(True)

    localTime = time.localtime()
    # 设置新的本地时间  
    new_time = (localTime[0], localTime[1], localTime[2], 0, localTime[3], localTime[4], localTime[5], 0)

    #设置RTC时间
    rtc.datetime(new_time)
    print("set rtc ok!!!")
  
def threadShowOled(tim1):
    global oled
    global g_weather

    #oled.fill(0)  #清空屏幕
    oled.text("ESP32 Weather Clock", 4, 0)
    oled.line(0, 14, 128, 14, 1)#划线
    oled.show()
    
    print("show oled:%s %s %s"%(g_weather.addr, g_weather.weather, g_weather.temperature))
    if 0  == len(g_weather.addr):
        return

    oled.fill(0)  #清空屏幕
    oled.text("ESP32 Weather Clock", 4, 0)
    oled.line(0, 14, 128, 14, 1)#划线

    oled.text("地点:%s"%g_weather.addr,0,16)
    oled.text("天气:%s 温度:%s℃"%(g_weather.weather, g_weather.temperature),0,32)

    localtime = rtc.datetime()
    print("localtime: ", localtime)
    strTime = ("%d-%02d-%02d %02d:%02d:%02d"%(localtime[0], localtime[1], localtime[2], localtime[4], localtime[5], localtime[6]))
    print(strTime)
    oled.text("%s"%strTime,0,48)
    oled.show()




if __name__ == '__main__':
#def test():
    oled.font_load("GB2312-12.fon")# 所使用的字体时12号字体
    
    print("begin connect wifi")    
    if wifi_connect():
        print("connect wifi success")
    else:
        print("connect wifi failed")
        sys.exit(0)

    sync_ntp()

    # 天气10分钟获取一次
    tim0 = Timer(0)
    threadFetchWeather(tim0)
    tim0.init(period=1000*60*10, mode=Timer.PERIODIC, callback=threadFetchWeather)

    time.sleep(5)
    
    # 时间1s更新刷屏
    tim1 = Timer(1)
    tim1.init(period=1000, mode=Timer.PERIODIC, callback=threadShowOled)
    
    while True:
        pass










代码目录结构:

完整代码请参考上一篇博客

成果展示:

MicroPython+ESP32+SSD1306 IIC OLED显示天气时钟

参考:

MicroPython开发手册

Search — MicroPython latest documentation

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你好!为了制作一个时钟,你将需要以下硬件和软件: 硬件: 1. ESP32 C3 开发板:ESP32 C3 是一款低成本、低功耗的Wi-Fi和蓝牙芯片,非常适合物联网应用。 2. DS3231SN 实时时钟模块:DS3231SN 是一款高精度的实时时钟模块,可以提供准确的时间信息。 3. SSD1306 OLED 显示屏:SSD1306 是一款0.96OLED显示屏,可以显示时钟和其他信息。 4. 连接线:用于连接 ESP32、DS3231SN 和 SSD1306。 软件: 1. MicroPythonMicroPython 是一种精简版的 Python 解释器,可以在嵌入式系统上运行。 下面是制作时钟的步骤: 1. 连接硬件: - 将 ESP32 C3 与 DS3231SN 和 SSD1306 连接起来。确保连接正确,参考硬件连接图。 - 将 DS3231SN 和 SSD1306 分别连接到 ESP32 的 I2C 接口。 2. 安装 MicroPython: - 在你的计算机上下载并安装 MicroPython。 - 使用 USB 数据线将 ESP32 C3 连接到计算机。 3. 编写 MicroPython 代码: - 打开一个文本编辑器,创建一个新的 MicroPython 脚本。 - 导入必要的库,例如 machine、ssd1306 和 ds3231。 - 初始化 I2C 总线和 DS3231SN 模块。 - 设置 SSD1306 OLED 显示屏的参数。 - 使用 DS3231SN 模块获取当前时间。 - 在 OLED 显示屏上显示时间。 4. 上传代码到 ESP32 C3: - 将编写好的 MicroPython 代码保存为 main.py 文件。 - 使用 MicroPython 工具将 main.py 上传到 ESP32 C3 开发板上。 5. 测试和调试: - 断开 ESP32 C3 与计算机的连接。 - 将 ESP32 C3 与电源连接,启动时钟程序。 - 监视 SSD1306 OLED 显示屏,确保时间正确显示。 这是一个基本的框架,你可以根据自己的需求进行进一步的扩展和美化。希望对你有所帮助!如果你有任何问题,请随时向我提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟与老炮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值