# Import necessary libraries
import time # Import the time module for sleep functionality
from machine import Pin # Import Pin class from machine module for GPIO control
import dht # Import DHT sensor library
import utime # Import utime module for precise timing
# Set up GPIO pins
PIR_PIN = 17 # Motion sensor pin
DHT_PIN = 4 # DHT22 sensor pin
TRIG_PIN = 20 # Ultrasonic sensor trigger pin
ECHO_PIN = 12 # Ultrasonic sensor echo pin
# Initialize the motion sensor
pir = Pin(PIR_PIN, Pin.IN, Pin.PULL_DOWN)
# Initialize the DHT22 sensor
dht_sensor = dht.DHT22(Pin(DHT_PIN))
# Initialize the ultrasonic sensor
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
print("Starting the program...")
# Function to get distance from ultrasonic sensor
def get_distance():
# Send a 10us pulse to trigger
trig.low()
utime.sleep_us(2)
trig.high()
utime.sleep_us(10)
trig.low()
# Measure the duration of the echo pulse
while echo.value() == 0:
pass
pulse_start = utime.ticks_us()
while echo.value() == 1:
pass
pulse_end = utime.ticks_us()
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
distance = (pulse_duration / 2) / 29.1 # Divide by 29.1 for distance in cm
return distance
try:
# Main program loop
while True:
# Read PIR motion sensor
if pir.value():
print("Motion detected!")
else:
print("No motion.")
# Read DHT22 sensor
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print(f"Temperature: {temperature:.1f}°C, Humidity: {humidity:.1f}%")
except OSError as e:
print("Failed to read from DHT sensor.")
# Read ultrasonic sensor
try:
distance = get_distance()
print(f"Distance: {distance:.2f} cm")
except OSError as e:
print("Failed to read from ultrasonic sensor.")
# Wait 2 seconds before repeating
time.sleep(2)
except KeyboardInterrupt:
print("Program stopped.")