from machine import Pin, PWM
import time
# --- Configuration ---
BUZZER_PIN = 6 # Set this to the GPIO pin you connected the buzzer to (e.g., GP5)
FREQUENCY = 440 # A4 note
DURATION_MS = 500 # How long the tone is ON (in milliseconds)
REST_MS = 500 # How long the tone is OFF (in milliseconds)
DUTY_CYCLE_16BIT = 32768 # 50% duty cycle for a square wave tone
# ---------------------
# Initialize PWM object outside the loop
# This sets up the pin to be ready for PWM
speaker = PWM(Pin(BUZZER_PIN))
print("Starting continuous tone sequence on pin GP{}".format(BUZZER_PIN))
while True:
# 1. --- Play Tone (ON) ---
print("Tone ON: {} Hz".format(FREQUENCY))
speaker.freq(FREQUENCY) # Set the frequency
speaker.duty_u16(DUTY_CYCLE_16BIT) # Set duty cycle (Turn tone ON)
time.sleep_ms(DURATION_MS) # Keep the tone on for the duration
# 2. --- Stop Tone (OFF) ---
print("Tone OFF")
# Setting the duty cycle to 0 effectively turns the sound off
speaker.duty_u16(0)
time.sleep_ms(REST_MS) # Keep the tone off for the rest period