from machine import Pin, I2C, time_pulse_us
import utime
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
print("Starting System...")
# 📌 ตั้งค่า I2C LCD
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
# 📌 ตั้งค่าพอร์ตของเซ็นเซอร์ Ultrasonic (ด้านนอก และด้านใน)
TRIG_OUT = Pin(5, Pin.OUT)
ECHO_OUT = Pin(18, Pin.IN)
TRIG_IN = Pin(17, Pin.OUT)
ECHO_IN = Pin(19, Pin.IN)
# 📌 ตั้งค่า PIR Sensor
PIR = Pin(4, Pin.IN)
# 📌 ตัวแปรเก็บจำนวนคนในห้อง
counter = 0
DETECTION_RANGE = (20, 380)
# 📌 เก็บเวลาที่เซ็นเซอร์จับวัตถุ
entry_time = None
exit_time = None
def get_distance(trig, echo):
trig.value(1)
utime.sleep_us(10)
trig.value(0)
duration = time_pulse_us(echo, 1, 30000)
distance = (duration * 0.0343) / 2
return distance
lcd.clear()
lcd.putstr("Room Tracker\nStarting...")
while True:
distance_out = get_distance(TRIG_OUT, ECHO_OUT)
distance_in = get_distance(TRIG_IN, ECHO_IN)
pir_motion = PIR.value()
entry_exit_status = "No Movement"
print(f"DEBUG: Outside = {distance_out:.2f} cm, Inside = {distance_in:.2f} cm, PIR Motion = {pir_motion}")
# ✅ ตรวจจับว่ามีคนผ่าน และบันทึกเวลา
if DETECTION_RANGE[0] <= distance_out <= DETECTION_RANGE[1] and entry_time is None:
entry_time = utime.ticks_ms()
print(f"📝 Logged Entry Time: {entry_time}")
if DETECTION_RANGE[0] <= distance_in <= DETECTION_RANGE[1] and exit_time is None:
exit_time = utime.ticks_ms()
print(f"📝 Logged Exit Time: {exit_time}")
# ✅ Debugging: ตรวจสอบค่าที่บันทึกได้
if entry_time and exit_time:
time_diff = abs(utime.ticks_diff(exit_time, entry_time))
print(f"🛠 DEBUG CHECK: Entry Time = {entry_time}, Exit Time = {exit_time}, Time Diff = {time_diff}")
if 0 < time_diff <= 1500:
if entry_time < exit_time:
counter += 1
entry_exit_status = "🔵 Someone Entered"
print(f"{entry_exit_status} - Total Inside: {counter}")
elif exit_time < entry_time:
counter -= 1
counter = max(counter, 0)
entry_exit_status = "🔴 Someone Left"
print(f"{entry_exit_status} - Total Inside: {counter}")
entry_time = None
exit_time = None
# ✅ วิเคราะห์พฤติกรรมในห้อง
if counter > 0 and pir_motion == 1:
room_status = "Active Meeting"
elif counter > 0 and pir_motion == 0:
room_status = "Silent Room"
else:
room_status = "Room Empty"
print(f"People: {counter}, PIR: {pir_motion}, Room: {room_status}, Entry/Exit: {entry_exit_status}")
# ✅ แสดงผลบน LCD
lcd.clear()
lcd.putstr(f"People: {counter}\n{room_status}")
utime.sleep(1)