|
| 1 | +from XRPLib.defaults import * |
| 2 | +import time |
| 3 | + |
| 4 | +""" |
| 5 | + By the end of this file students will learn how to use the Buzzer class |
| 6 | + to play individual notes, custom songs, and how to make the robot |
| 7 | + play music while it is moving. |
| 8 | +""" |
| 9 | + |
| 10 | +def simple_scale(): |
| 11 | + """Plays a basic C major scale.""" |
| 12 | + print("Playing a simple scale...") |
| 13 | + notes = ["C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5"] |
| 14 | + for note in notes: |
| 15 | + buzzer.play_note(note, "quarter") |
| 16 | + |
| 17 | +def custom_song_example(): |
| 18 | + """Demonstrates how to create and play a custom list of notes.""" |
| 19 | + print("Playing a custom melody...") |
| 20 | + # A song is a list of (note, duration) tuples |
| 21 | + # Durations can be "whole", "half", "quarter", "eighth", "sixteenth" |
| 22 | + my_song = [ |
| 23 | + ("E4", "eighth"), ("G4", "eighth"), ("E5", "quarter"), |
| 24 | + ("rest", "eighth"), |
| 25 | + ("C4", "quarter"), ("G3", "half") |
| 26 | + ] |
| 27 | + |
| 28 | + # Set tempo to 140 Beats Per Minute |
| 29 | + buzzer.set_tempo(140) |
| 30 | + buzzer.play_song(my_song) |
| 31 | + |
| 32 | +def siren(): |
| 33 | + """Simple two-tone siren effect using individual notes.""" |
| 34 | + print("Siren started!") |
| 35 | + for _ in range(3): |
| 36 | + buzzer.play_note("A4", "quarter") |
| 37 | + buzzer.play_note("E4", "quarter") |
| 38 | + |
| 39 | +def musical_robot(): |
| 40 | + """ |
| 41 | + Playing music while driving. |
| 42 | + We use blocking=False so the code continues to the next line |
| 43 | + while the music plays in the background. |
| 44 | + """ |
| 45 | + print("Dancing with music!") |
| 46 | + |
| 47 | + # Start 'Move It' in the background |
| 48 | + buzzer.play_move_it(blocking=False) |
| 49 | + |
| 50 | + # While the song is playing, the robot can perform actions |
| 51 | + for i in range(4): |
| 52 | + drivetrain.set_effort(0.6, -0.6) # Spin right |
| 53 | + time.sleep(0.5) |
| 54 | + drivetrain.set_effort(-0.6, 0.6) # Spin left |
| 55 | + time.sleep(0.5) |
| 56 | + |
| 57 | + drivetrain.stop() |
| 58 | + print("Dance finished.") |
| 59 | + |
| 60 | +def drive_and_beep(): |
| 61 | + """Driving forward and playing a note at the same time.""" |
| 62 | + # Start driving forward (this is non-blocking) |
| 63 | + drivetrain.set_effort(0.5, 0.5) |
| 64 | + |
| 65 | + # Play a long note (blocking=True) so the robot drives for the duration of the note |
| 66 | + print("Driving for a whole note...") |
| 67 | + buzzer.play_note("C5", "whole", blocking=True) |
| 68 | + |
| 69 | + drivetrain.stop() |
| 70 | + |
| 71 | +def main(): |
| 72 | + # Run the examples |
| 73 | + simple_scale() |
| 74 | + time.sleep(1) |
| 75 | + |
| 76 | + siren() |
| 77 | + time.sleep(1) |
| 78 | + |
| 79 | + musical_robot() |
| 80 | + |
| 81 | +main() |
0 commit comments