import machine
import time
from machine import Pin, PWM
# Define pin numbers
servo_pin = 2 # Pin for the servo motor
ldr_pin = 34 # Pin for the LDR sensor
ultrasonic_trigger_pin = 13 # Pin for ultrasonic sensor trigger
ultrasonic_echo_pin = 12 # Pin for ultrasonic sensor echo
buzzer_pin = 15 # Pin for the buzzer
led_pin = 14 # Pin for the LED
# Initialize components
servo = machine.PWM(machine.Pin(servo_pin), freq=50)
ldr = machine.ADC(ldr_pin)
ultrasonic_trigger = Pin(ultrasonic_trigger_pin, Pin.OUT)
ultrasonic_echo = Pin(ultrasonic_echo_pin, Pin.IN)
buzzer = Pin(buzzer_pin, Pin.OUT)
led = Pin(led_pin, Pin.OUT)
# Define threshold values
ldr_threshold = 1000 # Adjust as needed
distance_threshold = 50 # Adjust as needed (distance in cm)
# Servo control function
def set_servo_angle(angle):
duty = int((angle / 180) * 1024)
servo.duty(duty)
# Function to check LDR sensor for rain or hot weather
def check_weather():
ldr_value = ldr.read()
if ldr_value < ldr_threshold: # Rainy weather
set_servo_angle(0) # Close window
else: # Hot weather
set_servo_angle(90) # Open window
# Function to check ultrasonic sensor for thief detection
def check_thief():
ultrasonic_trigger.on()
time.sleep_us(10)
ultrasonic_trigger.off()
pulse_start = 0
pulse_end = 0
while ultrasonic_echo.value() == 0:
pulse_start = time.ticks_us()
while ultrasonic_echo.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
distance = (pulse_duration * 0.0343) / 2
if distance < distance_threshold:
set_servo_angle(0) # Close window
buzzer.on() # Activate buzzer
else:
buzzer.off() # Deactivate buzzer
# Main loop
while True:
check_weather() # Check LDR sensor for weather conditions
check_thief() # Check ultrasonic sensor for thief detection
# Update LED status based on window position
if servo.duty() == 0:
led.on() # Window closed, turn on LED
else:
led.off() # Window open, turn off LED
time.sleep(5) # Adjust the sleep duration as needed