分任务1:日历&时钟——完成一个可通过互联网更新的万年历时钟,并显示当地的天气信息
建议搭配器件:Adafruit ESP32-S3 TFT Feather
官网有个很好的参考示例
https://learn.adafruit.com/mini-weather-station-esp32-s2-tft
免费的天气服务
https://www.sojson.com/api/weather.html
利用http get请求库函数,得到json格式的天气数据,解析后在屏幕显示即可
import time
import board
import ssl
import wifi
import socketpool
import adafruit_requests
from adafruit_display_text import label, wrap_text_to_lines
from adafruit_bitmap_font import bitmap_font
color = 0xF01414
font = bitmap_font.load_font("wenquanyi_13px.pcf")
display = board.DISPLAY
display.brightness = 0.25
display.rotation = 0
JSON_TIME_URL = "http://quan.suning.com/getSysTime.do"
JSON_weather_URL = "http://t.weather.sojson.com/api/weather/city/{}"
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
def refresh_screen(print_text):
text_area = label.Label(font, text=print_text, scale=1)
text_area.x = 2
text_area.y = 10
text_area.scale = 1
text_area.color = color
display.show(text_area)
def get_data():
try:
response = requests.get(JSON_TIME_URL)
except ConnectionError as e:
print("Connection Error:", e)
print("Retrying in 60 seconds")
time_data = response.json()['sysTime2'][:-3]
try:
city_code = "101200101"
url = JSON_weather_URL.format(city_code)
response = requests.get(url)
except ConnectionError as e:
print("connect error:{},retry in 60s".format(e))
weather_data = response.json()
cityInfo = weather_data['cityInfo']
city_weather = weather_data['data']
forecast = city_weather['forecast']
dis_str = ""+cityInfo['parent']+' '+cityInfo['city']
dis_str += " "+time_data
dis_str += "\n" + forecast[0]['week']
dis_str += ' 空气质量:' + city_weather['quality']
dis_str += "\n温度:"+city_weather['wendu']+"℃"
dis_str += " 湿度:" + city_weather['shidu']
dis_str += "\n明天最"+forecast[1]['high']+' 最'+forecast[1]['low']
return dis_str
while not wifi.radio.ipv4_address:
try:
wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
except ConnectionError as e:
print("connecti error:{},retry in 2s".format(e))
time.sleep(2)
print("get ip:", wifi.radio.ipv4_address)
while True:
info = get_data()
refresh_screen(info)
time.sleep(60)
效果:
这个屏幕是彩屏?你这怎么显示红色的?