import machine
import time
from machine import Pin, PWM, I2C
import ssd1306
# ===== إعدادات الأجهزة =====
SERVO_PIN = 18
I2C_SDA = 21
I2C_SCL = 22
ROW_PINS = [13, 12, 14, 27] # صفوف الكيبورد
COL_PINS = [26, 25, 33, 32] # أعمدة الكيبورد
# ===== I2C والشاشة =====
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA))
display = ssd1306.SSD1306_I2C(128, 64, i2c)
# ===== السيرفو =====
servo = PWM(Pin(SERVO_PIN), freq=50)
def set_lock(locked):
if locked:
servo.duty(40) # مغلق
else:
servo.duty(90) # مفتوح
# ===== الكيبورد =====
keys = [['1','2','3','A'],
['4','5','6','B'],
['7','8','9','C'],
['*','0','#','D']]
rows = [Pin(p, Pin.OUT) for p in ROW_PINS]
cols = [Pin(p, Pin.IN, Pin.PULL_DOWN) for p in COL_PINS]
# تهيئة الصفوف HIGH
for r in rows:
r.value(1)
def scan_keypad():
for r_idx, row_pin in enumerate(rows):
row_pin.value(0) # تفعيل الصف
for c_idx, col_pin in enumerate(cols):
if col_pin.value() == 1: # زر مضغوط
time.sleep(0.2) # تأخير إلغاء الاهتزاز
while col_pin.value() == 1: pass
row_pin.value(1)
return keys[r_idx][c_idx]
row_pin.value(1) # إلغاء تفعيل الصف
return None
# ===== حفظ وقراءة الكود =====
def save_code(code):
with open('code.txt', 'w') as f:
f.write(code)
def read_code():
try:
with open('code.txt', 'r') as f:
return f.read()
except:
return "1234"
# ===== الشاشة =====
def display_msg(line1, line2="", clear=True):
if clear:
display.fill(0)
display.text(line1, 0, 10)
display.text(line2, 0, 30)
display.show()
# ===== رسم رمز Processor =====
def draw_processor():
display.fill(0)
# إطار المعالج
display.rect(30, 10, 70, 40, 1)
# دائرة المعالج الداخلية
display.rect(50, 25, 20, 15, 1)
# خطوط اتصالات على اليمين واليسار
for y in range(15, 55, 10):
display.line(30, y, 20, y, 1) # يسار
display.line(100, y, 110, y, 1) # يمين
display.show()
# ===== إدخال الكود =====
def input_code():
display_msg("Enter Code:", "[____]")
res = ""
while len(res) < 4:
key = scan_keypad()
if key and '0' <= key <= '9':
res += key
stars = "*" * len(res) + "_" * (4 - len(res))
display_msg("Enter Code:", "[" + stars + "]")
time.sleep(0.1)
return res
# ===== المتغيرات =====
secret_code = read_code()
is_locked = True
set_lock(True)
# ===== عرض Processor =====
draw_processor()
time.sleep(2)
display_msg("Safe Ready", "Enter Code")
# ===== الحلقة الرئيسية =====
while True:
if is_locked:
user_attempt = input_code()
if user_attempt == secret_code:
display_msg("GRANTED", "Welcome!")
set_lock(False)
is_locked = False
time.sleep(2)
else:
display_msg("DENIED!", "Try again")
time.sleep(2)
else:
display_msg("UNLOCKED", "#:Lock A:Code")
while not is_locked:
key = scan_keypad()
if key == '#':
is_locked = True
set_lock(True)
display_msg("LOCKING...", "")
time.sleep(1)
elif key == 'A':
display_msg("New Code:", "")
secret_code = input_code()
save_code(secret_code)
display_msg("Saved!", "")
time.sleep(2)
display_msg("UNLOCKED", "#:Lock A:Code")
time.sleep(0.1)