CircuitPython Power!

Build a simple Guitar Tuner with CircuitPython and Adafruit PyPortal! Use the touch screen to tap on tuning pegs and play music notes. The notes are pre-recorded wav audio files of guitar strings. The graphic of the head stock is a single bitmap. This uses the displayio library for CircuitPython and can be customized to make a unique sound board.

3D Printed PyPortal Case

The Adafruit PyPortal and a mini oval speaker are secured to a 3D printed enclosure using M2.5 screws and standoffs. The PyPortal is mounted vertically and features a built-in holder for a speaker.

Parts

PyPortal, our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Make custom touch screen interface...
$54.95
In Stock
Hear the good news! This wee speaker is a great addition to any audio project where you need 8 ohm impedance and 1W or less of power. We particularly like...
$1.95
In Stock
This cable is not only super-fashionable, with a woven pink and purple Blinka-like pattern, it's also fully reversible! That's right, you will save seconds a day by...
$3.95
In Stock
Totaling 380 pieces, this M2.5 Screw Set is a must-have for your workstation. You'll have enough screws, nuts, and hex standoffs to fuel your maker...
$16.95
In Stock

Parts List

STL files for 3D printing are oriented to print "as-is" on FDM style machines. Parts are designed to 3D print without any support material. Original design source may be downloaded using the links below.

  • frame.stl
  • screen-cover.stl
  • pcb-plate.stl

CAD Assembly

The PyPortal is secured to the PCB plate using M2.5 hardware screws and standoffs. The screen cover is press fitted over the PyPortal's display. The PCB plate is secured to the frame using M2.5 hardware screws and hex nuts. The speaker is press fitted into the holder in the center of the PCB plate.

Slicing Parts

No supports are required. Slice with settings for PLA material. 

The parts were sliced using CURA using the slice settings below.

  • PLA filament 220c extruder
  • 0.2 layer height
  • 10% gyroid infill
  • 60mm/s print speed
  • 60c heated bed

Design Source Files

The project assembly was designed in Fusion 360. This can be downloaded in different formats like STEP, STL and more. Electronic components like Adafruit's board, displays, connectors and more can be downloaded from the Adafruit CAD parts GitHub Repo.

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 "flash" drive to iterate.

The following instructions will show you how to install CircuitPython. If you've already installed CircuitPython but are looking to update it or reinstall it, the same steps work for that as well!

Set up CircuitPython Quick Start!

Follow this quick step-by-step for super-fast Python power :)

Click the link above to download the latest version of CircuitPython for the PyPortal.

Download and save it to your desktop (or wherever is handy).

Plug your PyPortal 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.

Double-click the Reset button on the top in the middle (magenta arrow) on your board, and you will see the NeoPixel RGB LED (green arrow) turn green. If it turns red, check the USB cable, try another USB port, etc. Note: The little red LED next to the USB connector will pulse red. That's ok!

If double-clicking doesn't work the first time, try again. Sometimes it can take a few tries to get the rhythm right!

You will see a new disk drive appear called PORTALBOOT.

Drag the adafruit-circuitpython-pyportal-<whatever>.uf2 file to PORTALBOOT.

The LED will flash. Then, the PORTALBOOT drive will disappear and a new disk drive called CIRCUITPY will appear.

If you haven't added any code to your board, the only file that will be present is boot_out.txt. This is absolutely normal! It's time for you to add your code.py and get started!

That's it, you're done! :)

PyPortal Default Files

Click below to download a zip of the files that shipped on the PyPortal or PyPortal Pynt.

As CircuitPython development continues and there are new releases, Adafruit will stop supporting older releases. Visit https://circuitpython.org/downloads to download the latest version of CircuitPython for your board. You must download the CircuitPython Library Bundle that matches your version of CircuitPython. Please update CircuitPython and then visit https://circuitpython.org/libraries to download the latest Library Bundle.

