Start and Stop Tone

The Circuit Playground Express and Bluefruit have a built-in speaker above the music note printed on the board. It is the grey box with a + on it, below button A, to the left of the slide switch. Though the image is of the Circuit Playground Express, the speaker is in the same location on the Bluefruit. This speaker is capable of multiple things including the ability to play tones.

What if, instead of playing a tone for a specified amount of time (using play_tone()), you want to play the tone only when you provide an input? For example, instead of playing a tone for 1 second, what if you want the tone to play while you're pressing a button? Or touching a touch pad? You can do that!

Add the following code to your code.py. Remember, if you need help with this, check here.

"""This example plays a different tone for each button, while the button is pressed."""
from adafruit_circuitplayground import cp

while True:
    if cp.button_a:
        cp.start_tone(262)
    elif cp.button_b:
        cp.start_tone(294)
    else:
        cp.stop_tone()

Press button A. Now, press button B. Each button plays a tone, but only while it's being pressed!

Let's look at the code. First we import cp.

Inside our loop, we check to see if the buttons are being pressed. If button A is pressed, we start a tone with cp.start_tone(262). If button B is pressed, we start a tone with cp.start_tone(294). Otherwise, if they're not being pressed, we stop the tone. That's it!

cp.start_tone() requires one thing from you, a frequency in hertz of the tone you would like to start. So anytime you want to use it, you'll add cp.start_tone(frequency) to your code, where frequency is the hertz of the tone you'd like to start.

cp.start_tone() requires cp.stop_tone() to stop playing. Without it, you'll start the tone and it will play indefinitely. You'll know very quickly if you've forgotten to add cp.stop_tone()!

Try replacing buttons A and B with touch pads A1 and A2, and change the frequencies to have different tones. Try using all the touch inputs to have more tone options!

This guide was first published on Jun 05, 2018. It was last updated on Jun 05, 2018. This page (Start and Stop Tone) was last updated on May 27, 2020.