It’s hard work being a werewolf, and I don’t just mean cleaning blood stains out of the carpet or dealing with fleas in the house.

It’s this messy business of the full Moon. Most wall calendars and news sources, if they even mention Moon phases, there’s about a 50/50 chance that they’re off by a full day (explained on the “Moon Facts” page). You might be out at a fancy event wearing a rental tuxedo when things turn weird. There goes your deposit. So awkward.

The only way to get a correct Moon phase for your time and location is with math and science. Our Matrix Portal Moon phase clock lets you know where things stand right here and now, portraying the Moon’s phase more accurately than a printed calendar, and whether it’s currently in the sky or has set.

So now you can prepare. No tux! Stay home and put on a comfortable flannel shirt like werewolves do.

This project requires:

  • Adafruit Matrix Portal M4 board
  • Any of our 64x32 pixel “HUB75” (not NeoPixel) RGB LED matrices (other sizes are not supported by this code)
  • USB C cable
  • USB power supply with output of 2 Amps or more
  • WiFi internet access
  • An insatiable hunger for human flesh

This guide will get the software running on the bare Matrix Portal hardware. Mounting or supporting the clock in an enclosure or frame is left as an exercise to the reader.

Next we’ll connect the Matrix Portal board and LED matrix. Do not over-tighten the screws on the power terminals or they can shear off. This is best done in human form.

Parts

Video of a person rotating an LED matrix panel with animation resembling falling colored sand.
Folks love our wide selection of RGB matrices and accessories, for making custom colorful LED displays... and our RGB Matrix Shields...
$24.95
In Stock
USB Type A to Type C Cable - approx 1 meter / 3 ft long
As technology changes and adapts, so does Adafruit. This  USB Type A to Type C cable will help you with the transition to USB C, even if you're still...
$4.95
In Stock

You can use a USB C power supply or a USB micro B with a micro B to C adapter

Angled shot of Official Raspberry Pi Power Supply 5.1V 3A with USB C with Power plug facing down.
The official Raspberry Pi USB-C power supply is here! And of course, we have 'em in classic Adafruit black! Superfast with just the right amount of cable length to get your Pi 4...
$7.95
In Stock
5V 2.5A Switching Power Supply with 20AWG MicroUSB Cable
Our all-in-one 5V 2.5 Amp + MicroUSB cable power adapter is the perfect choice for powering single-board computers like Raspberry Pi, BeagleBone, or anything else that's...
$8.25
In Stock
Angled shot of Micro B USB to USB C Adapter.
As technology changes and adapts, so does Adafruit, and speaking of adapting, this adapter has a Micro B USB jack and a USB C...
$1.25
In Stock

If you'd like your LEDs diffused, some acrylic may help

LED RGB matrix 12" x 12" with "Adafruit Industries LED Matrix" text showing, and LED acrylic slowly covering to make it nicely diffused
A nice whoppin' slab of some lovely black acrylic to add some extra diffusion to your LED Matrix project. This material is 2.6mm (0.1") thick and is made of special cast...
$9.95
In Stock

Adafruit carries a number of 64x32 RGB LED Matrices, varying between the space between LEDs (pitch) and whether rigid or flexible. Choose your favorite - larger pitch means the display is larger, width and height-wise but with the same number of pixels, and larger may be easier to read further away. Smaller for near your desk, for example.

Two white hands hold out an assembled and powered on 64x32 RGB LED Matrix Panel - 3mm pitch. The matrix displays "Adafruit Industries LED MATRIX! 32x64 *RGB*"
Bring a little bit of Times Square into your home with this sweet 64 x 32 square RGB LED matrix panel. These panels are normally used to make video walls, here in New York we see them...
$44.95
In Stock
Vide of assembled and powered on 64x32 RGB LED Matrix Panel - 4mm pitch. The matrix displays "Black Lives Matter" alongside the Raised Fist.
Bring a little bit of Times Square into your home with this sweet 64 x 32 square RGB LED matrix panel. These panels are normally used to make video walls, here in New York we see them...
$39.95
In Stock
Two white hands hold out an assembled and powered on 64x32 RGB LED Matrix Panel - 5mm pitch. The matrix displays "Adafruit Industries LED MATRIX! 32x64 *RGB*"
Bring a little bit of Times Square into your home with this sweet 64x32 square RGB LED matrix panel. These panels are normally used to make video walls, here in New York we see them on...
$49.95
In Stock
Two white hands hold out an assembled and powered on 64x32 RGB LED Matrix Panel - 6mm pitch. The matrix displays "Adafruit Industries LED MATRIX! 32x64 *RGB*"
Bring a little bit of Times Square into your home with this sweet 64x32 square RGB LED matrix panel. These panels are normally used to make video walls, here in New York we see them on...
$64.95
In Stock
Video of woman in a white sleeveless t-shirt holding and slightly bending a black flexible 64x32 RGB LED Matrix. The LED matrix is lit up with rainbow LEDs with the text: Adafruit Industries LED Matrix 32x64 *RGB*.
If you've played with multiplexed RGB matrices, you may have wondered "hey, could we possibly manufacture these on a thin enough PCB, so it's flexible?" and the...
$44.95
In Stock
Two hands flexing a powered on 64x32 Flexible RGB LED Matrix - 5mm Pitch.
If you've played with multiplexed RGB matrices, you may have wondered "hey, could we possibly manufacture these on a thin enough PCB so it's flexible?" and the answer...
Out of Stock

