Reader small image

You're reading from  Practical Python Programming for IoT

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838982461
Edition1st Edition
Languages
Right arrow

Running the RTTTL music example

Run the code in the chapter08/passive_buzzer_rtttl.py file, and your buzzer will play a simple musical scale.

The code to perform this is quite simple. In line (1) in the following code, we are using the rtttl module to parse an RTTTL music score into a series of notes defined by frequency and duration. Our score is stored in the rtttl_score variable:

from rtttl import parse_rtttl
rtttl_score = parse_rtttl("Scale:d=4,o=4,b=125:8a,8b, # (1)
8c#,8d,8e,8f#,8g#,8f#,8e,8d,8c#,8b,8a"
)

Next, in line (2), we loop through the parsed notes in rtttl_score and extract the frequency and duration:

    for note in rtttl_score['notes']:                        # (2)
frequency = int(note['frequency'])
duration = note['duration'] # Milliseconds
pi.hardware_PWM(BUZZER_GPIO, frequency, duty_cycle) # (3)
sleep(duration/1000) # (4)

In line (3), we set the frequency...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Practical Python Programming for IoT
Published in: Nov 2020Publisher: PacktISBN-13: 9781838982461