#Smart Room with monitoring system
import machine
import ssd1306
import dht
import time
# Pin configuration
dht_pin = machine.Pin(2) # DHT22 Connected To Pin 2
led_pin = machine.Pin(4, machine.Pin.OUT) # LED connected to pin 4
led_pir_pin = machine.Pin(19, machine.Pin.OUT) # LED for PIR motion sensor connected to pin 19 (change as needed)
servo_pin_1 = machine.Pin(5) # Servo motor 1 connected to pin 5
servo_pin_2 = machine.Pin(18) # Servo motor 2 connected to pin 18 (change as needed)
pir_pin = machine.Pin(14, machine.Pin.IN) # PIR motion sensor connected to pin 14
# Create PWM objects for LED and Servo
led_pwm = machine.PWM(led_pin)
led_pir_pwm = machine.PWM(led_pir_pin)
servo_pwm_1 = machine.PWM(servo_pin_1, freq=50) # Specify frequency for servo motor 1 (50Hz is common)
servo_pwm_2 = machine.PWM(servo_pin_2, freq=50) # Specify frequency for servo motor 2 (50Hz is common)
# OLED SSD1306 Configurations
i2c_1 = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21))
oled_1 = ssd1306.SSD1306_I2C(128, 64, i2c_1) # OLED for main display
i2c_2 = machine.I2C(scl=machine.Pin(25), sda=machine.Pin(26)) # Change the pin numbers as needed
oled_2 = ssd1306.SSD1306_I2C(128, 64, i2c_2) # OLED for secondary display
# Create a DHT object
dht_sensor = dht.DHT22(dht_pin)
# Function to turn the servo to a specific angle
def set_servo_angle(servo_pwm, angle):
duty = int(((angle / 180) * 75) + 40) # Convert angle to duty cycle (PWM range: 40-115)
servo_pwm.duty(duty)
# Function to return the servo to the normal position (0 degrees)
def return_servo_to_normal(servo_pwm):
set_servo_angle(servo_pwm, 0)
# Function to hide the secondary OLED display after a delay
def hide_secondary_oled():
oled_2.fill(0)
oled_2.show()
while True:
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
oled_1.fill(0)
oled_1.text("Temperature:", 0, 0)
oled_1.text(str(temperature) + " C", 0, 16)
oled_1.text("Humidity:", 0, 32)
oled_1.text(str(humidity) + " %", 0, 48)
oled_1.show()
# Control LED and Servo 1 based on temperature
if temperature >= 22:
led_pwm.duty(512) # Adjust duty cycle for LED (PWM range: 0-1023)
set_servo_angle(servo_pwm_1, 90) # Turn servo 1 to 90 degrees
elif temperature <= 18:
led_pwm.duty(0) # Turn off the LED
return_servo_to_normal(servo_pwm_1) # Return servo 1 to normal position
# Control Servo 2, LED for PIR sensor, and OLED 2 based on motion detection
if pir_pin.value() == 1: # Motion detected
set_servo_angle(servo_pwm_2, 90) # Open servo 2 to 90 degrees
led_pir_pwm.duty(512) # Turn on LED for PIR sensor
oled_2.fill(0)
oled_2.text("Welcome", 0, 16)
oled_2.show()
else:
return_servo_to_normal(servo_pwm_2) # Close servo 2 to normal position
led_pir_pwm.duty(0) # Turn off LED for PIR sensor
oled_2.text("Goodbye", 0, 16)
oled_2.show()
time.sleep(10) # Wait for 10 seconds
hide_secondary_oled() # Hide the secondary OLED display
except Exception as e:
print("Error:", e)
time.sleep(5)