Power Prep

The MatrixPortal supplies power to the matrix display panel via two standoffs. These come with protective tape applied (part of our manufacturing process) which MUST BE REMOVED!

Use some tweezers or a fingernail to remove the two amber circles.

Power Terminals

Next, screw in the spade connectors to the corresponding standoff.

  • red wire goes to +5V 
  • black wire goes to GND

Panel Power

Plug either one of the four-conductor power plugs into the power connector pins on the panel. The plug can only go in one way, and that way is marked on the board's silkscreen.

Dual Matrix Setup

If you're planning to use a 64x64 matrix, follow these instructions on soldering the Address E Line jumper.

Board Connection

Now, plug the board into the left side shrouded 8x2 connector as shown. The orientation matters, so take a moment to confirm that the white indicator arrow on the matrix panel is oriented pointing up and right as seen here and the MatrixPortal overhangs the edge of the panel when connected. This allows you to use the edge buttons from the front side.

 

Check nothing is impeding the board from plugging in firmly. If there's a plastic nub on the matrix that's keeping the Portal from sitting flat, cut it off with diagonal cutters

For info on adding LED diffusion acrylic, see the page LED Matrix Diffuser.

CircuitPython is a derivative of MicroPython designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the CIRCUITPY drive to iterate.

Set up CircuitPython Quick Start!

Follow this quick step-by-step for super-fast Python power :)

Further Information

For more detailed info on installing CircuitPython, check out Installing CircuitPython.

Click the link above and download the latest UF2 file.

Download and save it to your desktop (or wherever is handy).

Plug your MatrixPortal M4 into your computer using a known-good USB cable.

A lot of people end up using charge-only USB cables and it is very frustrating! So make sure you have a USB cable you know is good for data sync.

Double-click the Reset button (indicated by the green arrow) on your board, and you will see the NeoPixel RGB LED (indicated by the magenta arrow) turn green. If it turns red, check the USB cable, try another USB port, etc.

If double-clicking doesn't work the first time, try again. Sometimes it can take a few tries to get the rhythm right!

You will see a new disk drive appear called MATRIXBOOT.

 

Drag the adafruit_circuitpython_etc.uf2 file to MATRIXBOOT.

The LED will flash. Then, the MATRIXBOOT drive will disappear and a new disk drive called CIRCUITPY will appear.

That's it, you're done! :)

Back up any existing code or files you want to keep from your Matrix Portal CIRCUITPY drive.

Installing Project Code

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your CIRCUITPY drive. Then you need to update code.py with the example script.

Thankfully, we can do this in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, open the directory Matrix_Portal_Moon_Clock/ and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your CIRCUITPY drive.

Your CIRCUITPY drive should now look similar to the following image:

# SPDX-FileCopyrightText: 2020 Phillip Burgess for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
MOON PHASE CLOCK for Adafruit Matrix Portal: displays current time, lunar
phase and time of next moonrise or moonset. Requires WiFi internet access.

Written by Phil 'PaintYourDragon' Burgess for Adafruit Industries.
MIT license, all text above must be included in any redistribution.

