Raspberry Pi Pico Wの無線LANモジュールでネットワークに接続して標準時刻データとその場所の気象情報を表示させます。

Raspberry Pi Pico Wの無線LANモジュールでネットワークに接続して指定したNTP(Network Time Protocol)サーバから、標準時刻データと無料で利用できるOpenWeatherMapを利用して現在の天気予報を取得していきます。
Raspberry Pi Pico W
MicroPythonプログラム
# 必要なモジュールのインポート
import network
import rp2
import urequests
import ntptime
import time
# Wi-Fi接続パラメータ
ssid = "SSID"
password = "パスワード"
# 日本標準時(UTC+9時間)
UTC_OFFSET = 9
# NTPサーバ ドメイン
NTP_SRV = "ntp.nict.jp"
# Wi-Fiに接続する関数
def wifi_connect():
rp2.country('JP')
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.config(pm=0xa11140)
wlan.connect(ssid, password)
while not wlan.isconnected() and wlan.status() >= 0:
print("Wait for connection...")
time.sleep(1)
ip_add = wlan.ifconfig()[0]
print("Connected on", ip_add)
return ip_add
# NTPサーバから日時取得
def get_ntp_time():
ntptime.server = NTP_SRV
time.sleep(1)
ntptime.settime()
print("Connected to NTP server.")
time.sleep(2)
# 日付・時刻整形
def format_dttm(day_tm):
dat = ("%4d/%02d/%02d" % (day_tm[0:3]))
tm = ("%2d:%02d:%02d" % (day_tm[3:6]))
return dat, tm
# 日付時刻を取得
def get_dattm():
lcl_tm = time.localtime(time.mktime(time.localtime()) + UTC_OFFSET * 60 * 60)
dat, tm = format_dttm(lcl_tm)
return dat, tm
# メイン
try:
ip_add = wifi_connect()
get_ntp_time()
while True:
dat, tm = get_dattm()
print(dat, tm)
# APIから天気情報を取得
url = "https://api.openweathermap.org/data/2.5/weather?lat=緯度&lon=軽度&appid=APIキー"
response = urequests.get(url) # APIリクエスト
if response.status_code == 200:
json_data = response.json()
weather = json_data.get('weather')[0].get('main') # 天気
temperature = json_data.get('main').get('temp') # 気温
temperature_celsius = temperature - 273.15 # 摂氏に変換
wind_speed = json_data.get('wind').get('speed') # 風速
wind_deg = json_data.get('wind').get('deg') # 風向
print(f"天気: {weather}, 気温: {temperature_celsius:.1f}°C, 風速: {wind_speed:.1f} m/s, 風向: {wind_deg}°")
else:
print(f"Error: {response.status_code}")
time.sleep(10) # API呼び出しの間隔を調整
except KeyboardInterrupt:
print("「Ctrl + c」キーが押されました。")
無料アカウントの作り方
実行
自由研究

テンテン
天気を日本語にしたり風向を東西南北で表示できるといいですね。

