掌控板micropython编程实现OLED显示天气信息
上一个例子已经实现了在掌控板的OLED上显示汉字,本例使用掌控板的wifi访问心知天气,获取天气信息显示在掌控板的OLED上。
- 访问心知天气主页( https://www.seniverse.com/),注册后登录。可以申请免费版或试用版的API,区别如图1所示。
- 以试用版为例(如图2所示),在 API密钥中,将私钥可视化,复制此私钥。并将此私钥替换网址“api.seniverse.com/v3/weather/now.json?key=****** &location=SHENYANG&language=zh-Hans&unit=c"中的*******处。
- 在浏览器中访问加入私钥的网址,则会显示如下:
{"results": [{"location": {"id": "WXRVB9QYXKY8","name": "沈阳","country": "CN","path": "沈阳,沈阳,辽宁,中国","timezone": "Asia/Shanghai","timezone_offset": "+08:00"},"now": {"text": "多云","code": "4","temperature": "13"},"last_update": "2024-11-01T09:04:08+08:00"}]
}
- 获取天气的代码main.py如下:
import network
import time
import os
import urequests
import ujson
from machine import Pin, I2C
import ssd1106
import ufontssid = '******'
password ='******'i2c = I2C(scl=Pin(22), sda=Pin(23))
display = ssd1106.SSD1106_I2C(128, 64, i2c)mynetwork=network.WLAN(network.STA_IF)
mynetwork.active(True)
print("Connecting to WiFi...")
while not mynetwork.isconnected(): try: mynetwork.connect(ssid, password) time.sleep(1) except Exception as e: print("WiFi connection error:", e) time.sleep(5) # 等待一段时间后重试 print("Connected to WiFi!")
ifconfig_result = mynetwork.ifconfig()
#print("IP Address:", ifconfig_result['ip']) # 打印IP地址
print(ifconfig_result)
# 加载字体
font = ufont.BMFont("unifont-14-12917-16.v3.bmf") # 显示初始信息
font.text(display, "天气情况", 25, 0, show=True, clear=True) font = ufont.BMFont("unifont-14-12917-16.v3.bmf")font.text(display, "天气情况", 25, 24, show=True,clear=True)while True:json_data=urequests.get('https://api.seniverse.com/v3/weather/now.json?key=******&location=SHENYANG&language=zh-Hans&unit=c')# 使用ujson.loads()将JSON字符串解析为Python对象 parsed_data = ujson.loads(json_data.text) # 现在你可以像操作普通Python字典一样操作parsed_data # 例如,获取沈阳的天气情况 location_name = parsed_data['results'][0]['location']['name']weather_text = parsed_data['results'][0]['now']['text'] temperature = parsed_data['results'][0]['now']['temperature']print(f"地点: {location_name}") print(f"天气: {weather_text}") print(f"温度: {temperature}°C")display.fill(0)font.text(display, "地点: "+location_name, 20, 16, show=True)font.text(display, "天气: "+weather_text, 20,32, show=True)font.text(display, "温度: "+temperature+" ℃",20,48, show=True)time.sleep(5)
注意:在代码中需要将******部分换为掌控板连接的wifi的ssid和password,并将自己的私钥添加在api接口中。
- 上传到掌控板中的文件有"main.py",“ssd1106.py”,“ufont.py”,"unifont-14-12917-16.v3.bmf"四个文件。
-
运行结果如图4所示。