We'll be using CircuitPython for this project. Are you new to using CircuitPython? No worries, there is a full getting started guide here.

Adafruit suggests using the Mu editor to edit your code and have an interactive REPL in CircuitPython. You can learn about Mu and its installation in this tutorial.

In this first iteration, all we need is the Circuit Playground Express. We'll use the A and B buttons on it's face to trigger events, and in response we'll play a short (dot) or long (dash) tone on the onboard speaker.

The code is pretty simple. It continuously checks the two buttons and if one has been pressed it plays a tone for the appropriate length of time. After either tone plays, there's a short delay so the tones don't blur together. After that, the code makes sure the button has been released, or waits until it has. This avoids accidentally generating multiple triggers.

Save the code below as code.py on your Circuit Playground Express.

# SPDX-FileCopyrightText: 2018 Dave Astels for Adafruit Industries
# SPDX-License-Identifier: MIT

Circuit Playground Express GBoard: onboard buttons generating tones

Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!

Written by Dave Astels for Adafruit Industries
Copyright (c) 2018 Adafruit Industries
Licensed under the MIT license.

All text above must be included in any redistribution.

import time
from adafruit_circuitplayground.express import cpx


while True:
    if cpx.button_a:
        cpx.play_tone(4000, DOT_DURATION)
        while cpx.button_a:
    elif cpx.button_b:
        cpx.play_tone(4000, DASH_DURATION)
        while cpx.button_b:

Now, when you press button A a short tone will sound, and when you press button B a longer tone will sound.  The while cpx.button_X: pass code causes it to wait until you release the button before playing the tone again.

This guide was first published on Jul 24, 2018. It was last updated on Feb 19, 2024.

This page (Buttons and Buzzers) was last updated on Feb 08, 2024.

Text editor powered by tinymce.