🛠 Heure exacte via NTP : l'horloge temps réel des projets connectés

Raspberry Pi Pico W · intermediaire · Schéma : IMG-pico-w-intermediaire-3-picow-ntp-horloge.svg — Pico W envoyant un paquet UDP vers un serveur NTP via Internet, horloge affichant l'heure UTC, ecarts d'horloge interne avant/apres synchronisation annotés

Objectives

The RP2040 has no real-time clock: without a time source, time.time restarts from zero (or 2000) on every reset — unacceptable for timestamping measurements or using HTTPS. The official SDK provides a complete NTP example in pico_w/wifi/ (the ntp folder); in MicroPython, a few lines of UDP socket code are sufficient. You will understand the 48-byte NTP v3 packet, the 1900→1970 epoch offset, and why the SDK's SNTP mode is cleaner in C.

Hardware

Complete code

# ntp.py — synchronisation NTP en MicroPython (UDP brut, paquet 48 octets)
import machine, network, socket, time

wlan = network.WLAN; wlan.active(True)
if not wlan.isconnected:
    wlan.connect('my_ssid', 'my_password')
    while not wlan.isconnected:
        machine.idle

NTP_EPOCH_OFFSET = 2208988800   # secondes entre 1900 et 1970

def sync_time(server='pool.ntp.org'):
    addr = socket.getaddrinfo(server, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(5)
    pkt = bytearray(48)
    pkt[0] = 0x1B               # LI=0, VN=3, mode=3 (client)
    s.sendto(pkt, addr)
    data = s.recv(48)[0]
    secs = int.from_bytes(data[40:44], 'big') - NTP_EPOCH_OFFSET
    machine.RTC.datetime((1970, 1, 1, 0, 0, 0, 0, 0)[:3] +
                           time.gmtime(secs)[3:6] + (0,))
    return secs

t = sync_time
print('UTC :', time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(t)))
# En C SDK : exemple officiel pico_w/wifi/ntp (lwIP) ; lwIP expose aussi
# une API SNTP — > 
# de lwIP embarquee dans le Pico SDK (sntp_setserver vs sntp_set_server).

Expected verification

The console displays the current UTC date/time, consistent with your PC. After synchronization, time.time returns real POSIX seconds: your sensor logs are timestamped, and HTTPS with certificate validation becomes possible. Run a script without sync: the time restarts from zero — proof that the RP2040 retains nothing without NTP (no RTC, no battery).

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials