Overview

Surfs up! Or is it?

Do you live near an ocean or some other tidal body of water? Do you want to know what time high tide is? Low tide? Or even the overall tide level throughout the day? This guide will show how you can use an Adafruit PyPortal smart display to easily fetch tide information from the Internet and display it.

CircuitPython is used for the code and the PyPortal library does all the heavy lifting. All that's left is some  initial data entry and it's ready for display.

Parts

The parts for this project are available on AdaBox 011 or individually:

AdaBox011 - PyPortal

PRODUCT ID: 4061
Reach out beyond your desk - to the stars and beyond - with PyPortal! This ADABOX features a new, easy-to-use IoT device that allows you to customize and create your...
$69.95
IN STOCK

Adafruit PyPortal - CircuitPython Powered Internet Display

PRODUCT ID: 4116
PyPortal, our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Make custom touch screen interface...
OUT OF STOCK

Adafruit PyPortal Desktop Stand Enclosure Kit

PRODUCT ID: 4146
PyPortal is our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Create little pocket...
OUT OF STOCK

Pink and Purple Braided USB A to Micro B Cable - 2 meter long

PRODUCT ID: 4148
This cable is super-fashionable with a woven pink and purple Blinka-like pattern!First let's talk about the cover and over-molding. We got these in custom colors,...
$3.95
IN STOCK

Install CircuitPython

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 "flash" drive to iterate.

The following instructions will show you how to install CircuitPython. If you've already installed CircuitPython but are looking to update it or reinstall it, the same steps work for that as well!

Set up CircuitPython Quick Start!

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

Click the link above to download the latest version of CircuitPython for the PyPortal.

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

Plug your PyPortal 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 on the top in the middle (magenta arrow) on your board, and you will see the NeoPixel RGB LED (green arrow) turn green. If it turns red, check the USB cable, try another USB port, etc. Note: The little red LED next to the USB connector will pulse red. That's ok!

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 PORTALBOOT.

Drag the adafruit-circuitpython-pyportal-<whatever>.uf2 file to PORTALBOOT.

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

If you haven't added any code to your board, the only file that will be present is boot_out.txt. This is absolutely normal! It's time for you to add your code.py and get started!

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

PyPortal Default Files

Click below to download a zip of the files that shipped on the PyPortal.

PyPortal CircuitPython Setup

To use all the amazing features of your PyPortal with CircuitPython, you must first install a number of libraries. This page covers that process.

Adafruit CircuitPython Bundle

Download the Adafruit CircuitPython Library Bundle. You can find the latest release here:

Download the adafruit-circuitpython-bundle-4.x-mpy-*.zip bundle zip file, and unzip a folder of the same name. Inside you'll find a lib folder. You have two options:

  • You can add the lib folder to your CIRCUITPY drive. This will ensure you have all the drivers. But it will take a bunch of space on the 8 MB disk
  • Add each library as you need it, this will reduce the space usage but you'll need to put in a little more effort.

At a minimum we recommend the following libraries, in fact we more than recommend. They're basically required. So grab them and install them into CIRCUITPY/lib now!

  • adafruit_esp32spi - This is the library that gives you internet access via the ESP32 using (you guessed it!) SPI transport. You need this for anything Internet
  • adafruit_pyportal - This is our friendly wrapper library that does a lot of our projects, displays graphics and text, fetches data from the internet. Nearly all of our projects depend on it!
  • adafruit_touchscreen - a library for reading touches from the resistive touchscreen. Handles all the analog noodling, rotation and calibration for you.
  • adafruit_io - this library helps connect the PyPortal to our free datalogging and viewing service
  • adafruit_imageload - an image display helper, required for any graphics!
  • adafruit_display_text - not surprisingly, it displays text on the screen
  • adafruit_bitmap_font - we have fancy font support, and its easy to make new fonts. This library reads and parses font files.
  • adafruit_slideshow - for making image slideshows - handy for quick display of graphics and sound
  • neopixel - for controlling the onboard neopixel
  • adafruit_adt7410 - library to read the temperature from the on-board Analog Devices ADT7410 precision temperature sensor
  • adafruit_sdcard - support for reading/writing data from the onboard SD card slot.
  • adafruit_bus_device - low level support for I2C/SPI

