from machine import Pin, ADC, PWM
import time
# Define pins
light_sensor_pin = ADC(Pin(26)) # Light sensor analog output connected to GP26
buzzer_pin = Pin(16) # Buzzer connected to GP16
buzzer_pwm = PWM(buzzer_pin)
# Function to read light intensity
def read_light_intensity():
return light_sensor_pin.read_u16() # Read ADC value (0-65535)
# Function to activate the buzzer with a tone
def activate_buzzer(frequency, duration):
buzzer_pwm.freq(int(frequency)) # Convert frequency to integer
buzzer_pwm.duty_u16(32768) # Set the duty cycle (50% duty cycle for tone)
time.sleep(duration) # Wait for the specified duration
buzzer_pwm.duty_u16(0) # Turn off the buzzer
time.sleep(0.1) # Short pause
while True:
light_intensity = read_light_intensity()
print("Light Intensity: {}".format(light_intensity))
if light_intensity < 30000: # If light intensity is below a threshold
frequency = 1000 + (30000 - light_intensity) * 0.1 # Adjust frequency based on light intensity
activate_buzzer(frequency, 0.1) # Activate buzzer with the adjusted frequency
else:
buzzer_pwm.duty_u16(0) # Ensure buzzer is off when light intensity is above the threshold
time.sleep(1) # Wait 1 second before the next measurement