日時を表示してみた。

つぶやき

内蔵RTC (Real-Time Clock)からの時刻取得。Obtaining time from the built-in RTC (Real-Time Clock)

import machine
import utime

# Initialize the Real Time Clock (RTC)
rtc = machine.RTC()

# Get the current date and time as a tuple
# Format: (year, month, day, weekday, hours, minutes, seconds, subseconds)
current_time = rtc.datetime()

# Print the raw datetime tuple
print("Current time:", current_time)

# Print the formatted date and time as "YYYY/MM/DD HH:MM:SS"
print("{0}/{1:02d}/{2:02d} {4:02d}:{5:02d}:{6:02d}".format(
    current_time[0],  # year
    current_time[1],  # month
    current_time[2],  # day
    current_time[3],  # weekday (not displayed)
    current_time[4],  # hour
    current_time[5],  # minute
    current_time[6]   # second
))

NTP(ネット経由で時刻取得)。NTP (time acquisition via the Internet)

import time
import network
import ntptime

# Connect to Wi-Fi
def connect_to_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)  # Create a WLAN station interface
    wlan.active(True)                    # Activate the interface
    wlan.config(pm = 0xa11140)           # Optional: disable power saving mode
    wlan.connect(ssid, password)         # Connect to Wi-Fi

    # Optional: set DNS to 8.8.8.8 (Google DNS)
    # wlan_status = wlan.ifconfig()
    # wlan.ifconfig((wlan_status[0], wlan_status[1], wlan_status[2], '8.8.8.8'))    

    max_wait = 10
    while max_wait > 0:
        if wlan.status() < 0 or wlan.status() >= 3:
            break  # Either error or connected
        max_wait -= 1
        print('Waiting for connection...')
        time.sleep(1)

    if wlan.status() != 3:
        raise RuntimeError('Network connection failed')
    else:
        print('Wi-Fi connected')
        status = wlan.ifconfig()
        print('IP address = ' + status[0])

# Enter your Wi-Fi SSID and password here
ssid: str = "Raspberrypi_PICO_W"
password: str = "qwertyuiop1234"

# Connect to Wi-Fi
connect_to_wifi(ssid, password)

# Set the NTP server to use (default is pool.ntp.org)
ntptime.host = "time.cloudflare.com"

# Attempt to sync time from NTP server
try:
    ntptime.settime()  # This sets the RTC (Real Time Clock)
except:
    print("Failed to synchronize time.")
    raise

# Get local time (UTC + 9 hours for Japan Standard Time)
date_time = time.localtime(time.time() + 9 * 60 * 60)
print(date_time)

# Format and print time as "YYYY/MM/DD HH:MM:SS"
print("{0}/{1:02d}/{2:02d} {3:02d}:{4:02d}:{5:02d}".format(
    date_time[0],  # Year
    date_time[1],  # Month
    date_time[2],  # Day
    date_time[3],  # Hour
    date_time[4],  # Minute
    date_time[5]   # Second
))

ntptime.settime()

コメント