Raspberry Pi Pico Wの無線LANモジュールでネットワークに接続して標準時刻データを取得します。

Raspberry Pi Pico Wの無線LANモジュールでネットワークに接続して指定したNTP(Network Time Protocol)サーバから、標準時刻データを取得します。
Raspberry Pi Pico W
MicroPythonプログラム
##################################################
#
# モジュールの読み込み
#
##################################################
#Network/NTP
import network
import rp2
import ntptime
import time
##################################################
#
# Wi-Fi接続/時刻パラメータ
#
##################################################
#Wi-Fi接続パラメータ
ssid = "SSID"
password = "パスワード"
#日本標準時(UTC+9時間)
UTC_OFFSET = 9
#NTPサーバ ドメイン
NTP_SRV = "ntp.nict.jp"
##################################################
#
# 【関数】Wi-Fiに接続
#
##################################################
def wifi_connect():
#Wi-Fi地域(日本)の設定
rp2.country('JP')
#ステーションインタフェースの有効化
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
#Wi-Fiの省電力をオフに設定
wlan.config(pm = 0xa11140)
#wi-Fiに接続
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", f' {ip_add}')
#ダミー
time.sleep(2)
return ip_add
##################################################
#
# 【関数】NTPサーバから日時取得
#
##################################################
def get_ntp_time():
#NTPサーバ
ntptime.server = NTP_SRV
#NTPサーバへの接続待ち
time.sleep(1)
#ローカル時刻をUTC標準時刻に同期
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:
#Wi-Fiに接続
ip_add = wifi_connect()
#NTPサーバから日時取得
get_ntp_time()
#液晶ディスプレイに日付・時刻表示
while True:
#日付・時刻を取得
dat,tm = get_dattm()
#LCDに文字表示
print(dat, tm)
#1秒待ち
time.sleep(1)
except KeyboardInterrupt:
# Turn off the display
print("「Ctrl + c」キーが押されました。")
machine.reset()
実行
自由研究

テンテン
同じようにwifiをつかってインターネットからいろいろなデータを取得できます。天気予報も可能です。


