CircuitPython Code

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

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

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

The Wordnik API

Wordnik is where we'll be grabbing our word of the day data from to display on the PyPortal.

A bit about Wordnik from their website:

Wordnik is the world's biggest online English dictionary, by number of words.

Wordnik is a 501(c)(3) nonprofit organization, and our mission is to find and share as many words of English as possible with as many people as possible.

In order to use Wordnik's API and access their word data, we will need what's called an API key.

The Wordnik API has a one week waiting period for free API keys

How to obtain an API key from Wordnik

To get an API key first make an account on the Wordnik website by clicking here.

  • Next, head here to sign up for an API key.
  • If you donate $5 or more you can get the API key the same day.
  • You can also get a key for free but will have to wait one week to get it.

Using the API key

After you've gotten your key from Wordnik in your email, it's time to add it to your secrets file!

Here's how to enter the key into your secrets.py file.

secrets = {
	'ssid' : '_your_wifi_ssid_',
	'password' : '_your_wifi_password_',
	'wordnik_token' : 'HUGE_LONG_WORDNIK_API_KEY'
}
# SPDX-FileCopyrightText: 2019 Isaac Wellish for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""
This example uses the Wordnik API to display Wordnik's Word of the Day.
Each day a new word, its part of speech, and definition
will appear automatically on the display. Tap the screen to start
as well as to switch between the word's definition and an example sentence.
"""

import board
from adafruit_pyportal import PyPortal

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

# Set up where we'll be fetching data from
DATA_SOURCE = "https://api.wordnik.com/v4/words.json/wordOfTheDay?api_key="+secrets['wordnik_token']
PART_OF_SPEECH = ['definitions', 0, 'partOfSpeech']
DEF_LOCATION = ['definitions', 0, 'text']
EXAMPLE_LOCATION = ['examples', 0, 'text']
CAPTION = 'wordnik.com/word-of-the-day'
DEFINITION_EXAMPLE_ARR = [DEF_LOCATION, EXAMPLE_LOCATION]
#defintion and example array variable initialized at 0
definition_example = 0

# 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(url=DATA_SOURCE,
                    status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"/wordoftheday_background.bmp",
                    text_font=cwd+"/fonts/Arial-ItalicMT-17.bdf",
                    text_position=((50, 30),  # word location
                                   (50, 50), # part of speech location
                                   (50, 135)), # definition location
                    text_color=(0x8080FF,
                                0xFF00FF,
                                0xFFFFFF),
                    text_wrap=(0, # characters to wrap for text
                               0,
                               28),
                    text_maxlen=(180, 30, 115), # max text size for word, part of speech and def
                    caption_text=CAPTION,
                    caption_font=cwd+"/fonts/Arial-ItalicMT-17.bdf",
                    caption_position=(50, 220),
                    caption_color=0x808080)

print("loading...") # print to repl while waiting for font to load
pyportal.preload_font() # speed things up by preloading font
pyportal.set_text("\nWord of the Day") # show title

while True:
    if pyportal.touchscreen.touch_point:
        try:
            #set the JSON path here to be able to change between definition and example
            # pylint: disable=protected-access
            pyportal._json_path=(['word'],
                                 PART_OF_SPEECH,
                                 DEFINITION_EXAMPLE_ARR[definition_example])
            value = pyportal.fetch()
            print("Response is", value)
        except RuntimeError as e:
            print("Some error occured, retrying! -", e)
        #Change between definition and example
        if definition_example == 0:
            definition_example = 1
        elif definition_example == 1:
            definition_example = 0
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!

Title Sequence

When the PyPortal is turned on or reset, the following events occur.

  • Display the title of the app, "Word of the Day" at the top of the display and the source "Wordnik.com/wordoftheday" at the bottom
  • When screen is touched, display the word, part of speech, and definition with the source at the bottom.
  • When screen is touched again, display the word, part of speech, and an example sentence with the word. 

How It Works

The PyPortal Word of the Day is doing a couple of nifty things to deliver your insightful vocabulary expanding experience!

Background

First, it displays a bitmap graphic as the screen's background. This is a 320 x 240 pixel RGB 16-bit raster graphic in .bmp format. I found this image on Pixabay by user Clker-Free-Vector-Images and turned it into a black and white scroll for ultimate word of the day background!

Font

First we see "Word of the Day" appear on the screen along with the source at the bottom.

The fonts used here are bitmap fonts made from the Arial Italic typeface. You can learn more about converting type in this guide.

Parsing JSON from the Web

The neat part is that the text is not coming from a file on the device, but rather it is grabbed from a website!

From the Wordnik API's documentation for the word of the day, click the "Try it out!"  button.

  • A link can be found in the Request URL section. 
  • Try copy and pasting the below link into your browser and replace "YOURAPIKEY" with key you were given form Wordnik. 
  • When this link is entered into a browser the JSON data for that word shows up!

https://api.wordnik.com/v4/words.json/wordOfTheDay?api_key=YOURAPIKEY

You may see a large mess of numbers, letters and symbols. This is JSON data!

Head here to beautify the code so we can actually read it!

"Beautified" code:

{
  "_id": "5cab62b93cc5c96eb3afa5bf",
  "word": "adiaphoron",
  "contentProvider": {
    "name": "wordnik",
    "id": 711
  },
  "definitions": [
    {
      "source": "wiktionary",
      "text": "An indifferent matter.",
      "note": null,
      "partOfSpeech": "noun"
    },
    {
      "source": "wiktionary",
      "text": "A matter that is morally neutral.",
      "note": null,
      "partOfSpeech": "noun"
    },
    {
      "source": "wiktionary",
      "text": "Something neither forbidden nor commanded by scripture.",
      "note": null,
      "partOfSpeech": "noun"
    },
    {
      "source": "century",
      "text": "In theology and ethics, a thing indifferent; a tenet or practice which may be considered non-essential.",
      "note": null,
      "partOfSpeech": "noun"
    }
  ],
  "publishDate": "2019-04-12T03:00:00.000Z",
  "examples": [
    {
      "url": "http://api.wordnik.com/v4/mid/e1284319bcc8eed2b40528c240f6d69376b90187bd37ec0240e9907527a238de12ff8f433fbda52a4181ae99f4ade604",
      "title": "Historical Introductions to the Symbolical Books of the Evangelical Lutheran Church",
      "text": "For if the condition is good, the adiaphoron, too, is good, and its observance is commanded.",
      "id": 1090967175
    },
    {
      "url": "http://api.wordnik.com/v4/mid/6542bbb01a6a8314704c23814788a11d6197fd480404393c5fbd590e84fe27d6ad9ae69016e66722bfa1d945c00d2a61",
      "title": "Apology of the Augsburg Confession",
      "text": "For Augustine, in a long discussion refutes the opinion of those who thought that concupiscence in man is not a fault but an adiaphoron, as color of the body or ill health is said to be an adiaphoron [as to have a black or a white body is neither good nor evil].",
      "id": 1158602656
    }
  ],
  "pdd": "2019-04-12",
  "note": "The word 'adiaphoron' comes from a Greek word meaning 'indifferent'.",
  "htmlExtra": null
}

If we look through the JSON file, we'll see a key called word, and two others called definitions and examples each with a sub-tree below it hierarchically called 0 . Within the definitions key we see the two key value pairs that we want: text that has the contents of the word's definition, "An indifferent matter" and "partOfSpeech" with the contents of "noun". In the examples key we want text which has the contents of "For if the condition is good, the adiaphoron, too, is good, and its observance is commanded."

The raw JSON for these key : value pairs look like this:

  1. "word": "adiaphoron"
    "text": "An indifferent matter"
    "partOfSpeech": "noun"
    "text": "For if the condition is good, the adiaphoron, too, is good, and its observance is commanded."

Our CircuitPython code is able to grab and parse this data using these variables:

PART_OF_SPEECH = ['definitions', 0, 'partOfSpeech']
DEF_LOCATION = ['definitions', 0, 'text']
EXAMPLE_LOCATION = ['examples', 0, 'text']

*word data is called directly in the while loop

Parsing local JSON files 

If you would like to avoid pulling data from a web page or maybe you don't feel like waiting for an API key, you can use a "local" JSON file to pull data from.

To implement this local data sourcing method, create a new file and name it local.txt. Populate this file with the JSON data that you would like to use. For example, you could use the JSON data provided above and make sure the format of the data is the same. Save this file on the CIRCUITPY drive in the root. 

You should not need to change anything in your code.

And that's it! The JSON data will now be pulled from this local file!

PyPortal Constructor

When we set up the pyportal constructor, we are providing it with these things:

  • url to query
  • json_path to traverse and find the key:value pair we need
  • status_neopixel pin
  • default_bg path and name to display the background bitmap
  • text_font path and name to the font used for displaying the follower count value
  • text_position on the screen's x/y coordinate system
  • text_color
  • caption_text to display statically -- in this case the name of the repo
  • caption_font
  • caption_position
  • caption_color

Fetch

With the pyportal set up, we can then use pyportal.fetch() to do the query and parsing of the three pieces of Wordnik data and then display them on screen along with the caption text on top of the background image.

Customization

You can customize this project to make it your own and point to different website APIs as the source of your JSON data, as well as adjust the graphics and text.

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. You can do this with the text_positionand caption_position options.

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 Word of the Day is to adjust the color of the text. The line text_color=0xFFFFFF in the constructor shows how. You will need to use the hexidecimal 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

Background Image

If you would like to create your own background, awesome! You'll want to save the file with these specifications:

  • 320 x 240 pixels
  • 16-bit RGB color
  • Save file as .bmp format

You can then copy the .bmp file to the root level of the CIRCUITPY drive. Make sure you refer to this new filename in the pyportal constructor line:

default_bg=cwd+ "/wordoftheday_background.bmp"

Change that line to use the new filename name, such as:

default_bg=cwd+"/my_new_background.bmp"

Main loop

while True:

In the repeating main loop, the following actions are performed:

  1. Check to see if the screen was touched
  2. If screen was touched, display the word, part of speech, and definition with the source at the bottom.
  3. If the screen was touched again, display the word, part of speech, and an example sentence with the word. 
  4. Any further screen touches will continue to switch between displaying the word's definition and example.

Going Further

How can the app be modified to give even more knowledge on the words?

The Wordnik API has many more features including:

  • Audio pronunciations
  • Hyphenations
  • Scrabble scores

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

This page (Code PyPortal with CircuitPython) was last updated on May 10, 2023.

Text editor powered by tinymce.