Internet Connect!

Once you have CircuitPython setup and libraries installed we can get your board connected to the Internet. Note that access to enterprise level secured WiFi networks is not currently supported, only WiFi networks that require SSID and password.

To get connected, you will need to start by creating a secrets file.

What's a secrets file?

We expect people to share tons of projects as they build CircuitPython WiFi widgets. What we want to avoid is people accidentally sharing their passwords or secret tokens and API keys. So, we designed all our examples to use a secrets.py file, that is in your CIRCUITPY drive, to hold secret/private/custom data. That way you can share your main project without worrying about accidentally sharing private stuff.

Your secrets.py file should look like this:

Download: file
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : 'home ssid',
    'password' : 'my password',
    'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
    'github_token' : 'fawfj23rakjnfawiefa',
    'hackaday_token' : 'h4xx0rs3kret',
    }

Inside is a python dictionary named secrets with a line for each entry. Each entry has an entry name (say 'ssid') and then a colon to separate it from the entry key 'home ssid' and finally a comma ,

At a minimum you'll need the ssid and password for your local WiFi setup. As you make projects you may need more tokens and keys, just add them one line at a time. See for example other tokens such as one for accessing github or the hackaday API. Other non-secret data like your timezone can also go here, just cause its called secrets doesn't mean you can't have general customization data in there!

For the correct time zone string, look at http://worldtimeapi.org/timezones and remember that if your city is not listed, look for a city in the same time zone, for example Boston, New York, Philadelphia, Washington DC, and Miami are all on the same time as New York.

Of course, don't share your secrets.py - keep that out of GitHub, Discord or other project-sharing sites.

Connect to WiFi

OK now you have your secrets setup - you can connect to the Internet. Lets use the ESP32SPI library - you'll need to visit the CircuitPython bundle and install:

  • adafruit_bus_device
  • adafruit_esp32spi
  • neopixel

Into your lib folder. Once that's done, load up the following example using Mu or your favorite editor:

import board
import busio
from digitalio import DigitalInOut

from adafruit_esp32spi import adafruit_esp32spi
import adafruit_esp32spi.adafruit_esp32spi_requests as requests

print("ESP32 SPI webclient test")

TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json"


# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

requests.set_interface(esp)

if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
print("Firmware vers.", esp.firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address])

for ap in esp.scan_networks():
    print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi']))

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
    except RuntimeError as e:
        print("could not connect to AP, retrying: ",e)
        continue
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))
print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com")))
print("Ping google.com: %d ms" % esp.ping("google.com"))

#esp._debug = True
print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL)
print('-'*40)
print(r.text)
print('-'*40)
r.close()

print()
print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL)
print('-'*40)
print(r.json())
print('-'*40)
r.close()

print("Done!")

And save it to your board, with the name code.py

This first connection example doesn't use a secrets file - you'll hand-enter your SSID/password to verify connectivity first!

Then go down to this line

esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')

and change MY_SSID_NAME and MY_SSID_PASSWORD to your access point name and password, keeping them within the '' quotes. (This example doesn't use the secrets' file, but its also very stand-alone so if other things seem to not work you can always re-load this. You should get something like the following:

In order, the example code...

Initializes the ESP32 over SPI using the SPI port and 3 control pins:

Download: file
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

Tells our requests mimic library the name of the WiFi interface object (this is a little bit of a hack but lets us use requests like CPython does)

Download: file
requests.set_interface(esp)

Verifies an ESP32 is found, checks the firmware and MAC address

Download: file
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
print("Firmware vers.", esp.firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address])

