import machine
import time
import dht
from machine import Pin, PWM
#DHT22 Setup
#Connect the DHT22 sensor's VCC to 3.3V, GND to GND, and Data pin to GP2
dht_sensor = dht.DHT22(machine.Pin(2))
#Ultrasonic Sensor Setup (HC-SR04)
#Connect the ultrasonic sensor's VCC to 3.3V, GND to GND, Trigger pin to GP28 and Echo pin to GP27
trigger = Pin(28, Pin.OUT)
echo = Pin(27, Pin.IN)
#Servo Motor Setup (SG90)
#Connect the servo's VCC to 3.3V, GND to GND and Signal pin to GP16
#PWM operating frequency
servo = PWM(Pin(16))
servo.freq(50)
#Function to control the servo motor the opeining and closing
#Connect Servo motor signal to GP16
def set_servo_angle(angle):
#Calculate the duty cycle for the servo motor
#Convert angle to duty cycle for PWM signal
#Set the 16-bit duty cycle
duty = 1000 + (angle / 180) * 1000
servo.duty_u16(int(duty * 65535 / 20000))
#Function to calculate distance from the ultrasonic sensor (HC-SR04)
def measure_distance():
#Send a 10 microsecond pulse to trigger the ultrasonic sensor
trigger.low() #Ensure the trigger pin is low
time.sleep_us(2) #Wait for 2 microseconds
trigger.high() #Set the trigger pin high
time.sleep_us(10) #Hold the trigger high for 10 microseconds
trigger.low() #Set the trigger pin low again
#Measure the time it takes for the echo to return
while echo.value() == 0:
pulse_start = time.ticks_us() #Record the time when the pulse was sent
while echo.value() == 1:
pulse_end = time.ticks_us() #Record the time when the pulse returned
#Calculate the duration of the pulse and convert to distance in cm
pulse_duration = pulse_end - pulse_start
distance = (pulse_duration * 0.0343) / 2 #Convert time to distance using the speed of sound
return distance
#Main loop
while True:
#Measure distance using the ultrasonic sensor
distance = measure_distance()
print(f"Distance: {distance} cm") # Print the distance in centimeters
#If the distance is less than 50 cm, open the garage door
if distance < 50: #If object is within 50 cm, open the door
print("Garage door open")
set_servo_angle(90) #Rotate the servo motor to 90 degrees (open door)
else:
print("Garage door closed")
set_servo_angle(0) # Rotate the servo motor back to 0 degrees (close door)
# Read temperature and humidity from the DHT22 sensor
try:
dht_sensor.measure() # Take a reading from the DHT22 sensor
temperature = dht_sensor.temperature() #Get temperature reading in Celsius
humidity = dht_sensor.humidity() #Get humidity reading in percentage
print(f"Temperature: {temperature}C, Humidity: {humidity}%") # Print the readings
except OSError as e:
print("Failed to read sensor data.") #Error handling in case of failure to read from the sensor
time.sleep(2) # Wait for 2 seconds before taking the next reading