Skip to content

Instantly share code, notes, and snippets.

@andywarburton
Last active February 10, 2023 18:27
Show Gist options
  • Save andywarburton/be5d8c25e9c0c1197e1a71e8ddee71d1 to your computer and use it in GitHub Desktop.
Save andywarburton/be5d8c25e9c0c1197e1a71e8ddee71d1 to your computer and use it in GitHub Desktop.
import time
from galactic import GalacticUnicorn
from picographics import PicoGraphics, DISPLAY_GALACTIC_UNICORN as DISPLAY
import network
import rp2
from machine import Pin
import socket
import struct
import utime
### DEFINE THE THINGS ###
# time stuff
NTP_DELTA = 2208988800
host = "pool.ntp.org"
# create galactic object and graphics surface for drawing
unicorn = GalacticUnicorn()
unicorn.set_brightness(0.8)
width = GalacticUnicorn.WIDTH
height = GalacticUnicorn.HEIGHT
graphics = PicoGraphics(DISPLAY)
graphics.set_font("bitmap8")
# pen colours to draw with
BG_COLOUR = graphics.create_pen(0, 0, 0)
TEXT_COLOUR = graphics.create_pen(50, 0, 255)
countdown_target = (2023, 06, 30)
### FUNCTIONS ###
def days_between(d1, d2):
d1 += (1, 0, 0, 0, 0) # ensure a time past midnight
d2 += (1, 0, 0, 0, 0)
return utime.mktime(d1) // (24*3600) - utime.mktime(d2) // (24*3600)
def set_time():
# function by Alistair Allen
# https://gist.github.com/aallan/581ecf4dc92cd53e3a415b7c33a1147c
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
tm = time.gmtime(t)
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
def clear_display():
# does what it says on the tin
graphics.set_pen(BG_COLOUR)
graphics.clear()
unicorn.update(graphics)
### CONNECT TO WIFI ###
# set your WiFi Country
rp2.country('NL')
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
# set power mode to get WiFi power-saving off (if needed)
wlan.config(pm = 0xa11140)
wlan.connect(wifiname, password)
while not wlan.isconnected() and wlan.status() >= 0:
print("Waiting to connect:")
time.sleep(1)
if(wlan.isconnected()):
network_config = wlan.ifconfig()
ip = network_config[0]
print("Connected:" + ip)
clear_display()
# draw the text
graphics.set_pen(TEXT_COLOUR)
graphics.text("Active", 5, 2, 0, scale=1);
# update the display
unicorn.update(graphics)
time.sleep(5)
while True:
set_time()
realtime = time.localtime()
today = (int(realtime[0]), int(realtime[1]), int(realtime[2]))
remain = days_between(today, countdown_target)
print("T" + str(remain))
#clear the display
clear_display()
graphics.set_pen(TEXT_COLOUR)
graphics.text(str(remain), 34, 2, 0, scale=1);
# update the display
unicorn.update(graphics)
# pause for a bit (save network requests)
time.sleep(600)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment