Here is the code from a couple of the examples that are included with the library.

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)

Bitcoin Example

This example, which available in many iterations across many pieces of hardware, is one of Adafruit's classic demos. The version for the MagTag is a barebones, stripped down version that just gets the current 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 single import.

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://api.coindesk.com/v1/bpi/currentprice.json"
DATA_LOCATION = ["bpi", "USD", "rate_float"]

Next, a text transform is defined, which is just a function that accepts and returns a single value. This function just formats the bitcoin value, adds a label, and returns it.

def text_transform(val):
    return "Bitcoin: $%d" % val

The MagTag object is created here. This time, the url and json_path parameters are passed in, which are used in the fetch function further down.

magtag = MagTag(
    url=DATA_SOURCE,
    json_path=DATA_LOCATION,
)

The network access point is then connected.

magtag.network.connect()

The text label is created, but it is being done a little differently here. The center of the display is given as the text_position, a scale of 3 is used like in the previous example, and the text_transform is passed in here.

The text_anchor_point is set here and this tells the library where you want the text_position to be used relative to the text label and expects a tuple with values between 0-1. In this case by passing in 0.5, it tells that we want to use the very center of the label. This makes it very easy to center text.

magtag.add_text(
    text_position=(
        (magtag.graphics.display.width // 2) - 1,
        (magtag.graphics.display.height // 2) - 1,
    ),
    text_scale=3,
    text_transform=text_transform,
    text_anchor_point=(0.5, 0.5),
)

Finally, you may notice that this script does not have a main loop like many other Python scripts. The reason for that is because of the last statement, which we'll explain in a bit.

First a fetch is performed which grabs the bitcoin value, automatically transforms it, and sets it to the label. Second, the exit_and_deep_sleep function is called which tells the script to exit, places the device in a very low power mode, basically just enough for it to keep track of the time to wait, and then it restarts from the beginning. In this case, the device is waiting 60 seconds.

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)

When you run the code, it will connect to your access point, display the Bitcoin value, sleep for 60 seconds and repeat.

Full Example Code

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

# Set up where we'll be fetching data from
DATA_SOURCE = "https://api.coindesk.com/v1/bpi/currentprice.json"
DATA_LOCATION = ["bpi", "USD", "rate_float"]


def text_transform(val):
    return "Bitcoin: $%d" % val


magtag = MagTag(
    url=DATA_SOURCE,
    json_path=DATA_LOCATION,
)

magtag.network.connect()

magtag.add_text(
    text_position=(
        (magtag.graphics.display.width // 2) - 1,
        (magtag.graphics.display.height // 2) - 1,
    ),
    text_scale=3,
    text_transform=text_transform,
    text_anchor_point=(0.5, 0.5),
)

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 Dec 15, 2020.

This page (Code Examples) was last updated on Oct 23, 2021.

Text editor powered by tinymce.