Each CircuitPython program you run needs to have a lot of information to work. The reason CircuitPython is so simple to use is that most of that information is stored in other files and works in the background. These files are called libraries. Some of them are built into CircuitPython. Others are stored on your CIRCUITPY drive in a folder called lib. Part of what makes CircuitPython so great is its ability to store code separately from the firmware itself. Storing code separately from the firmware makes it easier to update both the code you write and the libraries you depend.

Your board may ship with a lib folder already, it's in the base directory of the drive. If not, simply create the folder yourself. When you first install CircuitPython, an empty lib directory will be created for you.

CircuitPython libraries work in the same way as regular Python modules so the Python docs are an excellent reference for how it all should work. In Python terms, you can place our library files in the lib directory because it's part of the Python path by default.

One downside of this approach of separate libraries is that they are not built in. To use them, one needs to copy them to the CIRCUITPY drive before they can be used. Fortunately, there is a library bundle.

The bundle and the library releases on GitHub also feature optimized versions of the libraries with the .mpy file extension. These files take less space on the drive and have a smaller memory footprint as they are loaded.

Due to the regular updates and space constraints, Adafruit does not ship boards with the entire bundle. Therefore, you will need to load the libraries you need when you begin working with your board. You can find example code in the guides for your board that depends on external libraries.

Either way, as you start to explore CircuitPython, you'll want to know how to get libraries on board.

The Adafruit CircuitPython Library Bundle

Adafruit provides CircuitPython libraries for much of the hardware they provide, including sensors, breakouts and more. To eliminate the need for searching for each library individually, the libraries are available together in the Adafruit CircuitPython Library Bundle. The bundle contains all the files needed to use each library.

Downloading the Adafruit CircuitPython Library Bundle

You can download the latest Adafruit CircuitPython Library Bundle release by clicking the button below. The libraries are being constantly updated and improved, so you'll always want to download the latest bundle. 

Match up the bundle version with the version of CircuitPython you are running. For example, you would download the 6.x library bundle if you're running any version of CircuitPython 6, or the 7.x library bundle if you're running any version of CircuitPython 7, etc. If you mix libraries with major CircuitPython versions, you will get incompatible mpy errors due to changes in library interfaces possible during major version changes.

Download the bundle version that matches your CircuitPython firmware version. If you don't know the version, check the version info in boot_out.txt file on the CIRCUITPY drive, or the initial prompt in the CircuitPython REPL. For example, if you're running v7.0.0, download the 7.x library bundle.

There's also a py bundle which contains the uncompressed python files, you probably don't want that unless you are doing advanced work on libraries.

The CircuitPython Community Library Bundle

The CircuitPython Community Library Bundle is made up of libraries written and provided by members of the CircuitPython community. These libraries are often written when community members encountered hardware not supported in the Adafruit Bundle, or to support a personal project. The authors all chose to submit these libraries to the Community Bundle make them available to the community.

These libraries are maintained by their authors and are not supported by Adafruit. As you would with any library, if you run into problems, feel free to file an issue on the GitHub repo for the library. Bear in mind, though, that most of these libraries are supported by a single person and you should be patient about receiving a response. Remember, these folks are not paid by Adafruit, and are volunteering their personal time when possible to provide support.

Downloading the CircuitPython Community Library Bundle

You can download the latest CircuitPython Community Library Bundle release by clicking the button below. The libraries are being constantly updated and improved, so you'll always want to download the latest bundle.

The link takes you to the latest release of the CircuitPython Community Library Bundle on GitHub. There are multiple versions of the bundle available. Download the bundle version that matches your CircuitPython firmware version. If you don't know the version, check the version info in boot_out.txt file on the CIRCUITPY drive, or the initial prompt in the CircuitPython REPL. For example, if you're running v7.0.0, download the 7.x library bundle.

Understanding the Bundle

After downloading the zip, extract its contents. This is usually done by double clicking on the zip. On Mac OSX, it places the file in the same directory as the zip.