BDF fonts from the X.Org project. Startup 'splash' images should not be
included in derivative projects, thanks. Tall splash images licensed from
123RF.com, wide splash images used with permission of artist Lew Lashmit
([email protected]). Rawr!
"""

# pylint: disable=import-error
import gc
import time
import math
import board
import busio
import displayio
from rtc import RTC
from adafruit_matrixportal.network import Network
from adafruit_matrixportal.matrix import Matrix
from adafruit_bitmap_font import bitmap_font
import adafruit_display_text.label
import adafruit_lis3dh

try:
    from secrets import secrets
except ImportError:
    print('WiFi secrets are kept in secrets.py, please add them there!')
    raise

# CONFIGURABLE SETTINGS ----------------------------------------------------

TWELVE_HOUR = True # If set, use 12-hour time vs 24-hour (e.g. 3:00 vs 15:00)
COUNTDOWN = False  # If set, show time to (vs time of) next rise/set event
MONTH_DAY = True   # If set, use MM/DD vs DD/MM (e.g. 31/12 vs 12/31)
BITPLANES = 6      # Ideally 6, but can set lower if RAM is tight


# SOME UTILITY FUNCTIONS AND CLASSES ---------------------------------------

def parse_time(timestring, is_dst=-1):
    """ Given a string of the format YYYY-MM-DDTHH:MM:SS.SS-HH:MM (and
        optionally a DST flag), convert to and return an equivalent
        time.struct_time (strptime() isn't available here). Calling function
        can use time.mktime() on result if epoch seconds is needed instead.
        Time string is assumed local time; UTC offset is ignored. If seconds
        value includes a decimal fraction it's ignored.
    """
    date_time = timestring.split('T')        # Separate into date and time
    year_month_day = date_time[0].split('-') # Separate time into Y/M/D
    hour_minute_second = date_time[1].split('+')[0].split('-')[0].split(':')
    return time.struct_time((int(year_month_day[0]),
                            int(year_month_day[1]),
                            int(year_month_day[2]),
                            int(hour_minute_second[0]),
                            int(hour_minute_second[1]),
                            int(hour_minute_second[2].split('.')[0]),
                            -1, -1, is_dst))


def update_time(timezone=None):
    """ Update system date/time from WorldTimeAPI public server;
        no account required. Pass in time zone string
        (http://worldtimeapi.org/api/timezone for list)
        or None to use IP geolocation. Returns current local time as a
        time.struct_time and UTC offset as string. This may throw an
        exception on fetch_data() - it is NOT CAUGHT HERE, should be
        handled in the calling code because different behaviors may be
        needed in different situations (e.g. reschedule for later).
    """
    if timezone: # Use timezone api
        time_url = 'http://worldtimeapi.org/api/timezone/' + timezone
    else: # Use IP geolocation
        time_url = 'http://worldtimeapi.org/api/ip'

    time_data = NETWORK.fetch_data(time_url,
                                   json_path=[['datetime'], ['dst'],
                                              ['utc_offset']])
    time_struct = parse_time(time_data[0], time_data[1])
    RTC().datetime = time_struct
    return time_struct, time_data[2]


def hh_mm(time_struct):
    """ Given a time.struct_time, return a string as H:MM or HH:MM, either
        12- or 24-hour style depending on global TWELVE_HOUR setting.
        This is ONLY for 'clock time,' NOT for countdown time, which is
        handled separately in the one spot where it's needed.
    """
    if TWELVE_HOUR:
        if time_struct.tm_hour > 12:
            hour_string = str(time_struct.tm_hour - 12) # 13-23 -> 1-11 (pm)
        elif time_struct.tm_hour > 0:
            hour_string = str(time_struct.tm_hour) # 1-12
        else:
            hour_string = '12' # 0 -> 12 (am)
    else:
        hour_string = '{0:0>2}'.format(time_struct.tm_hour)
    return hour_string + ':' + '{0:0>2}'.format(time_struct.tm_min)


# pylint: disable=too-few-public-methods
class MoonData():
    """ Class holding lunar data for a given day (00:00:00 to 23:59:59).
        App uses two of these -- one for the current day, and one for the
        following day -- then some interpolations and such can be made.
        Elements include:
        age      : Moon phase 'age' at midnight (start of period)
                   expressed from 0.0 (new moon) through 0.5 (full moon)
                   to 1.0 (next new moon).
        midnight : Epoch time in seconds @ midnight (start of period).
        rise     : Epoch time of moon rise within this 24-hour period.
        set      : Epoch time of moon set within this 24-hour period.
    """
    def __init__(self, datetime, hours_ahead, utc_offset):
        """ Initialize MoonData object elements (see above) from a
            time.struct_time, hours to skip ahead (typically 0 or 24),
            and a UTC offset (as a string) and a query to the MET Norway
            Sunrise API (also provides lunar data), documented at:
            https://api.met.no/weatherapi/sunrise/2.0/documentation
        """
        if hours_ahead:
            # Can't change attribute in datetime struct, need to create
            # a new one which will roll the date ahead as needed. Convert
            # to epoch seconds and back for the offset to work
            datetime = time.localtime(time.mktime(time.struct_time((
                datetime.tm_year,
                datetime.tm_mon,
                datetime.tm_mday,
                datetime.tm_hour + hours_ahead,
                datetime.tm_min,
                datetime.tm_sec,
                -1, -1, -1))))
        # strftime() not available here
        url = ('https://api.met.no/weatherapi/sunrise/2.0/.json?lat=' +
               str(LATITUDE) + '&lon=' + str(LONGITUDE) +
               '&date=' + str(datetime.tm_year) + '-' +
               '{0:0>2}'.format(datetime.tm_mon) + '-' +
               '{0:0>2}'.format(datetime.tm_mday) +
               '&offset=' + utc_offset)
        print('Fetching moon data via', url)
        # pylint: disable=bare-except
        for _ in range(5): # Retries
            try:
                location_data = NETWORK.fetch_data(url,
                                                   json_path=[['location']])
                moon_data = location_data['time'][0]
                #print(moon_data)
                # Reconstitute JSON data into the elements we need
                self.age = float(moon_data['moonphase']['value']) / 100
                self.midnight = time.mktime(parse_time(
                    moon_data['moonphase']['time']))
                if 'moonrise' in moon_data:
                    self.rise = time.mktime(
                        parse_time(moon_data['moonrise']['time']))
                else:
                    self.rise = None
                if 'moonset' in moon_data:
                    self.set = time.mktime(
                        parse_time(moon_data['moonset']['time']))
                else:
                    self.set = None
                return # Success!
            except:
                # Moon server error (maybe), try again after 15 seconds.
                # (Might be a memory error, that should be handled different)
                time.sleep(15)


# ONE-TIME INITIALIZATION --------------------------------------------------

MATRIX = Matrix(bit_depth=BITPLANES)
DISPLAY = MATRIX.display
ACCEL = adafruit_lis3dh.LIS3DH_I2C(busio.I2C(board.SCL, board.SDA),
                                   address=0x19)
_ = ACCEL.acceleration # Dummy reading to blow out any startup residue
time.sleep(0.1)
DISPLAY.rotation = (int(((math.atan2(-ACCEL.acceleration.y,
                                     -ACCEL.acceleration.x) + math.pi) /
                         (math.pi * 2) + 0.875) * 4) % 4) * 90

LARGE_FONT = bitmap_font.load_font('/fonts/helvB12.bdf')
SMALL_FONT = bitmap_font.load_font('/fonts/helvR10.bdf')
SYMBOL_FONT = bitmap_font.load_font('/fonts/6x10.bdf')
LARGE_FONT.load_glyphs('0123456789:')
SMALL_FONT.load_glyphs('0123456789:/.%')
SYMBOL_FONT.load_glyphs('\u21A5\u21A7')

# Display group is set up once, then we just shuffle items around later.
# Order of creation here determines their stacking order.
GROUP = displayio.Group()

# Element 0 is a stand-in item, later replaced with the moon phase bitmap
# pylint: disable=bare-except
try:
    FILENAME = 'moon/splash-' + str(DISPLAY.rotation) + '.bmp'

    # CircuitPython 6 & 7 compatible
    BITMAP = displayio.OnDiskBitmap(open(FILENAME, 'rb'))
    TILE_GRID = displayio.TileGrid(
        BITMAP,
        pixel_shader=getattr(BITMAP, 'pixel_shader', displayio.ColorConverter())
    )

    # # CircuitPython 7+ compatible
    # BITMAP = displayio.OnDiskBitmap(FILENAME)
    # TILE_GRID = displayio.TileGrid(BITMAP, pixel_shader=BITMAP.pixel_shader)

    GROUP.append(TILE_GRID)
except:
    GROUP.append(adafruit_display_text.label.Label(SMALL_FONT, color=0xFF0000,
                                                   text='AWOO'))
    GROUP[0].x = (DISPLAY.width - GROUP[0].bounding_box[2] + 1) // 2
    GROUP[0].y = DISPLAY.height // 2 - 1

# Elements 1-4 are an outline around the moon percentage -- text labels
# offset by 1 pixel up/down/left/right. Initial position is off the matrix,
# updated on first refresh. Initial text value must be long enough for
# longest anticipated string later.
for i in range(4):
    GROUP.append(adafruit_display_text.label.Label(SMALL_FONT, color=0,
                                                   text='99.9%', y=-99))
# Element 5 is the moon percentage (on top of the outline labels)
GROUP.append(adafruit_display_text.label.Label(SMALL_FONT, color=0xFFFF00,
                                               text='99.9%', y=-99))
# Element 6 is the current time
GROUP.append(adafruit_display_text.label.Label(LARGE_FONT, color=0x808080,
                                               text='12:00', y=-99))
# Element 7 is the current date
GROUP.append(adafruit_display_text.label.Label(SMALL_FONT, color=0x808080,
                                               text='12/31', y=-99))
# Element 8 is a symbol indicating next rise or set
GROUP.append(adafruit_display_text.label.Label(SYMBOL_FONT, color=0x00FF00,
                                               text='x', y=-99))
# Element 9 is the time of (or time to) next rise/set event
GROUP.append(adafruit_display_text.label.Label(SMALL_FONT, color=0x00FF00,
                                               text='12:00', y=-99))
DISPLAY.show(GROUP)

NETWORK = Network(status_neopixel=board.NEOPIXEL, debug=False)
NETWORK.connect()

# LATITUDE, LONGITUDE, TIMEZONE are set up once, constant over app lifetime

# Fetch latitude/longitude from secrets.py. If not present, use
# IP geolocation. This only needs to be done once, at startup!
try:
    LATITUDE = secrets['latitude']
    LONGITUDE = secrets['longitude']
    print('Using stored geolocation: ', LATITUDE, LONGITUDE)
except KeyError:
    LATITUDE, LONGITUDE = (
        NETWORK.fetch_data('http://www.geoplugin.net/json.gp',
                           json_path=[['geoplugin_latitude'],
                                      ['geoplugin_longitude']]))
    print('Using IP geolocation: ', LATITUDE, LONGITUDE)

# Load time zone string from secrets.py, else IP geolocation for this too
# (http://worldtimeapi.org/api/timezone for list).
try:
    TIMEZONE = secrets['timezone'] # e.g. 'America/New_York'
except:
    TIMEZONE = None # IP geolocation

# Set initial clock time, also fetch initial UTC offset while
# here (NOT stored in secrets.py as it may change with DST).
# pylint: disable=bare-except
try:
    DATETIME, UTC_OFFSET = update_time(TIMEZONE)
except:
    DATETIME, UTC_OFFSET = time.localtime(), '+00:00'
LAST_SYNC = time.mktime(DATETIME)

# Poll server for moon data for current 24-hour period and +24 ahead
PERIOD = []
for DAY in range(2):
    PERIOD.append(MoonData(DATETIME, DAY * 24, UTC_OFFSET))
# PERIOD[0] is the current 24-hour time period we're in. PERIOD[1] is the
# following 24 hours. Data is shifted down and new data fetched as days
# expire. Thought we might need a PERIOD[2] for certain circumstances but
# it appears not, that's changed easily enough if needed.


# MAIN LOOP ----------------------------------------------------------------

while True:
    gc.collect()
    NOW = time.time() # Current epoch time in seconds

    # Sync with time server every ~12 hours
    if NOW - LAST_SYNC > 12 * 60 * 60:
        try:
            DATETIME, UTC_OFFSET = update_time(TIMEZONE)
            LAST_SYNC = time.mktime(DATETIME)
            continue # Time may have changed; refresh NOW value
        except:
            # update_time() can throw an exception if time server doesn't
            # respond. That's OK, keep running with our current time, and
            # push sync time ahead to retry in 30 minutes (don't overwhelm
            # the server with repeated queries).
            LAST_SYNC += 30 * 60 # 30 minutes -> seconds

    # If PERIOD has expired, move data down and fetch new +24-hour data
    if NOW >= PERIOD[1].midnight:
        PERIOD[0] = PERIOD[1]
        PERIOD[1] = MoonData(time.localtime(), 24, UTC_OFFSET)

    # Determine weighting of tomorrow's phase vs today's, using current time
    RATIO = ((NOW - PERIOD[0].midnight) /
             (PERIOD[1].midnight - PERIOD[0].midnight))
    # Determine moon phase 'age'
    # 0.0  = new moon
    # 0.25 = first quarter
    # 0.5  = full moon
    # 0.75 = last quarter
    # 1.0  = new moon
    if PERIOD[0].age < PERIOD[1].age:
        AGE = (PERIOD[0].age +
               (PERIOD[1].age - PERIOD[0].age) * RATIO) % 1.0
    else: # Handle age wraparound (1.0 -> 0.0)
        # If tomorrow's age is less than today's, it indicates a new moon
        # crossover. Add 1 to tomorrow's age when computing age delta.
        AGE = (PERIOD[0].age +
               (PERIOD[1].age + 1 - PERIOD[0].age) * RATIO) % 1.0

    # AGE can be used for direct lookup to moon bitmap (0 to 99) -- these
    # images are pre-rendered for a linear timescale (solar terminator moves
    # nonlinearly across sphere).
    FRAME = int(AGE * 100) % 100 # Bitmap 0 to 99

    # Then use some trig to get percentage lit
    if AGE <= 0.5: # New -> first quarter -> full
        PERCENT = (1 - math.cos(AGE * 2 * math.pi)) * 50
    else:          # Full -> last quarter -> new
        PERCENT = (1 + math.cos((AGE - 0.5) * 2 * math.pi)) * 50

    # Find next rise/set event, complicated by the fact that some 24-hour
    # periods might not have one or the other (but usually do) due to the
    # Moon rising ~50 mins later each day. This uses a brute force approach,
    # working backwards through the time periods to locate rise/set events
    # that A) exist in that 24-hour period (are not None), B) are still in
    # the future, and C) are closer than the last guess. What's left at the
    # end is the next rise or set (and the inverse of the event type tells
    # us whether Moon's currently risen or not).
    NEXT_EVENT = PERIOD[1].midnight + 100000 # Force first match
    for DAY in reversed(PERIOD):
        if DAY.rise and NEXT_EVENT >= DAY.rise >= NOW:
            NEXT_EVENT = DAY.rise
            RISEN = False
        if DAY.set and NEXT_EVENT >= DAY.set >= NOW:
            NEXT_EVENT = DAY.set
            RISEN = True

    if DISPLAY.rotation in (0, 180): # Horizontal 'landscape' orientation
        CENTER_X = 48      # Text along right
        MOON_Y = 0         # Moon at left
        TIME_Y = 6         # Time at top right
        EVENT_Y = 26       # Rise/set at bottom right
    else:                  # Vertical 'portrait' orientation
        CENTER_X = 16      # Text down center
        if RISEN:
            MOON_Y = 0     # Moon at top
            EVENT_Y = 38   # Rise/set in middle
            TIME_Y = 49    # Time/date at bottom
        else:
            TIME_Y = 6     # Time/date at top
            EVENT_Y = 26   # Rise/set in middle
            MOON_Y = 32    # Moon at bottom

    print()

    # Update moon image (GROUP[0])
    FILENAME = 'moon/moon' + '{0:0>2}'.format(FRAME) + '.bmp'

    # CircuitPython 6 & 7 compatible
    BITMAP = displayio.OnDiskBitmap(open(FILENAME, 'rb'))
    TILE_GRID = displayio.TileGrid(
        BITMAP,
        pixel_shader=getattr(BITMAP, 'pixel_shader', displayio.ColorConverter())
    )

    # # CircuitPython 7+ compatible
    # BITMAP = displayio.OnDiskBitmap(FILENAME)
    # TILE_GRID = displayio.TileGrid(BITMAP, pixel_shader=BITMAP.pixel_shader)

    TILE_GRID.x = 0
    TILE_GRID.y = MOON_Y
    GROUP[0] = TILE_GRID

    # Update percent value (5 labels: GROUP[1-4] for outline, [5] for text)
    if PERCENT >= 99.95:
        STRING = '100%'
    else:
        STRING = '{:.1f}'.format(PERCENT + 0.05) + '%'
    print(NOW, STRING, 'full')
    # Set element 5 first, use its size and position for setting others
    GROUP[5].text = STRING
    GROUP[5].x = 16 - GROUP[5].bounding_box[2] // 2
    GROUP[5].y = MOON_Y + 16
    for _ in range(1, 5):
        GROUP[_].text = GROUP[5].text
    GROUP[1].x, GROUP[1].y = GROUP[5].x, GROUP[5].y - 1 # Up 1 pixel
    GROUP[2].x, GROUP[2].y = GROUP[5].x - 1, GROUP[5].y # Left
    GROUP[3].x, GROUP[3].y = GROUP[5].x + 1, GROUP[5].y # Right
    GROUP[4].x, GROUP[4].y = GROUP[5].x, GROUP[5].y + 1 # Down

    # Update next-event time (GROUP[8] and [9])
    # Do this before time because we need uncorrupted NOW value
    EVENT_TIME = time.localtime(NEXT_EVENT) # Convert to struct for later
    if COUNTDOWN: # Show NEXT_EVENT as countdown to event
        NEXT_EVENT -= NOW # Time until (vs time of) next rise/set
        MINUTES = NEXT_EVENT // 60
        STRING = str(MINUTES // 60) + ':' + '{0:0>2}'.format(MINUTES % 60)
    else: # Show NEXT_EVENT in clock time
        STRING = hh_mm(EVENT_TIME)
    GROUP[9].text = STRING
    XPOS = CENTER_X - (GROUP[9].bounding_box[2] + 6) // 2
    GROUP[8].x = XPOS
    if RISEN:                    # Next event is SET
        GROUP[8].text = '\u21A7' # Downwards arrow from bar
        GROUP[8].y = EVENT_Y - 2
        print('Sets:', STRING)
    else:                        # Next event is RISE
        GROUP[8].text = '\u21A5' # Upwards arrow from bar
        GROUP[8].y = EVENT_Y - 1
        print('Rises:', STRING)
    GROUP[9].x = XPOS + 6
    GROUP[9].y = EVENT_Y
    # Show event time in green if a.m., amber if p.m.
    GROUP[8].color = GROUP[9].color = (0x00FF00 if EVENT_TIME.tm_hour < 12
                                       else 0xC04000)

    # Update time (GROUP[6]) and date (GROUP[7])
    NOW = time.localtime()
    STRING = hh_mm(NOW)
    GROUP[6].text = STRING
    GROUP[6].x = CENTER_X - GROUP[6].bounding_box[2] // 2
    GROUP[6].y = TIME_Y
    if MONTH_DAY:
        STRING = str(NOW.tm_mon) + '/' + str(NOW.tm_mday)
    else:
        STRING = str(NOW.tm_mday) + '/' + str(NOW.tm_mon)
    GROUP[7].text = STRING
    GROUP[7].x = CENTER_X - GROUP[7].bounding_box[2] // 2
    GROUP[7].y = TIME_Y + 10

    DISPLAY.refresh() # Force full repaint (splash screen sometimes sticks)
    time.sleep(5)

One additional file you’ll create or edit yourself — secrets.py — is explained on the next page…

secrets.py on the CIRCUITPY drive holds your WiFi network credentials and other info. This file can be created or edited with any simple text editor you prefer. It resides in the root directory of the CIRCUITPY drive, not inside a folder.

If you already have this file on your Matrix Portal from prior projects…great!

If not, it should resemble what’s below, with the ssid and password lines. The corresponding values for these (after the colon) is in single-quotes.

The format of this file is super persnickety, every space and comma counts! If creating it for the first time, best to copy-and-paste the text below exactly, then change any items of interest (preserving quotation marks and such).

Latitude and longitude are optional but recommended. The clock can do IP geolocation (estimating your location using IP address), but having it here is more accurate and avoids another server query on startup. These values are floating-point numbers (in degrees and decimal fractions thereof) and should not be in quotes. For latitude, positive values are north, negative is south. For longitude, negative is west, positive is east.

secrets = {
    'ssid'      : 'WiFi-Network-Name',
    'password'  : 'WiFi-Network-Password',
    'latitude'  : 32.71193,
    'longitude' : -117.16072
}

You can easily get your decimal latitude and longitude from Google Maps. Zoom in on a location and right-click on the map. Information there includes latitude and longitude in exactly the format we need…click the coordinates to copy them to the clipboard, then paste into the secrets file and reformat the text as shown above.

The code will relaunch any time there’s a change on the CIRCUITPY drive…so, after editing secrets.py, the clock should start up on its own and you’ll see a splash screen after a few seconds.

If the clock does NOT start up, or shows the splash screen but then crashes: most likely the WiFi credentials are incorrect, or something is wrong with the secrets.py file syntax…make sure every quote, comma and colon is there and in the right place.

On power-up, the clock will display a splash screen while it connects to the WiFi network and makes a couple of initial server requests for time and Moon data.

Time is provided by WorldTimeAPI, and astronomical data from the Norwegian Meteorological Institute. These two sources were chosen as they are free and do not require an account for access.

The orientation of the clock at startup determines how information is displayed — in a vertical “portrait” format, or horizontal “landscape” format.

Clock Operation Basics

With the clock set up horizontally (either hung or propped up with a stand or case), the current Moon phase (with percentage lit) is displayed on the left.

The current time and date are displayed on the right. Below this is an indication of the next moonrise or set…

A downward-pointing arrow (as shown above) indicates the next lunar event will be a moonset — that the Moon is currently above the horizon (in the sky) as seen from your position, regardless of phase.

An upward-pointing arrow indicates a moonrise is next — the Moon is currently below the horizon, not currently visible from your position, regardless of phase.

The time shown next to the arrow is when this next lunar rise or set event will occur. It can alternately be configured as a countdown, explained shortly.

The color of the time and arrow indicates whether this next event occurs in the a.m. hours (green) or p.m. (amber).

The rise and set times are for an “idealized” horizon. Hills or other local obstructions could have it rising a short time later or setting earlier.

All the same data is displayed when the clock’s in a vertical orientation, but the visibility of the Moon from your location is made more apparent.

When the Moon is above the local horizon (in the sky) the phase is shown at the top of the matrix.

And if the Moon is currently below the local horizon, the phase scoots to the bottom.

The Moon might still appear above the horizon for someone to the west of you, but the phase will be nearly the same. That’s how this game of cosmic billiards works.

The percentage shown is the amount of the lunar “disc” that’s currently illuminated, not the “age” of the current lunar month. So this will go from 0% (new Moon) to 100%* (full Moon) and back down to 0% (next new Moon) over the course of the lunar month. The lunar terminator — the line between light and dark — always moves right to left, like turning the pages of a book (that’s why it doesn’t bother reporting if the phase is waxing or waning — it’s easy to visualize).

* It’s normal some months that you’ll see this only go to 99.8 or 99.9 percent…the Moon’s never quite perfectly full from our position.

If the clock starts up in the wrong orientation…just tap the reset button and let it try again. Occasionally the accelerometer gets confused when grappling the clock to plug it in, or the “snap” of a USB cable being inserted.

Customizing the Clock Display

Some aspects of the clock display can be changed by editing the file code.py in your text editor of choice. Starting around line 35, look for this section of code:

# CONFIGURABLE SETTINGS -------------------------------------

TWELVE_HOUR = True # If set, use 12-hour time vs 24-hour
COUNTDOWN = False  # If set, show time to next rise/set event

Change the value of TWELVE_HOUR to False (capitalized — Python is case sensitive) to have the clock display times in 24-hour military time.

Changing COUNTDOWN to True makes the clock show the time to the next rise/set event (hours and minutes), rather than the time of the event. Both modes are shown in the same HH:MM format, so COUNTDOWN mode may be confusing if you’re not familiar with the clock’s operation.

The startup splash screen images are inside the moon folder, named splash-0.bmpsplash-90.bmpsplash-180.bmp and splash-270.bmp — one image is selected on startup based on the Matrix Portal orientation. If you’ve settled on a position for installing your Moon clock but want the opposite splash image, you can just rename these files, e.g. swap the filenames on splash-0.bmp and splash-180.bmp (or 90 and 270). Or you can delete the splash images (they might be frightening to children) or substitute your own BMP files.

Matrix brightness is not currently adjustable. It’s just more than the microcontroller can handle.

Timekeeping

The clock will periodically contact a time server to keep itself in sync. But if you observe the time drifting by more than a minute or two, you can have it sync more often.

Look for these lines in code.py (in the “MAIN LOOP” section):

# Sync with time server every ~12 hours
if NOW - LAST_SYNC > 12 * 60 * 60:

Change the 12 to a smaller value…perhaps 6, or 3 if the time drift is really pronounced. This is the period (in hours) between clock updates. To avoid over-taxing the server, which they’re providing as a free service, don’t set this too low.

Interestingly, the clock will keep better time if powered from a computer’s USB port (which provides a steady 1.000 KHz reference pulse) than from a passive USB “wall wart.” Not always practical, of course…but if you have a free USB port on a NAS or other nearby system that runs 24/7, it’s something to consider.

led_matrices_full-moon-wikipedia.jpg
Image credit: Rogério da silva Santana, Wikipedia

So what's the big deal? What’s wrong with the Moon phases on wall calendars? Surely those dates come from trusted sources! NASA, almanacs and stuff!

The problems are many…some technical, some semantic…each alone may be minor, but there’s the potential for them to compound and really mix things up.

  • Most importantly, unless they explain their data sources, static media can’t take into account different time zones. At any given moment, the Moon’s phase appears nearly the same from anywhere on Earth (if it’s above the local horizon), but the time of day…and even the day itself…may vary. If a calendar is basing their phases on UTC time but you’re in North America, they might be reporting a lunar phase on on a Thursday while to you it’s still late Wednesday (this can happen in the other direction too).
  • Each day’s changeover at midnight doesn’t align with our semantic concept of a “night” — we tend to lump early morning hours with the prior day. So, if a lunar phase crossing occurs in the early hours after midnight (for a given time zone), it might be reported as Thursday, while we’re inclined to think of it as late Wednesday night…but, seeing Thursday on the calendar, we think “Thursday night” and could easily end up celebrating a “full” Moon that’s past its ideal freshness date.
  • What even is “full,” or any other phase of the Moon? It’s erroneous to think there’s a single night that the Moon is locked in “full,” because this is an analog system with celestial bodies in continual motion, and phase can change by several percent in a single 24-hour period. To the unaided eye, anything more than about 98% illumination of the lunar disc is pretty much indistinguishable from “full,” and you’ll get two to three successive nights that would qualify. Those dates on the calendar typically refer to an “instantaneous” phase crossing (and once again, for whatever time zone they’re using for reference). If at that moment the Moon is below the horizon (is on the opposite side of the planet from you, due to the Earth’s rotation), and if your definition of “full” is too narrow…have you really experienced a full Moon at all? Sometimes it’s okay to think of a phase as “ish.”
  • Sometimes just sloppy reporting…the instantaneous time of a phase crossing is sometimes improperly reported as the Moon rise time instead, and other slip-ups.

As you can see, it’s A Huge Ordeal, and that was the inspiration for making this clock. No more “do they mean Wednesday night or Thursday morning?” This is the Moon as it is right now.

Other Moon Factoids

  • We tend to think of the Moon as a nighttime phenomenon, but really it spends just as much time on the daylight side. During a new Moon, it rises and sets close to the same time as the Sun, the narrow crescent lost in the glare of the daylight sky.
  • The cycle of phases — the “lunar month” — is about 29.5 days long. It varies a bit due to the elliptical nature of orbits and that the Earth-Moon system is in turn orbiting the Sun.
  • If you really want to get lost in all the details, NASA’s Dial-A-Moon page is packed with information and nuance!
  • A lunar eclipse can only happen during the full Moon, but not all full Moons experience a lunar eclipse … the orbital planes of the Earth and Moon diverge by a few degrees. Correspondingly, a solar eclipse can only happen during the new Moon, but not all new Moons experience a solar eclipse. (WolfCop got this wrong, with a solar eclipse the day after a full moon, and I’m still bitter about it.)
  • Some full moons have special names — a “blue Moon” is an infrequent second full Moon in the same month, the “pink Moon” is usually the full Moon in April — but these are only names and are not actually descriptive of the Moon’s color. Sometimes atmospheric phenomena (smoke, etc.) can cast the Moon in varying hues, but it’s entirely unrelated to these names.

This guide was first published on Sep 23, 2020. It was last updated on Sep 23, 2020.