This Python script is designed for the Raspberry Pi Pico 2W to read the current time from an NTP server ("ntp.nict.jp") and periodically output the IP address, LED status, and current date and time. It connects to a Wi-Fi network using the provided SSID and password.
# PWMP100/wifista.py
# description: read time by NTP "ntp.nict.jp"
# board: Raspberry Pi Pico 2W with RP2350
# wifi mobile router: HW01L
# language: micropython MicroPython v1.25.0
# IDE: Thonny 4.1.7 on windows11
#
import network
import time
import utime
from time import sleep
from machine import Pin
import ntptime
import rp2
JST_OFFSET = 9 * 60 * 60 # JST = UTC + 9H(32400秒)
wifiId=('HW00','Embd0mm0')
codeid=("PWMP140")
def codeId(codeid):
print('{"codeId":"'+codeid+'"}')
def staBegin(wifiId):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(wifiId[0], wifiId[1])
wlan.ifconfig(('192.168.40.140', '255.255.255.0', '192.168.40.1', '8.8.8.8'))
sleep(5)
if wlan.status() != 3:
raise RuntimeError('wifi connection failed')
sleep(10)
machine.reset()
else:
ip=wlan.ifconfig()
print('connected:', ip)
return ip
def getIp():
wlan = network.WLAN(network.STA_IF)
print(f'{{"ip":"{wlan.ifconfig()[0]:s}"}}')
return
#-main-----------------------------
codeId(codeid)
led = Pin('LED',Pin.OUT)
led.on()
staBegin(wifiId)
ntptime.host = "ntp.nict.jp"
time.sleep(3)
ntptime.settime()
while True:
getIp()
led.toggle()
print(f'{{"led":{led.value():d}}}")
sleep(10)
dt=utime.localtime(utime.time() + 9 * 60 * 60)
print(f'{{"date":"{dt[0]:4d}/{dt[1]:02d}/{dt[2]:02d}"}}')
print(f'{{"time":"{dt[3]:2d}:{dt[4]:02d}:{dt[5]:02d}"}}')
The Wi-Fi SSID and password (wifiId=('HW00','Embd0mm0')) are hardcoded in the script. This is generally not a good practice for security and reusability.
Suggestion: For a beginner, consider explaining that in real-world applications, these credentials should be stored more securely (e.g., in a separate configuration file or using a more secure method if the Pico 2W supports it). For this basic example, it's acceptable but highlight the security implications.
The script configures a static IP address (wlan.ifconfig(('192.168.40.140', '255.255.255.0', '192.168.40.1', '8.8.8.8'))). While this can be useful for consistent addressing, it might cause issues if the network configuration changes or if the IP address is already in use.
Suggestion: Explain that DHCP (Dynamic Host Configuration Protocol) is often preferred as it automatically assigns IP addresses. For beginners, perhaps show how to enable DHCP by calling wlan.ifconfig('dhcp') instead. Mention the pros and cons of static vs. dynamic IP for their understanding.
In the staBegin function, there is a sleep(10) followed by a machine.reset() within the if wlan.status() != 3: block. If the Wi-Fi connection fails, the script will sleep for 10 seconds and then immediately reset. This could lead to a rapid reset loop if the Wi-Fi issue persists.
Suggestion: For beginners, emphasize the importance of handling errors gracefully. Instead of an immediate reset, consider adding a delay or a counter to limit the number of reset attempts. Perhaps print a more informative error message before resetting.
The time zone offset is hardcoded as JST_OFFSET = 9 * 60 * 60. While correct for JST, this might need to be changed if the device is used in a different time zone.
Suggestion: Explain the concept of UTC and time zones. For a beginner project, the hardcoded offset is acceptable, but mention that for more robust applications, time zone configuration should be more dynamic (though this might be beyond the scope of a very basic beginner project).
The script prints output in a JSON-like format. This is good for machine readability.
Good Practice: Highlight that using a structured format like JSON is beneficial for data logging and communication with other systems. Explain the basic structure of JSON (key-value pairs).
The script includes a basic check for Wi-Fi connection failure using wlan.status() != 3.
Suggestion: For beginners, explain that wlan.status() returns different values indicating the connection status and that checking for specific error codes can provide more detailed information about the failure. Referencing the MicroPython documentation for network status codes would be helpful.
The script imports both `time` and `utime`. In MicroPython, `utime` is generally preferred for lower-level time-related functions.
Suggestion: Explain the difference between `time` and `utime` in MicroPython. For this script, using `utime.sleep()` might be more consistent with the rest of the time-related functions used.
Clear Comments: The script includes comments explaining the purpose of different sections and variables.
Modular Design: The code is organized into functions (codeId, staBegin, getIp), which improves readability and reusability.
Using f-strings for Output: The use of f-strings for printing formatted output is modern and efficient.
MPY: soft reboot
{"codeId":"PWMP140"}
connected: ('192.168.40.140', '255.255.255.0', '192.168.40.1', '8.8.8.8')
{"ip":"192.168.40.140"}
{"led":0}
{"date":"2025/04/06"}
{"time":"18:42:36"}
{"ip":"192.168.40.140"}
{"led":1}
The output shows that the script successfully connected to Wi-Fi, retrieved an IP address, toggled the LED, and obtained the date and time from the NTP server, formatted as JSON strings.
This script provides a good starting point for an embedded beginner to learn about Wi-Fi connectivity, NTP, and basic hardware control on the Raspberry Pi Pico 2W. The review points highlight areas for improvement and further learning, focusing on security, robustness, and best practices in embedded programming.