Open the bundle folder. Inside you'll find two information files, and two folders. One folder is the lib bundle, and the other folder is the examples bundle.

Now open the lib folder. When you open the folder, you'll see a large number of .mpy files, and folders.

Example Files

All example files from each library are now included in the bundles in an examples directory (as seen above), as well as an examples-only bundle. These are included for two main reasons:

  • Allow for quick testing of devices.
  • Provide an example base of code, that is easily built upon for individualized purposes.

Copying Libraries to Your Board

First open the lib folder on your CIRCUITPY drive. Then, open the lib folder you extracted from the downloaded zip. Inside you'll find a number of folders and .mpy files. Find the library you'd like to use, and copy it to the lib folder on CIRCUITPY.

If the library is a directory with multiple .mpy files in it, be sure to copy the entire folder to CIRCUITPY/lib.

This also applies to example files. Open the examples folder you extracted from the downloaded zip, and copy the applicable file to your CIRCUITPY drive. Then, rename it to code.py to run it.

If a library has multiple .mpy files contained in a folder, be sure to copy the entire folder to CIRCUITPY/lib.

Understanding Which Libraries to Install

You now know how to load libraries on to your CircuitPython-compatible microcontroller board. You may now be wondering, how do you know which libraries you need to install? Unfortunately, it's not always straightforward. Fortunately, there is an obvious place to start, and a relatively simple way to figure out the rest. First up: the best place to start.

When you look at most CircuitPython examples, you'll see they begin with one or more import statements. These typically look like the following:

  • import library_or_module

However, import statements can also sometimes look like the following:

  • from library_or_module import name
  • from library_or_module.subpackage import name
  • from library_or_module import name as local_name

They can also have more complicated formats, such as including a try / except block, etc.

The important thing to know is that an import statement will always include the name of the module or library that you're importing.

Therefore, the best place to start is by reading through the import statements.

Here is an example import list for you to work with in this section. There is no setup or other code shown here, as the purpose of this section involves only the import list.

import time
import board
import neopixel
import adafruit_lis3dh
import usb_hid
from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode

Keep in mind, not all imported items are libraries. Some of them are almost always built-in CircuitPython modules. How do you know the difference? Time to visit the REPL.

In the Interacting with the REPL section on The REPL page in this guide, the help("modules") command is discussed. This command provides a list of all of the built-in modules available in CircuitPython for your board. So, if you connect to the serial console on your board, and enter the REPL, you can run help("modules") to see what modules are available for your board. Then, as you read through the import statements, you can, for the purposes of figuring out which libraries to load, ignore the statement that import modules.

The following is the list of modules built into CircuitPython for the Feather RP2040. Your list may look similar or be anything down to a significant subset of this list for smaller boards.

Now that you know what you're looking for, it's time to read through the import statements. The first two, time and board, are on the modules list above, so they're built-in.

The next one, neopixel, is not on the module list. That means it's your first library! So, you would head over to the bundle zip you downloaded, and search for neopixel. There is a neopixel.mpy file in the bundle zip. Copy it over to the lib folder on your CIRCUITPY drive. The following one, adafruit_lis3dh, is also not on the module list. Follow the same process for adafruit_lis3dh, where you'll find adafruit_lis3dh.mpy, and copy that over.

The fifth one is usb_hid, and it is in the modules list, so it is built in. Often all of the built-in modules come first in the import list, but sometimes they don't! Don't assume that everything after the first library is also a library, and verify each import with the modules list to be sure. Otherwise, you'll search the bundle and come up empty!

The final two imports are not as clear. Remember, when import statements are formatted like this, the first thing after the from is the library name. In this case, the library name is adafruit_hid. A search of the bundle will find an adafruit_hid folder. When a library is a folder, you must copy the entire folder and its contents as it is in the bundle to the lib folder on your CIRCUITPY drive. In this case, you would copy the entire adafruit_hid folder to your CIRCUITPY/lib folder.

