Play Mario on MicroPython
Welcome to the Mario Song Lab
In this lab, you will play the famous Super Mario theme song on your Pico! You will use a dictionary of note names and a list of notes to play a real melody.
How This Program Works
To play a real song, you need two things:
- A dictionary that maps note names (like
"E7") to their exact frequencies in Hz. - A list of note names in the order they should be played.
The program loops through the note list, looks up each frequency in the dictionary, and plays that tone.
The Mario Program
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
What Each Line Does
tones = {...}— a dictionary with over 80 note names. Each name maps to a frequency in Hz.mario = [...]— a list of note names in the order they play in the melody.0means silence (a rest).def play_tone(frequency):— a function that turns the buzzer on at a given pitch.def be_quiet():— a function that sets the duty cycle to 0, silencing the buzzer.def play_song(note_list):— a function that loops through the note list and plays each one.if note_list[i] == "P" or note_list[i] == 0:— checks if the current item is a rest.play_tone(tones[note_list[i]])— looks up the note name in the dictionary and plays that frequency.sleep(0.3)— waits 0.3 seconds before moving to the next note.
Key Idea
The tones dictionary is the key to this program. It connects human-readable note names like "E7" to the exact frequency numbers your buzzer needs. Without it, you would have to look up every frequency by hand!
Monty's Tip
Try replacing play_song(mario) with play_song(song) to hear the short test melody first. It is much shorter and easier to check that your wiring is correct!
You Did It!
Your Pico is now playing the Mario theme song! Next, you will wire up eight buttons to build a playable piano keyboard.