Song and lights — Smart Car (Python)
This example is written twice, once for each firmware. Pick the tab that matches the firmware of your Smart Car: the tab you pick is remembered on the other examples.
Firmware 3.0 renamed the Python names a program writes, and kept none of the old ones: a Smart Car on 2.x does not know the 3.0 names, and a Smart Car on 3.0 does not know the 2.x ones. The name map lists every change. If you open the example from inside MoBot, it picks the version for the firmware of your Smart Car. If you download a file from this page, use the one in the tab for your firmware.
A concert. The buzzer plays real tunes while both LEDs breathe in and out — LED 1 bright while LED 2 is dim, and back. Then the song pauses, carries on, speeds up, slows down, and finally the robot plays a tune written inside the program itself.
This is the version for a robot on firmware 3.0. For a robot that still runs firmware 2.x, MoBot opens the 2.x version of this example instead.
Project for firmware 3.0: 05-song-and-lights.firmware-3.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A Smart Car with its buzzer and both LEDs (nothing to plug in — they are all on the board).
- A USB cable and the serial monitor.
How to run it
Section titled “How to run it”- Open 05-song-and-lights.firmware-3.mobot and press Run.
- Listen, and watch the two LEDs.
It takes about half a minute from start to finish.
What you should see and hear
Section titled “What you should see and hear”| when | what |
|---|---|
| at the start | the monitor lists every song this robot knows — thirteen of them |
| then | the demo tune plays while LED 1 fades up as LED 2 fades down, over and over |
| after 4 seconds | the monitor prints still playing? and, while the song is still going, the first part of the song text |
| then | both LEDs come on solid and the music stops for 2 seconds — that is pause() |
| then | the music carries on from where it stopped, not from the beginning |
| then | mario_end plays fast, with LED 1 flashing all the way through, then the same tune again slowly |
| last | a short six-note tune written inside the program, and the volume printed in percent |
If the LEDs fade but you hear nothing, the buzzer is the problem. If you hear music but the LEDs stay dark, the LEDs are.
The surprise in this program
Section titled “The surprise in this program”play_song() does not wait. It hands the song to a hardware timer and
returns immediately, so the next line of your program runs while the music is
still going. That is why breathe(4) and the song happen at the same time
with no threads and no tricks — and it is also why you have to say
while buzzer.is_playing(): if you do want to wait for the end.
A song plays once unless you ask for more: play_song(song, loop=True)
repeats it until stop().
The block set has three sound blocks: Play sound, Stop sound and
Read sound volume (it reads buzzer.volume, in percent; it cannot change it).
pause(), resume(), is_playing(), current_song, set_tempo() and
set_volume() have no blocks at all.
Writing your own tune
Section titled “Writing your own tune”A song is a piece of text. Each note is four things separated by spaces:
"0 C4 2 0" -> at beat 0, play C4, for 2 beats, sound number 0and you join notes with ;. Notes run from C0 up to B9, and # means
sharp: C#4. Two notes with the same start beat play together as a chord.
The program
Section titled “The program”This is a reading copy of the program in the project: editing it changes nothing, so open the project and edit it there.
# main.py — Song and lights (Python) (robotics)## A reading copy of one file inside 05-song-and-lights.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# This is the entry point — the board runs it as main.py.# Written for firmware 3.0; the 2.x version is 05-song-and-lights.main.py.
"""Song and lights - MoBot Smart Car.
A little concert. The buzzer plays a real tune while the two LEDs breathe inand out at the same time - and that only works because of one surprising fact:
play_song() does NOT wait for the song to finish.
It starts the song on a timer and comes straight back, so the very next line ofyour program runs while the music is still going. That is why the LEDs can fade"during" the song without any clever tricks.
The block set can start a song, stop it, and read how loud it is. Everythingelse in this file - pause, resume, "is it still playing?", tempo, setting thevolume, and the songs that are not in the dropdown - is Python only."""
import timefrom indicators import SONGS
buzzer = robot.buzzerled1 = robot.led1led2 = robot.led2
print("Songs this robot knows:")print(" ", ", ".join(sorted(SONGS.keys())))print("")
def breathe(seconds): """Fade both LEDs up and down for a while. LED 2 is the opposite of LED 1.""" steps = 20 end = time.ticks_add(time.ticks_ms(), int(seconds * 1000)) while time.ticks_diff(end, time.ticks_ms()) > 0: for step in range(steps + 1): percent = step * 100 // steps led1.set_brightness(percent) # 0..100, a percentage led2.set_brightness(100 - percent) time.sleep(0.02) for step in range(steps + 1): percent = 100 - (step * 100 // steps) led1.set_brightness(percent) led2.set_brightness(100 - percent) time.sleep(0.02)
# ------------------------------------------------------------------- 1 ------# Start a song and keep working.
print("Playing 'demo' while the lights breathe.")buzzer.set_volume(8) # how loud, in percent: 8 is the usual, 100 the loudestbuzzer.set_tempo(3) # smaller number = fasterbuzzer.play_song(SONGS["demo"])
breathe(4)
print("still playing?", buzzer.is_playing())song = buzzer.current_songif song is not None: print("what is playing?", song[:40], "...")
# ------------------------------------------------------------------- 2 ------# Pause, wait, carry on. Nothing in the block set can do this.
print("Pausing for 2 seconds...")buzzer.pause()led1.on()led2.on()time.sleep(2)
print("...and back.")led1.off()led2.off()buzzer.resume()breathe(3)
buzzer.stop()
# ------------------------------------------------------------------- 3 ------# A song the dropdown does not offer, played fast, then slow.
print("")print("'mario_end' - fast, then slow. It is not in the block dropdown.")
buzzer.set_tempo(2)buzzer.play_song(SONGS["mario_end"])while buzzer.is_playing(): led1.on() time.sleep(0.1) led1.off() time.sleep(0.1)
time.sleep(0.5)
buzzer.set_tempo(8)buzzer.play_song(SONGS["mario_end"])time.sleep(4)buzzer.stop()
# ------------------------------------------------------------------- 4 ------# Your own tune. A song is just text: "<when> <note> <how long> <sound>",# with a semicolon between the notes. Notes go from C0 up to B9.
print("")print("Now a tune written right here in the program.")my_song = "0 C4 2 0;2 E4 2 0;4 G4 2 0;6 C5 4 0;10 G4 2 0;12 C5 6 0"buzzer.set_tempo(3)buzzer.play_song(my_song)time.sleep(4)buzzer.stop()
led1.off()led2.off()print("Concert over. The volume is", buzzer.volume, "percent.")Try changing it
Section titled “Try changing it”- Change
my_songat the bottom. Start with three notes and add more. buzzer.play_song(SONGS["siren"], loop=True)— it never stops until you callbuzzer.stop().buzzer.set_volume(30)for a louder concert;buzzer.volumetells you what it is set to.- Make
breathe()fade only LED 1 and leave LED 2 off.
A concert. The buzzer plays real tunes while both LEDs breathe in and out — LED 1 bright while LED 2 is dim, and back. Then the song pauses, carries on, speeds up, slows down, and finally the robot plays a tune written inside the program itself.
Project for firmware 2.x: 05-song-and-lights.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A Smart Car with its buzzer and both LEDs (nothing to plug in — they are all on the board).
- A USB cable and the serial monitor.
How to run it
Section titled “How to run it”- Open 05-song-and-lights.mobot and press Run.
- Listen, and watch the two LEDs.
It takes about half a minute from start to finish.
What you should see and hear
Section titled “What you should see and hear”| when | what |
|---|---|
| at the start | the monitor lists every song this robot knows — thirteen of them |
| then | the demo tune plays while LED 1 fades up as LED 2 fades down, over and over |
| after 4 seconds | the monitor prints still playing? True and the first part of the song text |
| then | both LEDs come on solid and the music stops for 2 seconds — that is pause() |
| then | the music carries on from where it stopped, not from the beginning |
| then | mario_end plays fast, with LED 1 flashing all the way through, then the same tune again slowly |
| last | a short six-note tune written inside the program |
If the LEDs fade but you hear nothing, the buzzer is the problem. If you hear music but the LEDs stay dark, the LEDs are.
The surprise in this program
Section titled “The surprise in this program”play() does not wait. It hands the song to a hardware timer and returns
immediately, so the next line of your program runs while the music is still
going. That is why breathe(4) and the song happen at the same time with no
threads and no tricks — and it is also why you have to say
while buzzer.is_playing(): if you do want to wait for the end.
The block set has exactly two sound blocks, Play sound and Stop sound.
pause(), resume(), is_playing(), get_current_song(), set_tempo() and
set_volume() have no blocks at all.
Writing your own tune
Section titled “Writing your own tune”A song is a piece of text. Each note is four things separated by spaces:
"0 C4 2 0" -> at beat 0, play C4, for 2 beats, sound number 0and you join notes with ;. Notes run from C0 up to B9, and # means
sharp: C#4. Two notes with the same start beat play together as a chord.
The program
Section titled “The program”This is a reading copy of the program in the project: editing it changes nothing, so open the project and edit it there.
# main.py — Song and lights (Python) (robotics)## A reading copy of one file inside 05-song-and-lights.mobot.# Editing this copy changes nothing: open the project and edit it there.# This is the entry point — the board runs it as main.py.
"""Song and lights - MoBot Smart Car.
A little concert. The buzzer plays a real tune while the two LEDs breathe inand out at the same time - and that only works because of one surprising fact:
play() does NOT wait for the song to finish.
It starts the song on a timer and comes straight back, so the very next line ofyour program runs while the music is still going. That is why the LEDs can fade"during" the song without any clever tricks.
The block set can only start a song and stop it. Everything else in this file -pause, resume, "is it still playing?", tempo, volume, and the songs that are notin the dropdown - is Python only."""
import timefrom indicators import SONGS
buzzer = mobotROBOTICS.buzzerled1 = mobotROBOTICS.led1led2 = mobotROBOTICS.led2
print("Songs this robot knows:")print(" ", ", ".join(sorted(SONGS.keys())))print("")
def breathe(seconds): """Fade both LEDs up and down for a while. LED 2 is the opposite of LED 1.""" steps = 20 end = time.ticks_add(time.ticks_ms(), int(seconds * 1000)) while time.ticks_diff(end, time.ticks_ms()) > 0: for step in range(steps + 1): percent = step * 100 // steps led1.setLedBrightness(percent) # 0..100, a percentage led2.setLedBrightness(100 - percent) time.sleep(0.02) for step in range(steps + 1): percent = 100 - (step * 100 // steps) led1.setLedBrightness(percent) led2.setLedBrightness(100 - percent) time.sleep(0.02)
# ------------------------------------------------------------------- 1 ------# Start a song and keep working.
print("Playing 'demo' while the lights breathe.")buzzer.set_volume(2512) # how loud. Bigger is louder, up to about 5000.buzzer.set_tempo(3) # smaller number = fasterbuzzer.play(SONGS["demo"], looping=False)
breathe(4)
print("still playing?", buzzer.is_playing())print("what is playing?", buzzer.get_current_song()[:40], "...")
# ------------------------------------------------------------------- 2 ------# Pause, wait, carry on. Nothing in the block set can do this.
print("Pausing for 2 seconds...")buzzer.pause()led1.on()led2.on()time.sleep(2)
print("...and back.")led1.off()led2.off()buzzer.resume()breathe(3)
buzzer.stop()
# ------------------------------------------------------------------- 3 ------# A song the dropdown does not offer, played fast, then slow.
print("")print("'mario_end' - fast, then slow. It is not in the block dropdown.")
buzzer.set_tempo(2)buzzer.play(SONGS["mario_end"], looping=False)while buzzer.is_playing(): led1.on() time.sleep(0.1) led1.off() time.sleep(0.1)
time.sleep(0.5)
buzzer.set_tempo(8)buzzer.play(SONGS["mario_end"], looping=False)time.sleep(4)buzzer.stop()
# ------------------------------------------------------------------- 4 ------# Your own tune. A song is just text: "<when> <note> <how long> <sound>",# with a semicolon between the notes. Notes go from C0 up to B9.
print("")print("Now a tune written right here in the program.")my_song = "0 C4 2 0;2 E4 2 0;4 G4 2 0;6 C5 4 0;10 G4 2 0;12 C5 6 0"buzzer.set_tempo(3)buzzer.play(my_song, looping=False)time.sleep(4)buzzer.stop()
led1.off()led2.off()print("Concert over.")Try changing it
Section titled “Try changing it”- Change
my_songat the bottom. Start with three notes and add more. buzzer.play(SONGS["siren"], looping=True)—looping=Truenever stops until you callbuzzer.stop().- Make
breathe()fade only LED 1 and leave LED 2 off.