from machine import Pin, PWM
import time
# Buzzer configuration
buzzer_pin = Pin(6) # Change this to the appropriate GPIO pin (GP6 on Raspberry Pi Pico)
buzzer_pwm = PWM(buzzer_pin)
# Button configuration
button_pin = Pin(8, Pin.IN, Pin.PULL_UP)
def play_tone(frequency, duration):
# Set the frequency of the PWM to the desired tone
buzzer_pwm.freq(frequency)
# Start the PWM
buzzer_pwm.duty_u16(32767) # 50% duty cycle
# Wait for the specified duration
time.sleep_ms(duration)
# Stop the PWM
buzzer_pwm.duty_u16(0)
def is_button_pressed():
# Check if the button is pressed (active low)
return not button_pin.value()
# Play a simple melody with frequencies between 1 and 800 Hz
melody = [200, 700, 500, 600, 900, 800, 700, 800]
duration = 200 # in milliseconds
while True:
if is_button_pressed():
print("Button pressed! Playing melody.")
for freq in melody:
play_tone(freq, duration)
time.sleep_ms(25) # Add a short delay between tones
else:
print("Button not pressed. Waiting...")
time.sleep(1.0) # Adjust the delay based on your needs