Performs a scan of all access points it can see and prints out the name and signal strength:

Download: file
for ap in esp.scan_networks():
    print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi']))

Connects to the AP we've defined here, then prints out the local IP address, attempts to do a domain name lookup and ping google.com to check network connectivity (note sometimes the ping fails or takes a while, this isn't a big deal)

Download: file
    print("Connecting to AP...")
esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))
print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com")))
print("Ping google.com: %d ms" % esp.ping("google.com"))
  

OK now we're getting to the really interesting part. With a SAMD51 or other large-RAM (well, over 32 KB) device, we can do a lot of neat tricks. Like for example we can implement an interface a lot like requests - which makes getting data really really easy

To read in all the text from a web URL call requests.get - you can pass in https URLs for SSL connectivity

Download: file
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL)
print('-'*40)
print(r.text)
print('-'*40)
r.close()

Or, if the data is in structured JSON, you can get the json pre-parsed into a Python dictionary that can be easily queried or traversed. (Again, only for nRF52840, M4 and other high-RAM boards)

Download: file
JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json"
print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL)
print('-'*40)
print(r.json())
print('-'*40)
r.close()

WiFi Manager

That simpletest example works but its a little finicky - you need to constantly check WiFi status and have many loops to manage connections and disconnections. For more advanced uses, we recommend using the WiFiManager object. It will wrap the connection/status/requests loop for you - reconnecting if WiFi drops, resetting the ESP32 if it gets into a bad state, etc.

Here's a more advanced example that shows the WiFi manager and also how to POST data with some extra headers:

import time
import board
import busio
from digitalio import DigitalInOut
import neopixel
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager

