This is my starting point. It connects to the internet, then to the NTC to get the current time. It then sets the RTC on the Pico and starts displaying it on the Oled. It works fine if I run it from Thonny, but not if I just plug in a usb with the program named main.py or boot.py. main runs, but aborts when attempting to connect to the internet. The sleep(1.5) are because of a youtube recommendation here:
https://www.youtube.com/watch?v=mCYB9tjsF0I.
# Test the I2C connections
import network
from machine import RTC
import rp2
import sys
import utime as time
import usocket as socket
import ustruct as struct
import time
from machine import Pin, I2C, ADC
import ssd1306
import rp2
import sys
import utime as time
import usocket as socket
import ustruct as struct
from time import sleep
from ssd1306 import SSD1306_I2C
ssid="XXXXXXX"
password="XXXXXXXX"
WIDTH = 128 # oled display width
HEIGHT = 64 # oled display height
sleep(1.5)
sda=machine.Pin(6) # Data pin
scl=machine.Pin(7) # Clock pin
i2c=machine.I2C(1,sda=sda, scl=scl, freq=400000) # Connection controller 0
sleep(1.5)
oled = ssd1306.SSD1306_I2C(128, 64, i2c) # Initialise ssd1306 display
# wintertime / Summerzeit
#GMT_OFFSET = 3600 * -5 # 3600 = 1 h (wintertime)
GMT_OFFSET = 3600 * -4 # 3600 = 1 h (summertime)
# NTP-Host
NTP_HOST = 'pool.ntp.org'
# Funktion: get time from NTP Server
def getTimeNTP():
NTP_DELTA = 2208988800
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1B
addr = socket.getaddrinfo(NTP_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()
ntp_time = struct.unpack("!I", msg[40:44])[0]
return time.gmtime(ntp_time - NTP_DELTA + GMT_OFFSET)
# Funktion: copy time to PI pico´s RTC
def setTimeRTC():
tm = getTimeNTP()
rtc.datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
sleep(1.5)
max_wait = 10
#print('Waiting for connection')
while max_wait > 10:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
sleep(1)
status = None
if wlan.status() != 3:
raise RuntimeError('Connections failed')
else:
status = wlan.ifconfig()
# print('connection to', ssid,'succesfull established!', sep=' ')
# print('IP-adress: ' + status[0])
ipAddress = status[0]
rtc = RTC()
setTimeRTC()
# ======== ssd1306 set up for I2C ========
# ====== Universal code starts here ======
def centre(msg, yy, cc): # Procedure to centre text on a line
space = WIDTH-(len(msg) * 8) # Characters are 8 pixels wide
gap = int(space/2)
# text(string, x, y, colour)
oled.text(msg,gap,yy,cc) # Write to buffer
delay = 1
while True:
tm=rtc.datetime()
A=(str(tm[4])+":"+str(tm[5])+":"+str(tm[6]))
# Waiting time in seconds
oled.fill(0) # Fill with Black
# ( text string, x, y, colour)
oled.text(A, 30, 30, 1) # White at (16,10)
oled.show() # Send buffer to display
time.sleep(delay)
oled.fill(0)