import time
import board
import digitalio
import pwmio
# Initialize components
# Ultrasonic Sensor
trigger = digitalio.DigitalInOut(board.GP2)
trigger.direction = digitalio.Direction.OUTPUT
echo = digitalio.DigitalInOut(board.GP3)
echo.direction = digitalio.Direction.INPUT
# LED
led = digitalio.DigitalInOut(board.GP15)
led.direction = digitalio.Direction.OUTPUT
# Pushbutton
button = digitalio.DigitalInOut(board.GP10)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.DOWN # Internal pull-down resistor
# Servo Motor
servo_pwm = pwmio.PWMOut(board.GP20, frequency=50)
servo_angle = 0 # Track the current angle of the servo
# DHT22 Sensor
class DHT22Sensor:
def __init__(self, pin):
self.pin = pin
def read_temperature(self):
try:
# Simulate reading the temperature directly from the sensor
return float(input("Enter temperature (°C): "))
except ValueError:
return None
def read_humidity(self):
try:
# Simulate reading the humidity directly from the sensor
return float(input("Enter humidity (%): "))
except ValueError:
return None
dht = DHT22Sensor(board.GP4)
# Function to read ultrasonic distance
def read_ultrasonic(trigger, echo):
# Send a 10µs pulse to trigger the sensor
trigger.value = True
time.sleep(0.00001) # 10 microseconds
trigger.value = False
# Measure the time for the echo to return
start_time = time.monotonic()
while not echo.value: # Wait for the pulse to start
if time.monotonic() - start_time > 0.1: # Timeout after 100ms
return None
pulse_start = time.monotonic()
while echo.value: # Wait for the pulse to end
if time.monotonic() - pulse_start > 0.1: # Timeout after 100ms
return None
pulse_end = time.monotonic()
pulse_duration = pulse_end - pulse_start
# Calculate distance in cm (speed of sound = 343m/s)
distance = (pulse_duration * 34300) / 2
return distance
# Function to set servo angle
def set_servo_angle(pwm, angle):
duty_cycle = int((angle / 180.0) * (2**16 - 1)) # Map angle to duty cycle
pwm.duty_cycle = duty_cycle
# Main loop
print("Starting Smart Room Monitoring System...")
button_pressed = False
while True:
# Read ultrasonic distance
distance = read_ultrasonic(trigger, echo)
if distance is not None:
print(f"Distance: {distance:.2f} cm")
# Control LED based on distance
led.value = distance < 10 # Turn on LED if distance < 10 cm
else:
print("Ultrasonic sensor timeout. No valid reading.")
# Read temperature and humidity from DHT22 sensor
temperature = dht.read_temperature()
humidity = dht.read_humidity()
if temperature is not None and humidity is not None:
print(f"Temperature: {temperature:.2f}°C, Humidity: {humidity:.2f}%")
else:
print("DHT22 sensor error. Please provide valid inputs.")
# Check pushbutton to toggle servo motor
if button.value and not button_pressed:
servo_angle = 180 if servo_angle == 0 else 0
set_servo_angle(servo_pwm, servo_angle)
print(f"Servo moved to {servo_angle}°")
button_pressed = True
if not button.value:
button_pressed = False
# Add a short delay for stability
time.sleep(1)