Here is the code from one of the examples that are included with the library. To run the examples, simply rename them as code.py and place them in the root of your CIRCUITPY drive.

Simple Test

This example uses of the top level MagTag layer and makes use of the graphics and peripherals. The code starts out with a couple imports.

import time
from adafruit_magtag.magtag import MagTag

After that, the MagTag library is initialized with no parameters. A NeoPixel could have been supplied for status, but then there would be one less NeoPixel available for programmatic use.

magtag = MagTag()

Next a text label is created with a scale of 3, with the left edge 50 pixels in and centered vertically and it's text is set to Hello World.

magtag.add_text(
    text_position=(
        50,
        (magtag.graphics.display.height // 2) - 1,
    ),
    text_scale=3,
)

magtag.set_text("Hello World")

The button colors and tones are set here and are easy to change.

button_colors = ((255, 0, 0), (255, 150, 0), (0, 255, 255), (180, 0, 255))
button_tones = (1047, 1318, 1568, 2093)

Finally this leads to the main loop. Inside the main loop it will check if each of the buttons has been pressed. If it has, it will print a message about which button, light up the corresponding NeoPixel and then break, which causes it to skip the code inside the else portion of the for loop. After that it will sleep for 0.01 seconds and then repeat.

while True:
    for i, b in enumerate(magtag.peripherals.buttons):
        if not b.value:
            print("Button %c pressed" % chr((ord("A") + i)))
            magtag.peripherals.neopixel_disable = False
            magtag.peripherals.neopixels.fill(button_colors[i])
            magtag.peripherals.play_tone(button_tones[i], 0.25)
            break
    else:
        magtag.peripherals.neopixel_disable = True
    time.sleep(0.01)

After running the code, when you press the buttons, the NeoPixels should light up and each play a different tone.

Full Example Code

# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
import time
from adafruit_magtag.magtag import MagTag

magtag = MagTag()

magtag.add_text(
    text_position=(
        50,
        (magtag.graphics.display.height // 2) - 1,
    ),
    text_scale=3,
)

magtag.set_text("Hello World")

button_colors = ((255, 0, 0), (255, 150, 0), (0, 255, 255), (180, 0, 255))
button_tones = (1047, 1318, 1568, 2093)

while True:
    for i, b in enumerate(magtag.peripherals.buttons):
        if not b.value:
            print("Button %c pressed" % chr((ord("A") + i)))
            magtag.peripherals.neopixel_disable = False
            magtag.peripherals.neopixels.fill(button_colors[i])
            magtag.peripherals.play_tone(button_tones[i], 0.25)
            break
    else:
        magtag.peripherals.neopixel_disable = True
    time.sleep(0.01)

Quotes Example

This example is a barebones stripped down version of the MagTag Showerthoughts and Quotes example that just gets the value, displays it, and then makes use of the deep sleep feature. This example also uses the MagTag top layer, but makes use of the graphics and network, but not the peripherals.

The code starts out with a couple imports:

import os
from adafruit_magtag.magtag import MagTag

Then it defines where to grab the value from and the path to find the result in the JSON response.

# Set up where we'll be fetching data from
DATA_SOURCE = "https://www.adafruit.com/api/quotes.php"
QUOTE_LOCATION = [0, "text"]
AUTHOR_LOCATION = [0, "author"]

Next the MagTag library is initialized at the top level. The Data URL, Data Location within the returned JSON, and Default Background are set here. The json_path has a tuple of 2 values because we are fetching 2 pieces of data.

magtag = MagTag(
    url=DATA_SOURCE,
    json_path=(QUOTE_LOCATION, AUTHOR_LOCATION),
    default_bg=0x000000,
)

Next we define a couple of text transform function. A text transform works by modifying a single parameter and returning the new value.

def add_quote_marks(quote_text):
    return f'"{quote_text}"'


def add_hyphen(author_name):
    return f"- {author_name}"

Next we add a couple of text fields. The order they are added should match the order of the items in the json_path parameter we used when initializing the MagTag library.

magtag.add_text(
    text_position=(
        (magtag.graphics.display.width // 2) - 1,
        (magtag.graphics.display.height // 2) - 20,
    ),
    text_color=0xFFFFFF,
    text_wrap=44,
    text_maxlen=180,
    line_spacing=1.0,
    text_transform=add_quote_marks,
    text_anchor_point=(0.5, 0.5),
)

magtag.add_text(
    text_position=(
        (magtag.graphics.display.width // 2) - 120,
        (magtag.graphics.display.height // 2) + 34,
    ),
    text_color=0xFFFFFF,
    text_wrap=0,
    text_maxlen=30,
    text_transform=add_hyphen,
)

Next we fetch the data and the text fields are automatically filled in. That is why the order they are added must match the order of the data locations.

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

Finally, the MagTag is put into deep sleep for 60 seconds. When it wakes up, the script starts from the beginning.

magtag.exit_and_deep_sleep(60)

After running the code, it should connect to your WiFi and download and display a quote.

Full Example Code

# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
import os
from adafruit_magtag.magtag import MagTag

# Set up where we'll be fetching data from
DATA_SOURCE = "https://www.adafruit.com/api/quotes.php"
QUOTE_LOCATION = [0, "text"]
AUTHOR_LOCATION = [0, "author"]

# the current working directory (where this file is)
try:
    cwd = os.path.dirname(os.path.realpath(__file__))
except AttributeError:
    cwd = ("/" + __file__).rsplit("/", 1)[0]

magtag = MagTag(
    url=DATA_SOURCE,
    json_path=(QUOTE_LOCATION, AUTHOR_LOCATION),
    default_bg=0x000000,
)


def add_quote_marks(quote_text):
    return f'"{quote_text}"'


def add_hyphen(author_name):
    return f"- {author_name}"


magtag.add_text(
    text_position=(
        (magtag.graphics.display.width // 2) - 1,
        (magtag.graphics.display.height // 2) - 20,
    ),
    text_color=0xFFFFFF,
    text_wrap=44,
    text_maxlen=180,
    line_spacing=1.0,
    text_transform=add_quote_marks,
    text_anchor_point=(0.5, 0.5),
)

magtag.add_text(
    text_position=(
        (magtag.graphics.display.width // 2) - 120,
        (magtag.graphics.display.height // 2) + 34,
    ),
    text_color=0xFFFFFF,
    text_wrap=0,
    text_maxlen=30,
    text_transform=add_hyphen,
)

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

This guide was first published on Dec 15, 2020. It was last updated on Nov 30, 2023.

This page (Code Examples) was last updated on Nov 30, 2023.

Text editor powered by tinymce.