print("ESP32 SPI webclient test")

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4"""
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
# Uncomment below for an externally defined RGB LED
# import adafruit_rgbled
# from adafruit_esp32spi import PWMOut
# RED_LED = PWMOut.PWMOut(esp, 26)
# GREEN_LED = PWMOut.PWMOut(esp, 27)
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

counter = 0

while True:
    try:
        print("Posting data...", end='')
        data = counter
        feed = 'test'
        payload = {'value':data}
        response = wifi.post(
            "https://io.adafruit.com/api/v2/"+secrets['aio_username']+"/feeds/"+feed+"/data",
            json=payload,
            headers={"X-AIO-KEY":secrets['aio_key']})
        print(response.json())
        response.close()
        counter = counter + 1
        print("OK")
    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying\n", e)
        wifi.reset()
        continue
    response = None
    time.sleep(15)

You'll note here we use a secrets.py file to manage our SSID info. The wifimanager is given the ESP32 object, secrets and a neopixel for status indication.

Note, you'll need to add a some additional information to your secrets file so that the code can query the Adafruit IO API:

  • aio_username
  • aio_key

You can go to your adafruit.io View AIO Key link to get those two values and add them to the secrets file, which will now look something like this:

Download: file
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : '_your_ssid_',
    'password' : '_your_wifi_password_',
    'timezone' : "America/Los_Angeles", # http://worldtimeapi.org/timezones
    'aio_username' : '_your_aio_username_',
    'aio_key' : '_your_aio_key_',
    }

Next, set up an Adafruit IO feed named test

We can then have a simple loop for posting data to Adafruit IO without having to deal with connecting or initializing the hardware!

Take a look at your test feed on Adafruit.io and you'll see the value increase each time the CircuitPython board posts data to it!

NOAA Tides Web Service

We will use a web service provided by the National Oceanic and Atmospheric Administration (NOAA) to get our tide information. One benefit of this is that no API key is needed, since it's your tax dollars at work. However, since this is a part of the US government, the service only covers regions of the United States.

If you live outside the United States, you may have to find a service which sends out tide data as a JSON feed and adapt the code to your new data source. The framework laid out here should provide you a great starting point.

NOAA CO-OPS API

Wow, acronyms! We already covered NOAA above. CO-OPS stands for Center for Operational Oceanographic Products and Services. Why is there a dash? Don't know, it's just what the government does. But also, it doesn't really matter. If you want to know more, read about it here.

API stands for Application Programming Interface, a general term used a lot in programming. The CO-OPS API is one of many web services that NOAA provides. There's a complete list here.

The main documentation for the web service we will use is here:

There are a lot of options and types of data that can be returned. We've worked out the magic invocation needed for the PyPortal and you can find it in the code later. The only item you will need to worry about is finding your closest tide monitoring station ID. This is how you will set your location in the code.

So let's see how you can figure that out next.

Find Your Tide Station ID

To find you station ID, start by going to this webpage:

Scroll down a bit and you'll see a map. You can simply click on the state of interest. Note that some states are not clickable. That's because they don't have tides :(

Once you've clicked on a state you'll get a familiar map like interface that you can drag and zoom around. Use that to zoom in and find the station marker that seems like it will work best for your location.

Click on the marker and it will bring up information about that marker.

The station ID will be the number shown near the top. This is what you will enter into your code.

Basic Tide Time Info

Here's the URL that gets the high and low times for the current day at the station location. The station ID is the very last thing in the URL, so you can change it for your location if you want.

Download: file
https://tidesandcurrents.noaa.gov/api/datagetter?date=today&product=predictions&datum=mllw&interval=hilo&format=json&units=metric&time_zone=lst_ldt&station=9447130

If you put that address in your web browser you'll get something that looks like this:

Not a very pretty web page. That's because it's just JSON data. The key predictions is the root for all the data. Then there are several entries that look like:

Download: file
{"t":"2019-04-15 02:55", "v":"3.401", "type":"H"}

The t entry gives us the date and time, the v entry gives us the tide level, and the type is H for high tide or L for low tide.

So we have what we need - the time for each of the high and low tides for the given day. You'll see how this is parsed out later in the code.

Tide Levels Throughout the Day

With a slight modification of the URL, we can get predicted water levels in 6 minute increments over the period of the current day. Here's the URL for that:

Download: file
https://tidesandcurrents.noaa.gov/api/datagetter?date=today&product=predictions&datum=mllw&format=json&units=metric&time_zone=lst_ldt&station=9447130

More data like before, but now much more of it!

With data every 6 minutes, that's 10 per hour, or 240 for the entire day. And now each entry contains simply t and v. So for the given time t, we get the predicted water level v. We can use that to make a neat little plot of water level vs. time for the day. This will give us a graphical representation of the tidal activity.

High Low Tide Times Viewer

This version is just a basic tide time information viewer. It shows the times when the daily high and low times will occur. Typically there will be two of each per day.

Let's get the code loaded up and running first, since that's more fun. We'll discuss how the parsing works after that.

Add 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_Tides.

Copy the contents of the PyPortal_Tides directory to your PyPortal's CIRCUITPY drive, and then be sure to rename pp_tides.py to code.py so it will automatically run when the PyPortal restarts.

Editing the Code

At the top of the code, find the line that sets the station ID and change it for your location:

Download: file
STATION_ID = "9447130"   # tide location, find yours here: https://tidesandcurrents.noaa.gov/

Note that it is entered as a string, not a number. So don't remove the quotation marks.

import time
import board
from adafruit_pyportal import PyPortal
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text.label import Label

#--| USER CONFIG |--------------------------
STATION_ID = "9447130"   # tide location, find yours here: https://tidesandcurrents.noaa.gov/
HI_COLOR   = 0x00FF00    # high tide times color
LO_COLOR   = 0x11FFFF    # low tide times color
DATE_COLOR = 0xFFFFFF    # date and time color
#-------------------------------------------

# pylint: disable=line-too-long
DATA_SOURCE = "https://tidesandcurrents.noaa.gov/api/datagetter?date=today&product=predictions&datum=mllw&interval=hilo&format=json&units=metric&time_zone=lst_ldt&station="+STATION_ID
DATA_LOCATION = ["predictions"]

# determine the current working directory needed so we know where to find files
cwd = ("/"+__file__).rsplit('/', 1)[0]
pyportal = PyPortal(url=DATA_SOURCE,
                    json_path=DATA_LOCATION,
                    status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"/tides_bg.bmp")

# Connect to the internet and get local time
pyportal.get_local_time()

# Setup tide times font
tide_font = bitmap_font.load_font(cwd+"/fonts/cq-mono-30.bdf")
tide_font.load_glyphs(b'1234567890:')

# Setup date and time font
date_font = bitmap_font.load_font(cwd+"/fonts/Arial-12.bdf")
date_font.load_glyphs(b'1234567890-')

# Labels setup
HI_LABELS = [ Label(tide_font, text="00:00", color=HI_COLOR, x= 40, y= 80) ,
              Label(tide_font, text="00:00", color=HI_COLOR, x= 40, y=165) ]
LO_LABELS = [ Label(tide_font, text="00:00", color=LO_COLOR, x=180, y= 80) ,
              Label(tide_font, text="00:00", color=LO_COLOR, x=180, y=165) ]
DATE_LABEL = Label(date_font, text="0000-00-00 00:00:00", color=DATE_COLOR, x=75, y=228)

# Add all the labels to the display
for label in HI_LABELS + LO_LABELS + [DATE_LABEL]:
    pyportal.splash.append(label)

def get_tide_info():
    """Fetch JSON tide time info and return it."""

    # Get raw JSON data
    raw_info = pyportal.fetch()

    # Return will be a dictionary of lists containing tide times
    new_tide_info = {"H":[], "L":[]}

    # Parse out the tide time info
    for info in raw_info:
        tide_type = info["type"]
        tide_time = info["t"].split(" ")[1]
        new_tide_info[tide_type].append(tide_time)

    return new_tide_info

def update_display(time_info, update_tides=False):
    """Update the display with current info."""

    # Tide time info
    if update_tides:
        # out with the old
        for tide_label in HI_LABELS + LO_LABELS:
            tide_label.text = ""
        # in with the new
        for i, hi_time in enumerate(tide_info["H"]):
            HI_LABELS[i].text = hi_time
        for i, lo_time in enumerate(tide_info["L"]):
            LO_LABELS[i].text = lo_time

    # Date and time
    DATE_LABEL.text = "{:04}-{:02}-{:02} {:02}:{:02}:{:02}".format(time_info.tm_year,
                                                                   time_info.tm_mon,
                                                                   time_info.tm_mday,
                                                                   time_info.tm_hour,
                                                                   time_info.tm_min,
                                                                   time_info.tm_sec)

    board.DISPLAY.refresh_soon()

# First run update
tide_info = get_tide_info()
current_time = time.localtime()
update_display(current_time, True)
current_yday = current_time.tm_yday

# Update daily
while True:
    current_time = time.localtime()
    new_tides = False
    if current_time.tm_yday != current_yday:
        # new day, time to update
        tide_info = get_tide_info()
        new_tides = True
        current_yday = current_time.tm_yday
    update_display(current_time, new_tides)
    time.sleep(0.5)

How It Works

As mentioned previously, the JSON data we need to deal with looks like this:

Download: file
{ "predictions" : [ {"t":"2019-04-15 02:55", "v":"3.401", "type":"H"},{"t":"2019-04-15 09:01", "v":"1.586", "type":"L"},{"t":"2019-04-15 14:04", "v":"2.780", "type":"H"},{"t":"2019-04-15 20:33", "v":"0.111", "type":"L"} ]}

All of the data mangling work is done in the function get_tide_info(). So let's walk through that.

When we setup our PyPortal object, we told it we want the information rooted at predictions. Once that is setup, along with providing the URL, to connect to the Internet and retrieve the data we simply call fetch() from the PyPortal library.

Download: file
    raw_data = pyportal.fetch()

Now we need to parse out the data in raw_data. We could come up with various ways of storing the results, but here we use a dictionary of lists. This will have an "H" entry which will contain the times for the high tides and an "L" entry which will contain the times for the low tides.

This choice of keys for the dictionary is not arbitrary. It was chosen to match the type values in the return results. That way we can use those directly as the dictionary keys.

We set this up initially with blank entries for the lists:

Download: file
    new_tide_info = {"H":[], "L":[]}

Then we loop over each entry and parse the data. We use type as is for the key. We don't want the date part of the t entry, so we split it on the space and save only the second part - the time.

Download: file
    for info in raw_info:
        tide_type = info["type"]
        tide_time = info["t"].split(" ")[1]
        new_tide_info[tide_type].append(tide_time)

Done! Now new_tide_info has what we want, so we return it.

Download: file
    return new_tide_info

The rest of the code just displays these results. The very bottom of the code is a loop that runs for ever. Once a day it will go and fetch the new tide data.

Graphical Tide Level Viewer

This version is a little fancier. It provides a graphical plot of the predicted tide level over the 24 hour span of the current day.

It works pretty much the same as the simple version - go grab the data, parse it, display it. Here we just have more data to deal with and we display it a little fancier.

Let's get the code loaded up and running first...

Add 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_Tides.

Copy the contents of the PyPortal_Tides directory to your PyPortal's CIRCUITPY drive, and then be sure to rename pp_tides_graphical.py to code.py so it will automatically run when the PyPortal restarts.

Editing the Code

At the top of the code, find the line that sets the station ID and change it for your location:

Download: file
STATION_ID = "9447130"   # tide location, find yours here: https://tidesandcurrents.noaa.gov/

Note that it is entered as a string, not a number.

import time
import board
import displayio
from adafruit_pyportal import PyPortal
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text.label import Label

#--| USER CONFIG |--------------------------
STATION_ID = "9447130"   # tide location, find yours here: https://tidesandcurrents.noaa.gov/
PLOT_SIZE = 2            # tide plot thickness
PLOT_COLOR = 0x00FF55    # tide plot color
MARK_SIZE = 6            # current time marker size
MARK_COLOR = 0xFF0000    # current time marker color
DATE_COLOR = 0xE0CD1A    # date text color
TIME_COLOR = 0xE0CD1A    # time text color
VSCALE = 20              # vertical plot scale
#-------------------------------------------

# pylint: disable=line-too-long
DATA_SOURCE = "https://tidesandcurrents.noaa.gov/api/datagetter?date=today&product=predictions&datum=mllw&format=json&units=metric&time_zone=lst_ldt&station="+STATION_ID
DATA_LOCATION = ["predictions"]

WIDTH = board.DISPLAY.width
HEIGHT = board.DISPLAY.height

# determine the current working directory needed so we know where to find files
cwd = ("/"+__file__).rsplit('/', 1)[0]
pyportal = PyPortal(url=DATA_SOURCE,
                    json_path=DATA_LOCATION,
                    status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"/tides_bg_graph.bmp")

# Connect to the internet and get local time
pyportal.get_local_time()

# Setup palette used for plot
palette = displayio.Palette(3)
palette[0] = 0x0
palette[1] = PLOT_COLOR
palette[2] = MARK_COLOR
palette.make_transparent(0)

# Setup tide plot bitmap
tide_plot = displayio.Bitmap(WIDTH, HEIGHT, 3)
pyportal.splash.append(displayio.TileGrid(tide_plot, pixel_shader=palette))

# Setup font used for date and time
date_font = bitmap_font.load_font(cwd+"/fonts/mono-bold-8.bdf")
date_font.load_glyphs(b'1234567890-')

# Setup date label
date_label = Label(date_font, text="0000-00-00", color=DATE_COLOR, x=7, y=14)
pyportal.splash.append(date_label)

# Setup time label
time_label = Label(date_font, text="00:00:00", color=TIME_COLOR, x=234, y=14)
pyportal.splash.append(time_label)

# Setup current time marker
time_marker_bitmap = displayio.Bitmap(MARK_SIZE, MARK_SIZE, 3)
for pixel in range(MARK_SIZE * MARK_SIZE):
    time_marker_bitmap[pixel] = 2
time_marker = displayio.TileGrid(time_marker_bitmap, pixel_shader=palette, x=-MARK_SIZE, y=-MARK_SIZE)
pyportal.splash.append(time_marker)

def get_tide_data():
    """Fetch JSON tide data and return parsed results in a list."""

    # Get raw JSON data
    raw_data = pyportal.fetch()

    # Results will be stored in a list that is display WIDTH long
    new_tide_data = [None]*WIDTH

    # Convert raw data to display coordinates
    for data in raw_data:
        _, t = data["t"].split(" ") # date and time
        h, m = t.split(":")         # hours and minutes
        v = data["v"]               # water level
        x = round( (WIDTH - 1) * (60 * float(h) + float(m)) / 1440 )
        y = (HEIGHT // 2) - round(VSCALE * float(v))
        y = 0 if y < 0 else y
        y = HEIGHT-1 if y >= HEIGHT else y
        new_tide_data[x] = y

    return new_tide_data

def draw_data_point(x, y, size=PLOT_SIZE, color=1):
    """Draw data point on to the tide plot bitmap at (x,y)."""
    if y is None:
        return
    offset = size // 2
    for xx in range(x-offset, x+offset+1):
        for yy in range(y-offset, y+offset+1):
            try:
                tide_plot[xx, yy] = color
            except IndexError:
                pass

def draw_time_marker(time_info):
    """Draw a marker on the tide plot for the current time."""
    h = time_info.tm_hour
    m = time_info.tm_min
    x = round( (WIDTH - 1) * (60 * float(h) + float(m)) / 1440 )
    y = tide_data[x]
    if y is not None:
        x -= MARK_SIZE // 2
        y -= MARK_SIZE // 2
        time_marker.x = x
        time_marker.y = y

def update_display(time_info, update_tides=False):
    """Update the display with current info."""

    # Tide data plot
    if update_tides:
        # out with the old
        for i in range(WIDTH * HEIGHT):
            tide_plot[i] = 0
        # in with the new
        for x in range(WIDTH):
            draw_data_point(x, tide_data[x])

    # Current location marker
    draw_time_marker(time_info)

    # Date and time
    date_label.text = "{:04}-{:02}-{:02}".format(time_info.tm_year,
                                                 time_info.tm_mon,
                                                 time_info.tm_mday)
    time_label.text = "{:02}:{:02}:{:02}".format(time_info.tm_hour,
                                                 time_info.tm_min,
                                                 time_info.tm_sec)

    board.DISPLAY.refresh_soon()

# First run update
tide_data = get_tide_data()
current_time = time.localtime()
update_display(current_time, True)
current_yday = current_time.tm_yday

# Run forever
while True:
    current_time = time.localtime()
    new_tides = False
    if current_time.tm_yday != current_yday:
        # new day, time to update
        tide_data = get_tide_data()
        new_tides = True
        current_yday = current_time.tm_yday
    update_display(current_time, new_tides)
    time.sleep(0.5)

How It Works

This code also does all the data mangling in a single function - get_tide_data(). The general idea is to take the time vs. tide level information and map it into the display's (x, y) coordinates. That way all we have to do is draw pixels at all the (x, y) locations and it will generate a plot.

But first, we go get the data. Same as before:

Download: file
    raw_data = pyportal.fetch()

We store this in a list that has an entry for each x pixel on the display. The index of the list corresponds to the x pixel. The entry itself is the y value. So we know we need as many entries as the display has pixels across, i.e. its WIDTH:

Download: file
    new_tide_data = [None]*WIDTH

And then we loop and parse the data again. We split out the date and time. We further split out the time into hours and minutes, so we can do some math on what will become our x value. The tide level v is what will become our y value. After some math, the results are stored in our list and finally returned.

Download: file
    for data in raw_data:
        _, t = data["t"].split(" ") # date and time
        h, m = t.split(":")         # hours and minutes
        v = data["v"]               # water level
        x = round( (WIDTH - 1) * (60 * float(h) + float(m)) / 1440 )
        y = (HEIGHT // 2) - round(VSCALE * float(v))
        y = 0 if y < 0 else y
        y = HEIGHT-1 if y >= HEIGHT else y
        new_tide_data[x] = y

    return new_tide_data

Let's talk about that math a little more. First, the math for the horizontal or x position:

Download: file
        x = round( (WIDTH - 1) * (60 * float(h) + float(m)) / 1440 )

The display is WIDTH pixels across. A day has 24 hours which is 24*60=1440 total minutes. So there are 1440 minutes per WIDTH pixels. To get the x coordinate for any given minute, we just multiply by that ratio:

x = minutes * (WIDTH / 1440)

That's all that's happening. There's a little more in the code to compute total minutes for hours+minutes time data. And the - 1 is to deal with the 0 based indexing of the x pixels - they start at 0, not 1.

Now the math for the vertical or y position:

Download: file
        y = (HEIGHT // 2) - round(VSCALE * float(v))

We want the vertical plot to vary above/below the middle of the display. So we just compute the middle of display with HEIGHT / 2. From the this we subtract the tide level value v.

y = (HEIGHT / 2) - v

And that's pretty much it.

The extra things being done are to use // instead of / to force integer math, since the y pixel needs to be an integer. We also scale the v value by multiplying by VSCALE, which is just an arbitrary value to make the plot spread out more. We wrap that in round() to also make sure it ends up being an integer.

The other two lines just make sure the bounds are with the actual display values of 0 to HEIGHT-1.

What's That Little Red Mark?

That's the location of the current time on the tide plot. It should move along the plot as the day progresses. If it doesn't show up when you initially run the code, wait a bit. It should eventually show up.

Customizing

Simple Stuff

At the top of each version of the code there is a section with some user changeable settings. It looks like this:

Download: file
#--| USER CONFIG |--------------------------
STATION_ID = "9447130"   # tide location, find yours here: https://tidesandcurrents.noaa.gov/
HI_COLOR   = 0x00FF00    # high tide times color
LO_COLOR   = 0x11FFFF    # low tide times color
DATE_COLOR = 0xFFFFFF    # date and time color
#-------------------------------------------

The most important is the station ID, which sets the location. But there are a few others as well. You can change the color used for the text labels, for example.

Not So Simple Stuff

Most of the graphics used for the tides display were created ahead of time and saved as a BMP image file. These were then simply set to be the background image for the PyPortal and the tide information was added on top of that.

What if you want to change the background image for the tides time display? Or you don't like the blue tinted graph and want to change that? To do so, you will need the source files used for generating the BMP images. These are provided below in SVG format. You can use something like Inkscape to edit these and output new BMP files.

12 Hour Time Format

Not a fan of the 24 hour time format? Wish it could be 12 hour AM/PM instead? The current version of the code does not support this. Only 24 hour time format. This is mainly due to wanting to keep things simple. The times shown are simply what is returned from the NOAA web service, which are strings in a 24 hour time format.

It wouldn't be too difficult to add additional parsing, logic, and math to add this. Most of the work would be in adding some form of AM/PM indication to the display. Doing so would be a fun exercise in learning more about Python and CircuitPython.

This guide was first published on Apr 17, 2019. It was last updated on Apr 17, 2019.