Overview
Bring some Zen to your life with this MagTag Haiku Viewer. Load your favorite haikus in a local text file, or use an AdafruitIO feed for easy remote management capabilities. When the MagTag boots up, a random haiku is selected and shown. The right and left buttons cycle through all of the available haikus forward and backwards respectively. The D12 button selects a new haiku to show at random.
Are haikus not your vibe? No problem, the code for this project can be easily repurposed to show jokes, quotes, or anything else you like.
Page last edited January 26, 2026
Install CircuitPython
CircuitPython is a derivative of MicroPython designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the CIRCUITPY drive to iterate.
Click the link above and download the latest .BIN and .UF2 file
You can use a 9.x.x release for a pre-2025 MagTag. You must use a 10.x.x release for the updated MagTag 2025 Edition.
(depending on how you program the ESP32S2 board you may need one or the other, might as well get both)
Download and save it to your desktop (or wherever is handy).
Plug your MagTag into your computer using a known-good USB cable.
A lot of people end up using charge-only USB cables and it is very frustrating! So make sure you have a USB cable you know is good for data sync.
Option 1 - Load with UF2 Bootloader
This is by far the easiest way to load CircuitPython. However it requires your board has the UF2 bootloader installed. Some early boards do not (we hadn't written UF2 yet!) - in which case you can load using the built in ROM bootloader.
Still, try this first!
Try Launching UF2 Bootloader
Loading CircuitPython by drag-n-drop UF2 bootloader is the easier way and we recommend it. If you have a MagTag where the front of the board is black, your MagTag came with UF2 already on it.
Launch UF2 by double-clicking the Reset button (the one next to the USB C port). You may have to try a few times to get the timing right.
If you're using Windows and you get an error at the end of the file copy that says Error from the file copy, Error 0x800701B1: A device which does not exist was specified. You can ignore this error, the bootloader sometimes disconnects without telling Windows, the install completed just fine and you can continue. If its really annoying, you can also upgrade the bootloader (the latest version of the UF2 bootloader fixes this warning)
Your board should auto-reset into CircuitPython, or you may need to press reset. A CIRCUITPY drive will appear. You're done! Go to the next pages.
Option 2 - Use esptool to load BIN file
If you have an original MagTag with while soldermask on the front, we didn't have UF2 written for the ESP32S2 yet so it will not come with the UF2 bootloader.
You can upload with esptool to the ROM (hardware) bootloader instead!
Follow the initial steps found in the Run esptool and check connection section of the ROM Bootloader page to verify your environment is set up, your board is successfully connected, and which port it's using.
In the final command to write a binary file to the board, replace the port with your port, and replace "firmware.bin" with the the file you downloaded above.
The output should look something like the output in the image.
Press reset to exit the bootloader.
Your CIRCUITPY drive should appear!
You're all set! Go to the next pages.
Option 3 - Use Chrome Browser To Upload BIN file
If for some reason you cannot get esptool to run, you can always try using the Chrome-browser version of esptool we have written. This is handy if you don't have Python on your computer, or something is really weird with your setup that makes esptool not run (which happens sometimes and isn't worth debugging!) You can follow along on the Web Serial ESPTool page and either load the UF2 bootloader and then come back to Option 1 on this page, or you can download the CircuitPython BIN file directly using the tool in the same manner as the bootloader.
Page last edited January 26, 2026
Create Your settings.toml File
CircuitPython works with WiFi-capable boards to enable you to make projects that have network connectivity. This means working with various passwords and API keys. As of CircuitPython 8, there is support for a settings.toml file. This is a file that is stored on your CIRCUITPY drive, that contains all of your secret network information, such as your SSID, SSID password and any API keys for IoT services. It is designed to separate your sensitive information from your code.py file so you are able to share your code without sharing your credentials.
CircuitPython previously used a secrets.py file for this purpose. The settings.toml file is quite similar.
CircuitPython settings.toml File
This section will provide a couple of examples of what your settings.toml file should look like, specifically for CircuitPython WiFi projects in general.
The most minimal settings.toml file must contain your WiFi SSID and password, as that is the minimum required to connect to WiFi. Copy this example, paste it into your settings.toml, and update:
your_wifi_ssidyour_wifi_password
CIRCUITPY_WIFI_SSID = "your_wifi_ssid" CIRCUITPY_WIFI_PASSWORD = "your_wifi_password"
Many CircuitPython network-connected projects on the Adafruit Learn System involve using Adafruit IO. For these projects, you must also include your Adafruit IO username and key. Copy the following example, paste it into your settings.toml file, and update:
your_wifi_ssidyour_wifi_passwordyour_aio_usernameyour_aio_key
CIRCUITPY_WIFI_SSID = "your_wifi_ssid" CIRCUITPY_WIFI_PASSWORD = "your_wifi_password" ADAFRUIT_AIO_USERNAME = "your_aio_username" ADAFRUIT_AIO_KEY = "your_aio_key"
Some projects use different variable names for the entries in the settings.toml file. For example, a project might use ADAFRUIT_AIO_ID in the place of ADAFRUIT_AIO_USERNAME. If you run into connectivity issues, one of the first things to check is that the names in the settings.toml file match the names in the code.
Here is an example settings.toml file.
# Comments are supported CIRCUITPY_WIFI_SSID = "guest wifi" CIRCUITPY_WIFI_PASSWORD = "guessable" CIRCUITPY_WEB_API_PORT = 80 CIRCUITPY_WEB_API_PASSWORD = "passw0rd" test_variable = "this is a test" thumbs_up = "\U0001f44d"
In a settings.toml file, it's important to keep these factors in mind:
- Strings are wrapped in double quotes; ex:
"your-string-here" - Integers are not quoted and may be written in decimal with optional sign (
+1,-1,1000) or hexadecimal (0xabcd).- Floats (decimal numbers), octal (
0o567) and binary (0b11011) are not supported.
- Floats (decimal numbers), octal (
- Use
\uescapes for weird characters,\xand\oooescapes are not available in .toml files- Example:
\U0001f44dfor 👍 (thumbs up emoji) and\u20acfor € (EUR sign)
- Example:
- Unicode emoji, and non-ASCII characters, stand for themselves as long as you're careful to save in "UTF-8 without BOM" format
When your settings.toml file is ready, you can save it in your text editor with the .toml extension.
In your code.py file, you'll need to import the os library to access the settings.toml file. Your settings are accessed with the os.getenv() function. You'll pass your settings entry to the function to import it into the code.py file.
import os
print(os.getenv("test_variable"))
In the upcoming CircuitPython WiFi examples, you'll see how the settings.toml file is used for connecting to your SSID and accessing your API keys.
Page last edited January 26, 2026
Code
Getting the Program's Files
To use the application, you need to obtain code.py with the program, the bamboo.bmp image file, and optionally the haikus.txt data file to place on the MagTag CIRCUITPY drive.
Thankfully, this can be done in one go. In the example below, click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file.
Connect your board to your computer via a known good data+power USB cable. The board should show up in your File Explorer/Finder (depending on your operating system) as a flash drive named CIRCUITPY.
Extract the contents of the zip file, copy the lib directory files to CIRCUITPY/lib. Copy the code.py, haikus.txt, and bamboo.bmp file to the CIRCUITPY drive on the MagTag via your computer. The program should self start.
Drive Structure
After copying the files, your drive should look like the listing below. It can contain other files as well, but must contain these at a minimum.
# SPDX-FileCopyrightText: 2025 Tim C, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
MagTag Haiku Viewer
Displays haikus loaded from the haikus.txt file and/or the
AdafruitIO feed 'haikus'. Press left and right buttons to
cycle through the avialble haikus. Press the D12 button
to change to a new random haiku.
"""
import os
import random
import time
import bitmaptools
import board
import digitalio
import displayio
import supervisor
import wifi
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError
from adafruit_bitmap_font import bitmap_font
import adafruit_connection_manager
from adafruit_debouncer import Debouncer
from adafruit_display_text.bitmap_label import Label
import adafruit_imageload
import adafruit_requests
# AdafruitIO connection. Will stay None if no WIFI or AIO credentials in settings.toml
io = None
# list of all haikus collected from the local file and
# ones pulled from 'haikus' feed on Adafruit IO
all_haikus = []
# If the WIFI is auto connected from web workflow
if wifi.radio.connected:
# Check for AdafruitIO credentials in settings.toml
aio_username = os.getenv("ADAFRUIT_AIO_USERNAME")
aio_key = os.getenv("ADAFRUIT_AIO_KEY")
# if there are AIO credentials
if None not in {aio_username, aio_key}:
# Initialize connection_manager and requests
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
requests = adafruit_requests.Session(pool, ssl_context)
# Initialize an Adafruit IO HTTP API object
io = IO_HTTP(aio_username, aio_key, requests)
# if the AdafruitIO connection is active
if io is not None:
try:
# Connect to the haikus IO feed
haiku_feed = io.get_feed("haikus")
# Retrieve data value from the feed
print("Retrieving data from haiku feed...")
haikus_data_from_io = io.receive_all_data(haiku_feed["key"])
# add the fetched haikus to the list
for haiku_data in haikus_data_from_io:
# replace escaped double slash newlines with single slash newline
all_haikus.append(haiku_data["value"].replace("\\n", "\n"))
except AdafruitIO_RequestError as re:
print("No haikus feed found on AdafruitIO. Using local haikus.txt file only.")
# attempt to load hakus from local file
try:
with open("haikus.txt", "r") as f:
haiku_txt_file_content = f.read()
# add all the haikus from the file to the list
for haiku in haiku_txt_file_content.split("\n\n"):
all_haikus.append(haiku)
except OSError as e:
print("No haikus.txt file found.")
# make sure there is at least one haiku to show
if len(all_haikus) == 0:
raise ValueError(
"\nNo haikus were found.\nPlease add haikus to IO\nor the haikus file."
)
print(f"Choosing from {len(all_haikus)} haikus")
# index of haiku to show. start on a random one
current_index = random.randint(0, len(all_haikus) - 1)
# get the selected haiku from the list
haiku = all_haikus[current_index]
# variable to hold the built-in eInk display reference
display = supervisor.runtime.display
# main group to hold all other visual elements
main_group = displayio.Group()
# background group used for white background behind the quote
# scale 8x to save memory on the Bitmap
bg_group = displayio.Group(scale=8)
# Create & append Bitmap for the white background
bg_bmp = displayio.Bitmap(display.width // 8, display.height // 8, 1)
bg_palette = displayio.Palette(1)
bg_palette[0] = 0xFFFFFF
bg_tg = displayio.TileGrid(bg_bmp, pixel_shader=bg_palette)
bg_group.append(bg_tg)
main_group.append(bg_group)
# Bamboo image element across the bottom
bamboo_bmp, bamboo_palette = adafruit_imageload.load("bamboo.bmp")
bamboo_tg = displayio.TileGrid(bitmap=bamboo_bmp, pixel_shader=bamboo_palette)
bamboo_tg.y = display.height - bamboo_tg.tile_height - 5
main_group.append(bamboo_tg)
# Grey border around the edges of the display
border_group = displayio.Group(scale=4)
border_bmp = displayio.Bitmap(display.width // 4, display.height // 4, 1)
border_palette = displayio.Palette(2)
border_palette[0] = 0x999999
border_palette[1] = 0xFFFFFF
border_palette.make_transparent(1)
bitmaptools.fill_region(
border_bmp, 1, 1, border_bmp.width - 1, border_bmp.height - 1, 1
)
border_tg = displayio.TileGrid(border_bmp, pixel_shader=border_palette)
border_group.append(border_tg)
main_group.append(border_group)
# load the custom font & initialze Label to show haiku
FONT = bitmap_font.load_font("fanwood_webfont_15.bdf", displayio.Bitmap)
haiku_lbl = Label(FONT, text=haiku, scale=1, color=0x333333, line_spacing=1.0)
haiku_lbl.anchor_point = (0, 0)
haiku_lbl.anchored_position = (8, 0)
main_group.append(haiku_lbl)
# set up left button pin and debouncer
left_btn_pin = digitalio.DigitalInOut(board.D15)
left_btn_pin.direction = digitalio.Direction.INPUT
left_btn_pin.pull = digitalio.Pull.UP
left_btn = Debouncer(left_btn_pin)
# set up right button pin and debouncer
right_btn_pin = digitalio.DigitalInOut(board.D11)
right_btn_pin.direction = digitalio.Direction.INPUT
right_btn_pin.pull = digitalio.Pull.UP
right_btn = Debouncer(right_btn_pin)
# setup D12 button and debouncer
random_btn_pin = digitalio.DigitalInOut(board.D12)
random_btn_pin.direction = digitalio.Direction.INPUT
random_btn_pin.pull = digitalio.Pull.UP
random_btn = Debouncer(random_btn_pin)
# set main_group as root_group to show on the display
display.root_group = main_group
def refresh_display():
"""
Wait until the display is ready to refresh,
and then call refresh() on it.
:return:
"""
time.sleep(display.time_to_refresh)
display.refresh()
# initial refresh to show the first haiku
refresh_display()
# main loop
while True:
# update the button debouncers
right_btn.update()
left_btn.update()
random_btn.update()
# if the right button was pressed
if right_btn.fell:
print("right button pressed")
# increment the current index
current_index += 1
# wrap around if past len of the list
if current_index >= len(all_haikus):
current_index = 0
# get the new haiku
haiku = all_haikus[current_index % len(all_haikus)]
# set the new haiku text on the Label
haiku_lbl.text = haiku
refresh_display()
# if the left button was pressed
if left_btn.fell:
print("left button pressed")
# decrement the current index
current_index -= 1
# wrap around if below 0
if current_index < 0:
current_index = len(all_haikus) - 1
# get the new haiku
haiku = all_haikus[current_index % len(all_haikus)]
# set the new haiku text on the Label
haiku_lbl.text = haiku
refresh_display()
# if the (D12) random button was pressed
if random_btn.fell:
# ensure at least 2 haikus for random function
if len(all_haikus) > 1:
# choose a random haiku, different from currently showing one
old_index = current_index
while current_index == old_index:
current_index = random.randint(0, len(all_haikus) - 1)
# get the new haiku
haiku = all_haikus[current_index % len(all_haikus)]
# set the new haiku text on the Label
haiku_lbl.text = haiku
refresh_display()
Page last edited January 26, 2026
Code Explanation
The code for the project is contained in a single code.py file. The code has sections for high level tasks. Each task is covered in more detail below.
- Loading haikus from the local file and Adafruit IO
- Set up displayio visual elements
- Set up debouncers for the relevant buttons
- Respond to user interaction when the buttons are pressed
Loading Haikus
The code first checks whether the device is connected to a WiFi network. The connection itself happens automatically as long as settings.toml contains valid network credential values in the CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys. Next it ensures that there are values for ADAFRUIT_AIO_USERNAME and ADAFRUIT_AIO_KEY, if those values exist it initializes an HTTP connection to Adafruit IO. The Adafruit IO connection is then used to fetch the "haikus" feed.
The entries within the feed have an extra slash inserted into their newline escape sequences automatically by the Adafruit IO server, before adding them to the local list of haikus to show the double slash escape "\\n" is changed to a normal single slash newline "\n". When set as text on the Label, the newline escapes will be where visual line-breaks appear.
The local text file haikus.txt is opened and the contents are read(). The content is split on double newlines "\n\n" to separate all of the haikus contained in the file. Each one is added to the local list of haikus to show.
The current_index stores the index of the haiku that is currently displayed on the eInk display. It gets set to a random index initially and updated in response to user interaction.
The visual interface is comprised of 4 main components:
- The white background which uses 8x
scalein order to save memory by using a smaller Bitmap. It is placed behind all other visual elements. - The grey bamboo image shown along the bottom of the display. It's loaded with the adafruit_imageload library.
- The grey border drawn around the edges of the display. The bitmaptools.fill_region() function is used along with transparent color indexes within a
Paletteto "cut out" a rectangle from a full grey Bitmap leaving just the border visible. - The
BitmapLabelused to show the haiku. It uses a custom font loaded from the file fanwood_webfont_15.bdf. The font is one of the ones included in the circuitpython_fonts bundle.
The adafruit_debouncer library is used with the D11, D12, and D15 button pins to determine when the user presses the buttons. During the main loop each debouncer instance is updated and then checked for the falling edge that indicates the button is pressed. The right and left buttons, pins D11 and D15, will increment or decrement the current index and show the new haiku from the list. The down button on pin D12 will select a different random haiku from the list to show, updating the current index to the randomly chosen one.
Page last edited January 26, 2026
Use
There are two ways to load haikus on your MagTag. Write them in a local text file haikus.txt and put the file on the CIRCUITPY drive, or create a "haikus" feed on Adafruit IO and add them to feed. Depending on where you display your MagTag and how you power it, one or the other may be more convenient.
The code compiles the full list of haikus from both places so you can use either one or mix it up with some of each.
The right and left buttons, labeled D11 and D15, will cycle through the list of available haikus moving to the next or previous one to show it on the display.
The down button, labeled D12, will select a different random haiku from the list and change to it.
Local haikus.txt file
The first way to load haikus is to put them in a text file named haikus.txt in the root of the CIRCUITPY drive. If you downloaded the project bundle includes a haikus.txt with a handful of electronics and coding themed haikus. The format of the file is fairly simple with each 3-line haiku being separated by a full blank line, see the truncated example below.
hot iron, cool bench everything is organized nirvana achieved continuity? the multimeter goes beep testing continues rainbow LEDs blink and chase and undulate example code.py
Add your favorite haikus to the file by making new lines at the bottom or inserted between the existing ones. Or you can start from a blank file and write your haikus using the same syntax if you don't want to use the ones that come with the project bundle.
The other option is to set up an Adafruit IO Feed named "Haikus" and then add each haiku as an entry in the feed.
CIRCUITPY_WIFI_SSID, CIRCUITPY_WIFI_PASSWORD, ADAFRUIT_AIO_USERNAME, and ADAFRUIT_AIO_KEY in settings.toml with appropriate values for your WiFi network and AIO access.
Log in to Adafruit IO, click on "Feeds" in the navigation links then click on the "New Feed" button.
Enter the name "Haikus" for the new feed then press the Create button. The project code uses the feed name to fetch data so it is important to use the exact name "Haikus" or else it will not find the correct feed.
After the feed is created, click on its name in the list of feeds to go to the page for the new feed.
Click on the "Add Data" button to create a new entry in the feed.
Type or paste the lines of the haiku with \n in between each line. You must include the newline escape sequence \n in the haiku in order to get the lines to wrap at the appropriate points when displayed on the MagTag. For example:
The keyboard goes clack\nwriting code at 3AM\ntime for espresso!
Once a haiku with appropriate newline escapes is entered, press the "Create" button.
Repeat the process to add as many haikus as you want.
The project code will fetch the data from this feed and add the haikus from it to the list to be shown by the app.
Page last edited January 26, 2026