Bitcoin Value Display

Bitcoin Value

With the PyPortal running CircuitPython code, we can have the PyPortal display the current value of Bitcoin according to the coindesk.com API.

The PyPortal Bitcoin Display will do the following:

  • Display a custom background .bmp
  • Determine the current value of Bitcoin using the WiFi connection to the Internet
  • Display the current Bitcoin value converted into USD, Euros, or GBP.

Install CircuitPython Code and Assets

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

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

Copy the contents of the PyPortal_Bitcoin directory to your PyPortal's CIRCUITPY drive, and then be sure to rename the bitcoin.py file to code.py so it will automatically run when the PyPortal re-starts.

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

"""
This example will access the coindesk API, grab a number like bitcoin value in
USD 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

# You can display in 'GBP', 'EUR' or 'USD'
CURRENCY = 'USD'
# Set up where we'll be fetching data from
DATA_SOURCE = "https://api.coindesk.com/v1/bpi/currentprice.json"
DATA_LOCATION = ['bpi', CURRENCY, 'rate_float']

def text_transform(val):
    if CURRENCY == 'USD':
        return "$%d" % val
    if CURRENCY == 'EUR':
        return "‎€%d" % val
    if CURRENCY == 'GBP':
        return "£%d" % val
    return "%d" % val

# the current working directory (where this file is)
cwd = ("/"+__file__).rsplit('/', 1)[0]
pyportal = PyPortal(url=DATA_SOURCE, json_path=DATA_LOCATION,
                    status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"/bitcoin_background.bmp",
                    text_font=cwd+"/fonts/Arial-Bold-24-Complete.bdf",
                    text_position=(195, 130),
                    text_color=0x0,
                    text_transform=text_transform)
pyportal.preload_font(b'$012345789')  # preload numbers
pyportal.preload_font((0x00A3, 0x20AC)) # preload gbp/euro symbol

while True:
    try:
        value = pyportal.fetch()
        print("Response is", value)
    except (ValueError, RuntimeError) as e:
        print("Some error occured, retrying! -", e)

    time.sleep(3*60)  # wait 3 minutes
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 Bitcoin Display is doing the following things;

Background

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

Font

To display information on the screen, the PyPortal code will use a  bitmapped font overlayed on top of the background. The font used here is are bitmap fonts made from the Arial typeface. You can learn more about converting type in this guide.

In order to speed up the display of text, the pyportal.preload_font() command is used to place the needed glyphs into memory.

JSON

So how does the PyPortal Bitcoin Display actually stay up to date with the current value of Bitcoin? By fetching the currentprice.json JSON file from the coindesk.com website's API!

Coindesk generates a JSON file with the current value of Bitcoin at the address https://api.coindesk.com/v1/bpi/currentprice.json

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:

Download: file
{
  "time": {
    "updated": "Mar 26, 2019 14:55:00 UTC",
    "updatedISO": "2019-03-26T14:55:00+00:00",
    "updateduk": "Mar 26, 2019 at 14:55 GMT"
  },
  "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
  "chartName": "Bitcoin",
  "bpi": {
    "USD": {
      "code": "USD",
      "symbol": "$",
      "rate": "3,930.3000",
      "description": "United States Dollar",
      "rate_float": 3930.3
    },
    "GBP": {
      "code": "GBP",
      "symbol": "£",
      "rate": "2,972.8750",
      "description": "British Pound Sterling",
      "rate_float": 2972.875
    },
    "EUR": {
      "code": "EUR",
      "symbol": "€",
      "rate": "3,482.6035",
      "description": "Euro",
      "rate_float": 3482.6035
    }
  }
}

Keys

If we look a bit further down the JSON page, we'll see a key called bpi that has three sub-trees, USD, GBP, and EUR. Each of those, in turn, have their own sub-trees with five keys: code, symbol, rate, description, and rate_float

The raw JSON for one of the rate_float key : value pairs looks like this: "rate_float": 3930.3

Our CircuitPython code is able to grab and parse this data using these variables, where the CURRENCY value is used to choose from the three currency sub-trees:

Download: file
CURRENCY = 'USD'
DATA_SOURCE = "https://api.coindesk.com/v1/bpi/currentprice.json"
DATA_LOCATION = ['bpi', CURRENCY, 'rate_float']

Traversing JSON

The DATA_LOCATION contains three values 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 bpi(Bitcoin Price Index) key is at the top level of the file's hierarchy, so we can call its name first, followed by the CURRENCY key which is USD in this case (you can change to EUR or GBP if you like). Finally, we specify the rate_float key and get for the value of it, in this case 3930.3.

You can see this more clearly by switching to the "Form" view of the code beautifier.

Our DATA_LOCATION, therefore, is:

["bpi", "USD", "rate_float"]

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
  • text_transform this is used to format the text string, in this case by adding the currency symbol in front of the chosen currency for US dollars $ , Euros € , or GB pounds £.

Fetch

With the PyPortal set up, we can then use pyportal.fetch() to do the query and parsing of the data and then display it on screen on top of the background image.

This repeats every three minutes to stay current!

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

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 (8-bits per channel)
  • 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+"/bitcoin_background.bmp"

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

default_bg=cwd+"/my_new_background.bmp"

This guide was first published on Mar 26, 2019. It was last updated on Mar 26, 2019. This page ( Bitcoin Value Display) was last updated on Sep 22, 2019.