print("Patient Fall Detection System")
print("Date: 16/4/2026")
print ("MUHAMMAD IDHAM BIN TAJUDIN")
# IMPORT LIBRARIES
from machine import Pin, SoftI2C, PWM, SPI
import time, math
import oled_lib
import mpu6050
from mfrc522 import MFRC522
# I2C SETUP
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
# PIN DECLARATION
green_led = Pin(18, Pin.OUT)
red_led = Pin(19, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_UP)
pir = Pin(34, Pin.IN)
# buzzer
buzzer = PWM(Pin(15))
buzzer.duty(0) # start OFF
# Relay module
relay = Pin(23, Pin.OUT)
relay.off()
# OBJECT
sensor = mpu6050.accel(i2c)
screen = oled_lib.SSD1306_I2C(128, 64, i2c)
# RFID SETUP
rdr = MFRC522(spi_id=1, sck=25, mosi=26, miso=27, cs=32, rst=33)
# SETTINGS
THRESHOLD = 2.5
fall_detected = False
bed_name = None
# RFID MAPPING
RFID_MAP = {
"a1b2c3d4": "Bed 1" #kod gelang RFID
}
# FUNCTIONS
def normal_state():
green_led.on()
red_led.off()
buzzer.duty(0)
relay.off()
screen.fill(0)
screen.text("Bed 1 SAFE", 25, 25)
screen.show()
print("Relay OFF - Bed 1 SAFE")
def fall_screen():
green_led.off()
red_led.on()
relay.on()
screen.fill(0)
screen.text("Bed 1 FALL!", 20, 20)
screen.text("DETECTED", 25, 40)
if bed_name:
screen.text(bed_name, 35, 55)
screen.show()
print("Relay ON - Bed 1 FALL DETECTED")
if bed_name:
print("Fall at:", bed_name)
def beep():
buzzer.freq(1000)
buzzer.duty(512) # ON
time.sleep(0.2)
buzzer.duty(0) # OFF
time.sleep(0.2)
def reset_system():
global fall_detected, bed_name
fall_detected = False
bed_name = None
buzzer.duty(0)
relay.off()
print("SYSTEM RESET - Bed 1")
print("Relay OFF")
# INITIAL DISPLAY
normal_state()
# MAIN LOOP
while True:
# READ MPU6050
data = sensor.get_values()
ax = data["AcX"] / 16384
ay = data["AcY"] / 16384
az = data["AcZ"] / 16384
accel = math.sqrt(ax**2 + ay**2 + az**2)
# Rotation (Gyroscope)
gx = data["GyX"] / 131
gy = data["GyY"] / 131
gz = data["GyZ"] / 131
# Temperature
temp = (data["Tmp"] / 340.0) + 36.53
# Print to Serial Monitor
print("Acceleration:", accel)
print("Rotation:", gx, gy, gz)
print("Temperature:", temp)
# READ PIR SENSOR
if pir.value() == 1:
print("Patient Moving detected!")
screen.fill(0)
screen.text("Patient Moving", 15, 30)
screen.show()
time.sleep(0.5)
# FALL DETECTION
if accel > THRESHOLD and not fall_detected:
fall_detected = True
print("FALL DETECTED - Bed 1")
# RFID read
uid = rdr.get_id()
if uid:
bed_name = RFID_MAP.get(uid, "Unknown Bed")
print("RFID detected:", uid, "->", bed_name)
if fall_detected:
fall_screen(); beep()
else:
normal_state()
if button.value() == 0:
reset_system(); time.sleep(0.5)
time.sleep(0.1)Loading
mfrc522
mfrc522