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

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

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

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

"""
This example will access the twitter follow button API, grab a number like
the number of followers... and display it on a screen!
if you can find something that spits out JSON data, we can display it
"""
import time
import board
from adafruit_pyportal import PyPortal

# Change this to your twitter username!
TWITTER_NAME = "adafruit"

# Set up where we'll be fetching data from
DATA_SOURCE = "https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names="+TWITTER_NAME   # pylint: disable=line-too-long
DATA_LOCATION = [0, "followers_count"]

# the current working directory (where this file is)
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,
                    json_path=DATA_LOCATION,
                    status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"/twitter_background.bmp",
                    text_font=cwd+"/fonts/Collegiate-50.bdf",
                    text_position=(165, 140),
                    text_color=0xFFFFFF,
                    caption_text="www.twitter.com/"+TWITTER_NAME,
                    caption_font=cwd+"/fonts/Collegiate-24.bdf",
                    caption_position=(50, 200),
                    caption_color=0xFFFFFF,)

# track the last value so we can play a sound when it updates
last_value = 0

while True:
    try:
        value = pyportal.fetch()
        print("Response is", value)
        if last_value < value:  # ooh it went up!
            print("New follower!")
            pyportal.play_file(cwd+"/coin.wav")  # uncomment make a noise!
        last_value = value
    except (ValueError, RuntimeError, ConnectionError, OSError) as e:
        print("Some error occured, retrying! -", e)

    time.sleep(60)  # wait a minute before getting again
If you run into any errors, such as "ImportError: no module named `adafruit_display_text.label`" be sure to update your libraries to the latest release bundle!

How It Works

The PyPortal Stats Trophy is doing a couple of neat-o things to provide for your stats-tastic display needs!

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.

Font

Then, it displays the Twitter account's name as a caption, created with bitmapped fonts to overlay on top of the background. The fonts used here is are bitmap fonts made from the Collegiate typeface. You can learn more about converting type in this guide.

Next, the PyPortal will display the current number of Followers for the account.

JSON

To keep things current, the follower count is grabbed from the website itself.

Twitter automatically generates a JSON file for each account, in this case at the address https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names=adafruit

This file contains all sorts of information, delivered in an easy-to-parse format. If you visit that URL by copying the address and pasting it into the Load Url button of the online code "beautifier" https://codebeautify.org/jsonviewer you'll see the raw JSON file next to a nicely formatted version of it (choose "View" from the dropdown menu in the right hand box to change the display format).

Here it is in a raw-er form, but still using indentation and carriage returns to make it readable:

[
  {
    "following": false,
    "id": "20731304",
    "screen_name": "adafruit",
    "name": "adafruit industries",
    "protected": false,
    "followers_count": 157262,
    "formatted_followers_count": "157K followers",
    "age_gated": false
  }
]

Keys

If we look a bit further down the JSON page, we'll see a key called followers_count that has a value of 157262. The raw JSON for this key : value pair looks like this: "followers_count": 157262

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

TWITTER_NAME = "adafruit"
DATA_SOURCE = "https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names="+TWITTER_NAME   # pylint: disable=line-too-long
DATA_LOCATION = [0, "followers_count"]

Traversing JSON

The DATA_LOCATION contains a value that we use to traverse the JSON file. In the image above, note how there is a tree hierarchy indicated by the indentation level. The followers_count key is one set of brackets indented from the top level of the file's hierarchy, so we can call it the child of the first index of the array, which is 0. You can see this more clearly by switching to the "Form" view of the code beautifier as seen below:

Our DATA_LOCATION, therefore, is [0, "followers_count"].

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
  • 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 Twitter data and then display it on screen along with the caption text on top of the background image.

Ba-Ding!

Additionally, we use the last_value variable's state to compare against the latest value. If they differ, we play the coin.wav file for a satisfying ding over the PyPortal's built in speaker!

To make your own .wav files, check out this guide.

Customization

You can customize this project to make it your own and point to different website API's 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_position and 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).

So, if you wanted to move the subscriber count text to the right and up closer to the top, your code may look like this for that part of the pyportal constructor: text_position=(250, 10)

Text Color

Another way to customize your stats trophy 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+"/twitter_background.bmp"

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

default_bg=cwd+"/my_new_background.bmp"

Now, we'll look at mounting the PyPortal onto a trophy for display!

This guide was first published on Mar 01, 2019. It was last updated on Nov 21, 2023.

This page (Code PyPortal with CircuitPython) was last updated on Nov 21, 2023.

Text editor powered by tinymce.