# ==========================================
# Semester 1 Project: Smart Entry System
# ESP32 Board 1: Sensor Reading & Servo Control
# ==========================================
# --- Importing Libraries ---
import dht
from machine import Pin, UART, ADC, time_pulse_us, PWM
import time
import network
import BlynkLib
# --- WiFi & Blynk Configuration ---
BLYNK_TEMPLATE_ID = "TMPL2NokFB3pV"
BLYNK_TEMPLATE_NAME = "Semester 1 Project"
BLYNK_AUTH_TOKEN = "HbMWKl1LSSoHtIDc8Oa6pgVtcNlh7NEX"
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# --- Network Initialization ---
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.1)
print("WiFi Connected!")
# --- Blynk Initialization ---
blynk = BlynkLib.Blynk(BLYNK_AUTH_TOKEN, insecure=True)
@blynk.on("connected")
def on_blynk_connected():
print("Successfully connected to Blynk server")
# --- Hardware Setup & Pin Assignments ---
# 1. DHT22 Sensor (Temperature & Humidity)
dht_sensor = dht.DHT22(Pin(32))
# 2. UART Communication (To ESP32 Board 2)
# Using UART 1, TX on Pin 17, RX on Pin 16
uart_conn = UART(1, baudrate=9600, tx=Pin(17), rx=Pin(16), timeout=1000, timeout_char=100)
# 3. MQ-2 Gas Sensor
gas_sensor_digital = Pin(25, Pin.IN) # Optional: if using digital output
gas_sensor_analog = ADC(Pin(34))
gas_sensor_analog.atten(ADC.ATTN_11DB) # Read full range up to 3.3V
# 4. HC-SR04 Ultrasonic Sensor
ultrasonic_echo = Pin(14, Pin.IN)
ultrasonic_trig = Pin(12, Pin.OUT)
# 5. Alert LED
alert_led = Pin(4, Pin.OUT)
# 6. Servo Motors (Lock and Door)
servo_lock = PWM(Pin(2), freq=50)
servo_door = PWM(Pin(18), freq=50)
# --- System Thresholds ---
DISTANCE_THRESHOLD_CM = 30
GAS_THRESHOLD_VALUE = 2500
TEMP_THRESHOLD_C = 30 # Currently unused in logic, but good to have
HUMIDITY_THRESHOLD_PCT = 40 # Currently unused in logic, but good to have
# --- Helper Functions ---
def set_lock_servo(angle):
"""Controls the lock servo motor angle (0-180 degrees)."""
duty_cycle = int((angle / 180) * 102 + 26)
servo_lock.duty(duty_cycle)
def set_door_servo(angle):
"""Controls the door servo motor angle (0-180 degrees)."""
duty_cycle = int((angle / 180) * 102 + 26)
servo_door.duty(duty_cycle)
def measure_distance_cm():
"""Triggers the ultrasonic sensor and returns distance in cm."""
ultrasonic_trig.value(0)
time.sleep_us(2)
ultrasonic_trig.value(1)
time.sleep_us(10)
ultrasonic_trig.value(0)
# Calculate duration of the echo pulse
duration_us = time_pulse_us(ultrasonic_echo, 1)
# Speed of sound is approx 343 m/s or 0.034 cm/us
distance_cm = (duration_us * 0.034) / 2
return distance_cm
# Initialize servos to closed position (0 degrees)
set_lock_servo(0)
set_door_servo(0)
# Track the last time sensors were read to avoid flooding
last_reading_time = time.ticks_ms()
# ==========================================
# --- Main Control Loop ---
# ==========================================
print("Starting main loop...")
while True:
blynk.run()
# Execute sensor readings every 250 ms
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_reading_time) >= 250:
last_reading_time = current_time
try:
# --- 1. Read Sensors ---
current_distance = measure_distance_cm()
current_gas_level = gas_sensor_analog.read()
dht_sensor.measure()
current_temp = dht_sensor.temperature()
current_humidity = dht_sensor.humidity()
# --- 2. Process Logic & Determine States ---
# Initialize state variables
is_door_open = False
door_status_text = "Closed"
numeric_door_state = 0
numeric_gas_leak_state = 0
numeric_object_near_state = 0
# Gas Leak Logic
if current_gas_level > GAS_THRESHOLD_VALUE:
alert_led.on()
numeric_gas_leak_state = 1
else:
alert_led.off()
numeric_gas_leak_state = 0
# Object Proximity Logic
if current_distance < DISTANCE_THRESHOLD_CM:
numeric_object_near_state = 1
else:
numeric_object_near_state = 0
# Door Opening Logic (Opens if object is near OR gas leak detected)
if numeric_object_near_state == 1 or numeric_gas_leak_state == 1:
is_door_open = True
# Actuate Servos based on Door State
if is_door_open:
set_lock_servo(80)
set_door_servo(80)
numeric_door_state = 1
door_status_text = "Open"
else:
set_lock_servo(0)
set_door_servo(0)
numeric_door_state = 0
door_status_text = "Closed"
# --- 3. Communication & Debugging ---
# Print readings to console
print("Temp: {:.1f}C | Hum: {:.1f}% | Dist: {:.1f}cm | Gas: {}".format(
current_temp, current_humidity, current_distance, current_gas_level))
print("Door Open:", is_door_open)
# Send Data via UART to ESP32 Board 2 (CSV Format)
# Format: Temp, Humidity, ObjectNear(0/1), DoorState(0/1), GasLeak(0/1)
uart_msg = "{:.1f},{:.1f},{},{},{}\n".format(
current_temp,
current_humidity,
numeric_object_near_state,
numeric_door_state,
numeric_gas_leak_state
)
uart_conn.write(uart_msg)
print("UART Sent:", uart_msg.strip())
print("-" * 30)
# Send Data to Blynk Dashboard
blynk.virtual_write(0, door_status_text)
blynk.virtual_write(1, current_gas_level)
blynk.virtual_write(2, numeric_gas_leak_state)
blynk.virtual_write(3, current_temp)
blynk.virtual_write(4, current_humidity)
except Exception as e:
print("Error reading sensors or sending data:", e)