Notice that there are two imports that begin with adafruit_hid. Sometimes you will need to import more than one thing from the same library. Regardless of how many times you import the same library, you only need to load the library by copying over the adafruit_hid folder once.

That is how you can use your example code to figure out what libraries to load on your CircuitPython-compatible board!

There are cases, however, where libraries require other libraries internally. The internally required library is called a dependency. In the event of library dependencies, the easiest way to figure out what other libraries are required is to connect to the serial console and follow along with the ImportError printed there. The following is a very simple example of an ImportError, but the concept is the same for any missing library.

Example: ImportError Due to Missing Library

If you choose to load libraries as you need them, or you're starting fresh with an existing example, you may end up with code that tries to use a library you haven't yet loaded.  This section will demonstrate what happens when you try to utilise a library that you don't have loaded on your board, and cover the steps required to resolve the issue.

This demonstration will only return an error if you do not have the required library loaded into the lib folder on your CIRCUITPY drive.

Let's use a modified version of the Blink example.

import board
import time
import simpleio

led = simpleio.DigitalOut(board.LED)

while True:
    led.value = True
    time.sleep(0.5)
    led.value = False
    time.sleep(0.5)

Save this file. Nothing happens to your board. Let's check the serial console to see what's going on.

You have an ImportError. It says there is no module named 'simpleio'. That's the one you just included in your code!

Click the link above to download the correct bundle. Extract the lib folder from the downloaded bundle file. Scroll down to find simpleio.mpy. This is the library file you're looking for! Follow the steps above to load an individual library file.

The LED starts blinking again! Let's check the serial console.

No errors! Excellent. You've successfully resolved an ImportError!

If you run into this error in the future, follow along with the steps above and choose the library that matches the one you're missing.

Library Install on Non-Express Boards

If you have an M0 non-Express board such as Trinket M0, Gemma M0, QT Py M0, or one of the M0 Trinkeys, you'll want to follow the same steps in the example above to install libraries as you need them. Remember, you don't need to wait for an ImportError if you know what library you added to your code. Open the library bundle you downloaded, find the library you need, and drag it to the lib folder on your CIRCUITPY drive.

You can still end up running out of space on your M0 non-Express board even if you only load libraries as you need them. There are a number of steps you can use to try to resolve this issue. You'll find suggestions on the Troubleshooting page.

Updating CircuitPython Libraries and Examples

Libraries and examples are updated from time to time, and it's important to update the files you have on your CIRCUITPY drive.

To update a single library or example, follow the same steps above. When you drag the library file to your lib folder, it will ask if you want to replace it. Say yes. That's it!

A new library bundle is released every time there's an update to a library. Updates include things like bug fixes and new features. It's important to check in every so often to see if the libraries you're using have been updated.

Adding Libraries

Once you've finished setting up your PyPortal with CircuitPython, you can add these libraries to the lib folder:

  • adafruit_bitmap_font
  • adafruit_bus_device
  • adafruit_display_shapes
  • adafruit_display_text
  • adafruit_esp32spi
  • adafruit_imageload
  • adafruit_io
  • adafruit_adt7410.mpy
  • adafruit_button.mpy
  • adafruit_pyportal.mpy
  • adafruit_requests.mpy
  • adafruit_sdcard.mpy
  • adafruit_touchscreen.mpy
  • neopixel.mpy

Then, you can click on the Download: Project Zip link above the code to download the code file, audio files and bitmap file.

Code

Click on "Copy Code" and then paste it into the Mu editor to save to your PyPortal as code.py or copy the code file from the Project Zip folder to the PyPortal's CIRCUITPY drive.

You will also need the secrets.py code file from the Project Zip folder since it is required for the PyPortal CircuitPython library.

import time
from adafruit_button import Button
from adafruit_pyportal import PyPortal

pyportal = PyPortal(default_bg="/stock-pyportal.bmp")

