from machine import Pin , time_pulse_us , PWM ,UART
import dht ,time
import network
import BlynkLib
#setup ,Initialize pins
#1st , inputs (sensors)
dht_sensor = dht.DHT22(Pin(14))
gas_sensor = Pin(13, Pin.IN, Pin.PULL_UP)
echoPin = Pin(32, Pin.IN)
trigPin = Pin(33, Pin.OUT)
#2nd , outputs(actuators)
led = Pin(23, Pin.OUT)
servo_lock = PWM(Pin(18), freq=50)
servo_door = PWM(Pin(15), freq=50)
#3rd , Define communcation protocols
uart = UART(1, baudrate=9600, tx=Pin(17), rx=Pin(16))
#variables
door_status =0
# Function to measure distance
def measure_distance():
trigPin.off()
time.sleep_us(2)
trigPin.on()
time.sleep_us(10)
trigPin.off()
duration = time_pulse_us(echoPin, 1)
distance = (duration * 0.034) / 2
return distance
#function to change servo angles
def set_angle(angle):
duty = int(((angle)/180 * 2 + 0.5) / 20 * 1023)
return duty
############ Blynk Code : #############
# BLYNK CONFIG
BLYNK_TEMPLATE_ID = "TMPL2X_YzjBW2"
BLYNK_TEMPLATE_NAME = "Smart Home Proj"
BLYNK_AUTH_TOKEN = "XjMmLFt_uZLr2L5YolzPig3C6Hqoxfwv"
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASS)
print("Connecting to WiFi...")
while not wifi.isconnected():
time.sleep(0.2)
print("WiFi Connected!")
blynk = BlynkLib.Blynk(BLYNK_AUTH_TOKEN, insecure=True)
@blynk.on("connected")
def connected():
print("Blynk Connected!")
def send_to_blynk(temp, hum, gas, door):
blynk.virtual_write(2, temp)
blynk.virtual_write(3, hum)
# Warning LED
if gas == 0:
blynk.virtual_write(1, 255)
else:
blynk.virtual_write(1, 0)
# Door Status
if door == 1:
blynk.virtual_write(0, "Open")
else:
blynk.virtual_write(0, "Closed")
#######################################
#Main Loop
while True :
dht_sensor.measure()
temp = dht_sensor.temperature() # °C
hmd = dht_sensor.humidity() # %
gas = gas_sensor.value() #pmm
dist = measure_distance() #cm
#Safety Alert if gas value broke the threshold
if gas ==0:
led.on()
print("⚠ Safety Alert : Gas Leak")
else:
led.off()
#Smart door system (to oprn automatically when it is needed)
if dist <=30:
servo_lock.duty(set_angle(90))
time.sleep(0.3)
servo_door.duty(set_angle(90))
door_status=1
print("door opened")
else :
servo_door.duty(set_angle(0))
time.sleep(0.3)
servo_lock.duty(set_angle(0))
door_status=0
#sending data within uart
msg = "{:.1f},{:.1f},{},{}\n".format(temp, hmd, gas, door_status)
uart.write(msg)
print("Sent:", msg.strip())
blynk.run()
send_to_blynk(temp, hmd, gas, door_status)
time.sleep(0.5) # a new loop every 0.5s