Sunday, February 15, 2026

Python on a Raspberry Pi Pico (Update)

 Here is an update to my Raspberry Pi Pico project. I setup the Python code to connect the Pico to Wi-Fi then grab date and time from an NTP (Network Time Protocol) server. I have it displaying the date and time on the first row. On the second row, it is displaying the temperature and humidity from a sensor connected to the Pico. I put it all together in a modular bracket I drew and 3D printed for my network rack. I used Thonny to write and Python with assistance from ChatGPT as I'm still learning how to write Python. The code to this project is below the images.

Hardware for this project is.
Raspberry Pi Pico 2W.
The screen model is the I2C LCD 1602.
The temperature and humidity sensor is the DHT-11 module.

You'll need to download the drivers for the screen.








Here is the Pyhton code this project.

from machine import Pin
from time import sleep_ms
import dht
import network
import secrets
import socket
import time
import struct
import I2C_LCD_driver

sensor = dht.DHT11(Pin(15))
lcd = I2C_LCD_driver.lcd()

from machine import Pin

NTP_DELTA = 2208988800
host = "pool.ntp.org"

led = Pin("LED", Pin.OUT)

def set_time():
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1B
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.settimeout(1)
        res = s.sendto(NTP_QUERY, addr)
        msg = s.recv(48)
    finally:
        s.close()
    val = struct.unpack("!I", msg[40:44])[0]
    t = val - NTP_DELTA
    UTC_OFFSET = -5   # <-- your timezone here
    t = t + int(UTC_OFFSET * 3600)
    tm = time.gmtime(t)
    machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))


# ---- WiFi Setup ----
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(secrets.secrets['ssid'], secrets.secrets['password'])

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

if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('connected')
    status = wlan.ifconfig()
    print( 'ip = ' + status[0] )

led.on()
set_time()
print(time.localtime())
led.off()


def display_time():
    while True:
        tm = time.localtime()
        year   = tm[0]
        month  = tm[1]
        day    = tm[2]
        hour   = tm[3]
        minute = tm[4]

        # Convert to 12-hour format without leading zero
        if hour == 0 or hour == 12:
            display_hour = 12
        else:
            display_hour = hour % 12

        # Format date as MM/DD/YY
        date_str = "{:02d}/{:02d}/{:02d}".format(month, day, year % 100)
        # Format time as H:MM (no leading zero on hour)
        time_str = "{}:{:02d}".format(display_hour, minute)

        # Combine date and time with single space
        row1 = "{}   {}".format(date_str, time_str)[:16]

        # Display on first row
        lcd.lcd_display_string(row1, 1)
        
        # Reading Temp and Humidity
        sensor.measure()
        tempF = round(((sensor.temperature() * 1.8) + 32), 0)
        humid = sensor.humidity()
        
        # Display on second row
        line = "TMP:{:.0f}F HUM:{:.0f}%".format(tempF, humid)
        lcd.lcd_display_string(line, 2)
        sleep_ms(2500)
        
        time.sleep(1)

display_time()


 I also created a Python file that stores my WiFi credentials called secrets.py. You can see the reference in the code below.

# Save this as settings.toml in the root directory
CIRCUITPY_WIFI_SSID="Your_WiFi_Name"
CIRCUITPY_WIFI_PASSWORD="Your_Password"

No comments:

Post a Comment