Play Three Tones
Welcome to Three Tones
In this lab, you will play three tones in a row. Each tone has its own pitch and its own timing. This is how simple music is made!
How It Works
Playing a sequence of tones is a simple pattern. For each tone, you:
- Turn the sound on with
duty_u16. - Set the pitch with
freq. - Wait for a moment with
sleep. - Turn the sound off with
duty_u16(0). - Wait for a short gap before the next tone.
Lab 1: Three Tones in a Row
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
What Each Line Does
speaker.duty_u16(1000)— turns the sound on. The value 1000 is low, making the tone quieter than 32768.speaker.freq(300)— sets the pitch to 300 Hz. Lower numbers give lower pitches.sleep(0.5)— waits half a second while the note plays.speaker.duty_u16(0)— turns the sound off.sleep(0.25)— waits a short time between notes. This gap makes each tone sound separate.
Key Idea
The gap between notes matters! Without sleep(0.25) between tones, they would blend together and sound like one long note.
Using Variables for Timing
If you want to change how long each note plays, you would have to update every sleep(0.5) line. There is a better way — store the timing values in variables:
1 2 3 4 | |
Now you only need to change one number to update all the notes at once.
Lab 2: Three Tones With Variables
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
What Changed
ON_TIME = 0.25— one variable controls how long every note plays.OFF_TIME = 0.1— one variable controls the gap between every note.- You can now change the timing of the whole program by editing just two lines.
Monty's Tip
Using CAPITAL_LETTERS for constant values like ON_TIME is a Python convention. It tells other coders (and future you!) that this value is set once and does not change while the program runs.
Experiments
- Change
ON_TIMEto a very short value like0.05. What is the shortest note you can still hear? - Try changing the order of the three tones: Low → High → Medium. Then try High → Low → Medium. Which order sounds most like a "game over" sound? Which sounds most like a "level up"?
- Add a fourth tone. Pick a frequency between 100 and 2000 Hz.
Great Work!
You just programmed your Pico to play a sequence of notes. In the next lab, you will use a loop to play a whole scale of tones automatically!