Adafruit官网上关于如何使用NTP(网络时间协议)和如何获取天气信息有详细的教程以及相应的库支持。本文将根据官方的示例实现电子万年历和时钟功能。
本文使用到的硬件有ESP32-S3以及TFT显示屏,利用ESP32-S3自带的Wifi功能连接到网络,从网络上获取时间信息和天气信息,在TFT显示屏上将获取的信息显示出来。
参考Adafruit官网提供NTP演示示例,在CIRCUTPY的lib中添加adafruit_ntp库用于支持网络时间的获取,参考官网提供的示例代码,同时将获取的时间信息显示在显示屏上,相关代码如下:
# Get current time using NTP
print("Fetching time from NTP.")
pool = socketpool.SocketPool(wifi.radio)
#指定NTP服务器为国内阿里云服务器
ntp = adafruit_ntp.NTP(pool, server="ntp.aliyun.com", tz_offset=TZ_OFFSET)
rtc.RTC().datetime = ntp.datetime
通过心知天气的API接口获取天气信息,天气信息以JSON字符的形式返回,在心知天气的官网上可以查看API的调用方式以及返回数据的例子。
从返回的数据中解析其中的数据,提取出城市、温度、以及天气信息,同时在显示屏上显示出来,相关代码如下:
DATA_SOURCE = "http://api.seniverse.com/v3/weather/now.json?key=SG-nLPzA3pyLEy9Tw&location=wuxi&language=en&unit=c"
while True:
# Fetch weather data from 心知 API
print("Fetching json from", DATA_SOURCE)
response = requests.get(DATA_SOURCE)
print(response.json())
# Extract temperature and weather condition data from API response
current_temp = response.json()["results"][0]["now"]["temperature"]
current_weather_condition = response.json()["results"][0]["now"]["text"]
current_city = response.json()["results"][0]["location"]["name"]
print("Weather condition: ", current_weather_condition)
整个工程的代码如下:
# 在这里写上你的代码 :-)
# SPDX-FileCopyrightText: 2022 Carter Nelson for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import board
import rtc
import wifi
import adafruit_ntp
import os
import ssl
import time
import displayio
import terminalio
import socketpool
import adafruit_requests
from adafruit_display_text import bitmap_label, label
DATA_SOURCE = "http://api.seniverse.com/v3/weather/now.json?key=SG-nLPzA3pyLEy9Tw&location=wuxi&language=en&unit=c"
# --| User Config |--------------------------------
TZ_OFFSET = 8 # time zone offset in hours from UTC
NEO_PIN = board.NEOPIXEL # neopixel pin
NEO_CNT = 1 # neopixel count
# -------------------------------------------------
# Set up TFT display
display = board.DISPLAY
board.DISPLAY.brightness = 0.35
board.DISPLAY.rotation = 0
group = displayio.Group()
time_color = 0xFF0000
weather_color = 0x00FF00
time_area = label.Label(terminalio.FONT, text="Hello", color=time_color)
time_area.x = 2
time_area.y = 10
time_area.line_spacing = 0.8
time_area.scale = 1
weather_area = label.Label(terminalio.FONT, text="Weather", color=weather_color)
weather_area.x = 2
weather_area.y = 30
weather_area.line_spacing = 0.8
weather_area.scale = 1
main_group = displayio.Group()
main_group.append(group)
main_group.append(time_area)
main_group.append(weather_area)
# Show the main group on the display
display.show(main_group)
# Connect to local network
wifi.radio.connect(os.getenv("WIFI_SSID"), os.getenv("WIFI_PASSWORD"))
print("Wifi connected.")
# Get current time using NTP
print("Fetching time from NTP.")
pool = socketpool.SocketPool(wifi.radio)
ntp = adafruit_ntp.NTP(pool, server="ntp.aliyun.com", tz_offset=TZ_OFFSET)
rtc.RTC().datetime = ntp.datetime
#
requests = adafruit_requests.Session(pool, ssl.create_default_context())
# Define time interval between requests
time_interval = 3000 # set the time interval to 30 minutes
# Wait for wake up time
now = time.localtime()
print("Current time: {:2}:{:02}".format(now.tm_hour, now.tm_min))
while True:
# Fetch weather data from 心知 API
print("Fetching json from", DATA_SOURCE)
response = requests.get(DATA_SOURCE)
print(response.json())
# Extract temperature and weather condition data from API response
current_temp = response.json()["results"][0]["now"]["temperature"]
current_weather_condition = response.json()["results"][0]["now"]["text"]
current_city = response.json()["results"][0]["location"]["name"]
print("Weather condition: ", current_weather_condition)
time_area.text = "Hello EEWorld\n\Time is {:2}:{:02}".format(
now.tm_hour, now.tm_min
)
weather_area.text="City: " + current_city+"\n"\
+"Temperature: {}".format(current_temp)+"\n"\
+"Weather: "+ current_weather_condition
# just sleep until next time check
time.sleep(30)
now = time.localtime()
代码的运行效果如图所示:
官网上的例子由于使用大部分都是国外的服务器,在移植时需要使用者对NTP和天气API的具体使用要有了解,从而能正确地使用国内的服务,使自己的代码正确运行。
官网上的例子由于使用大部分都是国外的服务器,在移植时需要使用者对NTP和天气API的具体使用要有了解,从而能正确地使用国内的服务,使自己的代码正确运行。
有时买个梯子,非常重要!