lowE = "/sounds/lowE.wav"
A = "/sounds/A.wav"
D = "/sounds/D.wav"
G = "/sounds/G.wav"
B = "/sounds/B.wav"
highE = "/sounds/highE.wav"

notes = [lowE, A, D, G, B, highE]

pegs = [
    {'label': "lowE", 'pos': (53, 0), 'size': (65, 90)},
    {'label': "A", 'pos': (124, 0), 'size': (65, 90)},
    {'label': "D", 'pos': (194, 0), 'size': (65, 90)},
    {'label': "G", 'pos': (194, 150), 'size': (65, 90)},
    {'label': "B", 'pos': (124, 150), 'size': (65, 90)},
    {'label': "highE", 'pos': (53, 150), 'size': (65, 90)}
    ]

buttons = []
for peg in pegs:
    button = Button(x=peg['pos'][0], y=peg['pos'][1],
                    width=peg['size'][0], height=peg['size'][1],
                    style=Button.RECT,
                    fill_color=None, outline_color=0x5C3C15,
                    name=peg['label'])
    pyportal.splash.append(button.group)
    buttons.append(button)

note_select = None

while True:
    touch = pyportal.touchscreen.touch_point
    if not touch and note_select:
        note_select = False
    if touch:
        for i in range(6):
            tuning = notes[i]
            button = buttons[i]
            if button.contains(touch) and not note_select:
                print("Touched", button.name)
                note_select = True
                for z in range(3):
                    pyportal.play_file(tuning)
    time.sleep(0.1)

Audio Files and Bitmap Graphic

In addition to the lib folder, for this project you'll also have a sounds folder. The sounds folder contains the six audio files that are used to tune your guitar using the PyPortal. Each audio file is a quick sample of each string on a guitar in standard tuning (E - A - D - G - B - E).

  • A.wav
  • B.wav
  • D.wav
  • G.wav
  • highE.wav
  • lowE.wav

There is also a bitmap image for the PyPortal's display that depicts a guitar's headstock. This image file, called stock-pyportal.bmp, will also be stored on the PyPortal. 

Copy the sounds folder and the stock-pyportal.bmp bitmap image file from the Project Zip folder to the PyPortal's CIRCUITPY drive.

Your PyPortal CIRCUITPY drive should look like this after you load the libraries, audio files, bitmap and code files below:

Setup

CircuitPython Libraries

The CircuitPython code begins by importing the libraries.

import time
from adafruit_button import Button
from adafruit_pyportal import PyPortal

Display Setup

First, pyportal is setup as a PyPortal object. The PyPortal's default background is also setup to be the guitar headstock image, stock-pyportal.bmp. This means that on boot, the PyPortal will display the bitmap with just one line of code.

pyportal = PyPortal(default_bg="/stock-pyportal.bmp")

Loading Audio Files

The audio file locations are assigned to variables so that they can be easily referenced in the code. Then, files are put into the notes array in order from low to high.

lowE = "/sounds/lowE.wav"
A = "/sounds/A.wav"
D = "/sounds/D.wav"
G = "/sounds/G.wav"
B = "/sounds/B.wav"
highE = "/sounds/highE.wav"

notes = [lowE, A, D, G, B, highE]

Touchscreen Buttons

The PyPortal will have six buttons that sit on top of the guitar headstock image. Instead of setting each button up individually, their parameters are setup as a group in an array, called pegs, of dictionary entries. This way you can easily denote the buttons' label, position and size.

pegs = [
    {'label': "lowE", 'pos': (53, 0), 'size': (65, 90)},
    {'label': "A", 'pos': (124, 0), 'size': (65, 90)},
    {'label': "D", 'pos': (194, 0), 'size': (65, 90)},
    {'label': "G", 'pos': (194, 150), 'size': (65, 90)},
    {'label': "B", 'pos': (124, 150), 'size': (65, 90)},
    {'label': "highE", 'pos': (53, 150), 'size': (65, 90)}
    ]

