Weekly Countdown

With the PyPortal running CircuitPython code, we can set the date and time of an important event, and then have the display show how may years, days, hours, and minutes have elapsed since that time. This could be anything you want, from the lunar landing, as in our example, to the year Hydrox, the original creme-filled sandwich cookie, was introduced (1908).

The PyPortal Countdown Clock will do the following:

  • Display a custom background .bmp for the event
  • Determine the current local time using the WiFi connection to the Internet
  • Draw out the count-up time in years, days, hours, and minutes

Adafruit IO Time Server

In order to get the precise time, our project will query the Adafruit IO Internet of Things service for the time. Adafruit IO is absolutely free to use, but you'll need to log in with your Adafruit account to use it. If you don't already have an Adafruit login, create one here.

If you haven't used Adafruit IO before, check out this guide for more info.

Once you have logged into your account, there are two pieces of information you'll need to place in your secrets.py file: Adafruit IO username, and Adafruit IO key. Head to io.adafruit.com and simply click the View AIO Key link on the left hand side of the Adafruit IO page to get this information.

Then, add them to the secrets.py file like this:

secrets = {

    'ssid' : '_your_wifi_ssid',

    'password : '_your_wifi_password',

    'aio_username' : '_your_aio_username_',
    'aio_key' : '_your_big_huge_super_long_aio_key_'

    }

Install CircuitPython Code and Assets

In the embedded code element below, click on the Download: Project Zip link, and save the .zip archive file to your computer.

Then, uncompress the .zip file, it will unpack to a folder named PyPortal_EventCountup.

Copy the contents of the PyPortal_EventCountup directory to your PyPortal's CIRCUITPY drive.

This is what the final contents of the CIRCUITPY drive will look like:

