TW
from gpiozero import Buzzer
from time import sleep
import RPi.GPIO as GPIO
# Set up PWM on the buzzer pin
buzzer_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(buzzer_pin, GPIO.OUT)
buzzer = GPIO.PWM(buzzer_pin, 440) # Initialize PWM on pin 17 with a default frequency
# Define the notes and their frequencies in Hz
notes = {
'C': 261.63,
'D': 293.66,
'E': 329.63,
'F': 349.23,
'G': 392.00,
'A': 440.00,
'B': 493.88,
'C_high': 523.25
}
# Define the melody of "Twinkle Twinkle Little Star" as (note, duration)
melody = [
('C', 0.5), ('C', 0.5), ('G', 0.5), ('G', 0.5), ('A', 0.5), ('A', 0.5), ('G', 1.0),
('F', 0.5), ('F', 0.5), ('E', 0.5), ('E', 0.5), ('D', 0.5), ('D', 0.5), ('C', 1.0),
('G', 0.5), ('G', 0.5), ('F', 0.5), ('F', 0.5), ('E', 0.5), ('E', 0.5), ('D', 1.0),
('G', 0.5), ('G', 0.5), ('F', 0.5), ('F', 0.5), ('E', 0.5), ('E', 0.5), ('D', 1.0),
('C', 0.5), ('C', 0.5), ('G', 0.5), ('G', 0.5), ('A', 0.5), ('A', 0.5), ('G', 1.0),
('F', 0.5), ('F', 0.5), ('E', 0.5), ('E', 0.5), ('D', 0.5), ('D', 0.5), ('C', 1.0)
]
# Function to play a note
def play_buzzer(note, duration):
if note in notes:
buzzer.ChangeFrequency(notes[note]) # Change the frequency to the note
buzzer.start(50) # Start the buzzer at 50% duty cycle (square wave)
sleep(duration) # Play the note for the specified duration
buzzer.stop() # Stop the buzzer after the note is played
sleep(0.05) # Short pause between notes
# Play the melody
try:
for note, duration in melody:
play_buzzer(note, duration)
finally:
buzzer.stop()
GPIO.cleanup() # Clean up GPIO settings after playing