Finally, this information for the buttons are assigned as Button objects using the adafruit_button CircuitPython library. Using the pegs array, all of the information from the dictionaries can be pulled in to complete the setup for the buttons. These buttons are then added to the PyPortal's display.

buttons = []
for peg in pegs:
    button = Button(x=peg['pos'][0], y=peg['pos'][1],
                    width=peg['size'][0], height=peg['size'][1],
                    style=Button.RECT,
                    fill_color=None, outline_color=0x5C3C15,
                    name=peg['label'])
    pyportal.splash.append(button.group)
    buttons.append(button)

Button State

The note_select state will be used to debounce the touchscreen buttons.

note_select = None

The Loop

The loop begins with touch setup to hold the PyPortal's touchscreen functionality.

Next, touchscreen button debouncing is setup. You only need to setup one instance rather than one for each individual button because you are essentially checking to see if the touchscreen is being touched in any location.

while True:
    touch = pyportal.touchscreen.touch_point
    
    if not touch and note_select:
        note_select = False

Play Notes

The final portion of the loop is how notes are played through the PyPortal. First, it checks to see if the touchscreen has been touched.

This is followed by a for statement. In this for statement, tuning and button are setup to hold the array index locations for the notes and buttons arrays. Since there are six indexes in each of these arrays, this allows for the sound files to match up with the touchscreen buttons and play when pressed.

Finally, an if statement checks if the touchscreen was touched in the proximity of the coordinates of one of the button locations. If it was, then the name of the button is printed to the REPL. This is followed by a final for statement. This for statement allows for the corresponding note's audio file to play three times.

This is followed by a delay. The length of the delay will determine the amount of time between each time the audio files are played. You may want to adjust it depending on your guitar tuning preferences.

if touch:
        for i in range(6):
            tuning = notes[i]
            button = buttons[i]
          	if button.contains(touch) and not note_select:
                print("Touched", button.name)
                note_select = True
                for z in range(3):
                    pyportal.play_file(tuning)
    time.sleep(0.1)

Hardware Setup

Use 4x M2.5 x 6mm long FF standoffs and 4x M2.5 x 6mm long screws to secure the PCB plate to the PyPortal. 

Install Standoffs

Insert M2.5 x 6mm screws through the top of the mounting tabs on PyPortal. Fasten M2.5 x 6mm long standoffs onto the threads of the screws.

Screen Cover

Orient the screen cover with the display on the PyPortal. Use the photo to reference the correct orientation.

Install Screen Cover

Fit the PyPortal display into the recess on the screen cover. Press the screen to fully seat into the screen cover.

Installed Screen Cover

The screen cover helps to keep the display attached to the PyPortal. The viewing area is exposed and does not obstruct display. This also hides the screens bezel.

Installing Plate and Speaker

The PyPortal is secured to the PCB plate using 4x M2.5 x 6mm screws. The mini oval speaker is press fitted onto the speaker holder on the PCB plate.

Connect Speaker

Plug in the molex pico connector from the speaker to the speaker port on the back of the PyPortal.

Install Speaker

Press fit the body of the speaker into the speaker holder in the center of the PCB plate. Reference the photo for best orientation. 

Secure PyPortal

Place the PCB plate to the back of the PyPortal with the mounting holes lined up with the standoffs.

Install Frame

Orient the frame with the mount tabs on the PCB plate. Line up the mounting holes in the frame with the mounting tabs on the PCB.

Secure Frame

Insert 4x M2.5 x 6mm screws into the side of the frame and through the mounting tabs on the PCB plate. Insert and fasten 4x M2.5 hex nuts onto threads of the screws and tighten.

Final Build

And now we're ready for some guitar tuning!

Going Further

The frame has adequate amount of space for a USB battery or other components.

This guide was first published on Jun 09, 2020. It was last updated on Jun 09, 2020.