# SPDX-FileCopyrightText: 2019 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
This example will figure out the current local time using the internet, and
then draw out a count-up clock since an event occurred!
Once the event is happening, a new graphic is shown
"""
import time
import board
from adafruit_pyportal import PyPortal
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text.label import Label

# The time of the thing!
EVENT_YEAR = 1972
EVENT_MONTH = 12
EVENT_DAY = 7
EVENT_HOUR = 5
EVENT_MINUTE = 55
# we'll make a python-friendly structure
event_time = time.struct_time((EVENT_YEAR, EVENT_MONTH, EVENT_DAY,
                               EVENT_HOUR, EVENT_MINUTE, 0,  # we don't track seconds
                               -1, -1, False))  # we dont know day of week/year or DST

# determine the current working directory
# needed so we know where to find files
cwd = ("/"+__file__).rsplit('/', 1)[0]
# Initialize the pyportal object and let us know what data to fetch and where
# to display it
pyportal = PyPortal(status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"/countup_background.bmp")

big_font = bitmap_font.load_font(cwd+"/fonts/Helvetica-Bold-24.bdf")
big_font.load_glyphs(b'0123456789') # pre-load glyphs for fast printing

years_position = (126, 15)
days_position = (13, 41)
hours_position = (118, 41)
minutes_position = (25, 68)
text_color = 0xFF0000

text_areas = []
for pos in (years_position, days_position, hours_position, minutes_position):
    textarea = Label(big_font, text='  ')
    textarea.x = pos[0]
    textarea.y = pos[1]
    textarea.color = text_color
    pyportal.splash.append(textarea)
    text_areas.append(textarea)
refresh_time = None


while True:
    # only query the online time once per hour (and on first run)
    if (not refresh_time) or (time.monotonic() - refresh_time) > 3600:
        try:
            print("Getting time from internet!")
            pyportal.get_local_time()
            refresh_time = time.monotonic()
        except RuntimeError as e:
            print("Some error occured, retrying! -", e)
            continue

    now = time.localtime()
    print("Current time:", now)

    # We're going to do a little cheat here, since circuitpython can't
    # track huge amounts of time, we'll calculate the delta years here
    if now[0] > (EVENT_YEAR+1):  # we add one year to avoid half-years
        years_since = now[0] - (EVENT_YEAR+1)
        # and then set the event_time to not include the year delta
        event_time = time.struct_time((EVENT_YEAR+years_since, EVENT_MONTH, EVENT_DAY,
                                       EVENT_HOUR, EVENT_MINUTE, 0,  # we don't track seconds
                                       -1, -1, False))  # we dont know day of week/year or DST
    else:
        years_since = 0
    print(event_time)
    since = time.mktime(now) - time.mktime(event_time)
    print("Time since not including years (in sec):", since)
    sec_since = since % 60
    since //= 60
    mins_since = since % 60
    since //= 60
    hours_since = since % 24
    since //= 24
    days_since = since % 365
    since //= 365
    years_since += since
    print("%d years, %d days, %d hours, %d minutes and %s seconds" %
          (years_since, days_since, hours_since, mins_since, sec_since))
    text_areas[0].text = '{}'.format(years_since)  # set days textarea
    text_areas[1].text = '{}'.format(days_since)  # set days textarea
    text_areas[2].text = '{}'.format(hours_since) # set hours textarea
    text_areas[3].text = '{}'.format(mins_since)  # set minutes textarea

    # update every 10 seconds
    time.sleep(10)
If you run into any errors, such as "ImportError: no module named `adafruit_display_text.label`" be sure to update your libraries to the latest release bundle!

How it Works

The PyPortal Event Countup is doing a couple of cool things to make your event display:

Background

First, it displays a bitmap graphic named countup_background.bmp as the screen's background. This is a 320 x 240 pixel RGB 16-bit raster graphic in .bmp format.

Time

In order to calculate the count-up value,

the PyPortal's CircuitPython code determines the local time by checking the internet time via the WiFi connection. It uses your IP address information to determine the local time. The good news is that once you've set up your timezone (or if the IP is fine) you do not have to adjust for daylight savings, leap years, etc.

In some cases, the time may not appear correctly based on your IP address, but don't fear! You can override that by manually setting the timezone in your secrets.py file. Plus, you can explicitly set your PyPortal to display a different time zone in case you have travel plans or a friend in Tokyo or something!

To do this, you'll add this line to your secrets file:

'timezone' : "America/Los_Angeles"

Here's a great list of valid timezones from the IANA Timezone Database. Head there to find the name of the one you want. Simply find the nearest timezone to your desired location, and use that name as displayed in the TZ database name column. 

You can adjust the following variables to make this work:

  • EVENT_YEAR
  • EVENT_MONTH
  • EVENT_DAY
  • EVENT_HOUR
  • EVENT_MINUTE

Here's what that looks like for the precise minute of the lunar landing:

EVENT_YEAR = 1972
EVENT_MONTH = 12
EVENT_DAY = 7
EVENT_HOUR = 5
EVENT_MINUTE = 55

Font

Then, it displays the info with bitmapped fonts to overlay on top of the background. You can learn more about converting type in this guide.

Afterwards, it repeats all over again for the next week.

Customization

If you like, you can also customize the background for a different event, by making your own 320x240 16-bit RGB color .bmp file.

Then, adjust your setting to match the new event's time.

Graphics

Let's have a look at how the code places the elements on screen. Below, we can see the text items that are displayed.

Text Position

Depending on the design of your background bitmap and the length of the text you're displaying, you may want to reposition the text and caption.

The PyPortal's display is 320 pixels wide and 240 pixels high. In order to refer to those positions on the screen, we use an x/y coordinate system, where x is horizontal and y is vertical.

The origin of this coordinate system is the upper left corner. This means that a pixel placed at the upper left corner would be (0,0) and the lower right corner would be (320, 240).

Text Color

Another way to customize your display is to adjust the color of the text. The line text_color=0xFFFFFF in the constructor shows how. You will need to use the hexadecimal value for any color you want to display.

You can use something like https://htmlcolorcodes.com/ to pick your color and then copy the hex value, in this example it would be 0x0ED9EE

So, in order to customize the position and color of the text, you would adjust the values in these lines of code in code.py:

years_position = (126, 15)
days_position = (13, 41)
hours_position = (118, 41)
minutes_position = (25, 68)
text_color = 0xFF0000

3D Printed Stand

If you'd like to create a 3D printed stand for your PyPortal Countdown Clock, you can follow the general instructions in this guide, but use the horizontal PyPortal Stand model linked here.

Use the four sets of standoffs and screws to fasten them together as shown.

This guide was first published on Mar 13, 2019. It was last updated on Mar 13, 2019.

This page (Code PyPortal with CircuitPython) was last updated on Sep 30, 2023.

Text editor powered by tinymce.