import machine
import dht
import utime
# Define the GPIO pins
pir_sensor = machine.Pin(28, machine.Pin.IN)
dht_sensor = dht.DHT22(machine.Pin(20))
servo_pin = machine.Pin(19)
servo = machine.PWM(servo_pin)
servo.freq(50) # Typical servo motor frequency
# Function to set the servo angle
def set_servo_angle(angle):
duty = int((angle / 180) * 1023 + 102) # Convert angle to duty cycle
servo.duty_u16(duty)
while True:
# Read PIR sensor
if pir_sensor.value() == 1:
print("Motion detected!")
# Read DHT22 sensor
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print("Temperature: {}°C".format(temperature))
print("Humidity: {}%".format(humidity))
# Control the servo based on humidity
if humidity < 60:
print("Humidity is below 40%, turning on the servo motor.")
set_servo_angle(90) # Example angle to turn on the servo motor
else:
print("Humidity is above 40%, turning off the servo motor.")
set_servo_angle(0) # Example angle to turn off the servo motor
except OSError as e:
print("Failed to read DHT22 sensor.")
else:
print("No motion")
set_servo_angle(0) # Turn off the servo motor when no motion is detected
utime.sleep(2) # Wait for 2 seconds before checking again