# main.py corrigé — MicroPython pour ESP32
from machine import Pin, I2C
from time import sleep
from ssd1306 import SSD1306_I2C
from servo import Servo
from keypad import Keypad4x4
# ----------------------
# Pins (mapping stable)
# ----------------------
# I2C OLED
I2C_SDA = 4
I2C_SCL = 16
# Capteur & LEDs & buzzer & servo
PIR_PIN = 25 # entrée PIR
LED_PIN = 26 # LED verte
BUZZER_PIN= 27 # buzzer (GPIO digital)
SERVO_PIN = 14 # servo signal
# Keypad pins (choisies pour être sûres et non input-only)
ROWS_PINS = (32, 33, 5, 18) # sorties
COLS_PINS = (12, 13, 19, 23) # entrées (avec pull-down)
# ----------------------
# Init matos
# ----------------------
# OLED
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA))
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)
# PIR, LED, buzzer, servo
pir = Pin(PIR_PIN, Pin.IN)
led = Pin(LED_PIN, Pin.OUT)
buzzer = Pin(BUZZER_PIN, Pin.OUT)
servo = Servo(Pin(SERVO_PIN))
# Keypad (on passe rows, cols et la matrice des touches)
rows = [Pin(p, Pin.OUT) for p in ROWS_PINS]
cols = [Pin(p, Pin.IN, Pin.PULL_DOWN) for p in COLS_PINS]
keys = [
['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']
]
keypad = Keypad4x4(rows, cols, keys)
# ----------------------
# Variables
# ----------------------
CODE = "1111"
saisie = ""
OUVERT_ANGLE = 90
FERME_ANGLE = 0
# ----------------------
# Fonctions utilitaires
# ----------------------
def affiche(msg, y=20):
oled.fill(0)
oled.text(msg, 0, y)
oled.show()
def alarme():
affiche("CODE INCORRECT")
for _ in range(5):
buzzer.value(1)
sleep(0.2)
buzzer.value(0)
sleep(0.2)
def ouvrir_porte():
affiche("ACCES AUTORISE")
servo.write_angle(OUVERT_ANGLE)
sleep(2)
servo.write_angle(FERME_ANGLE)
# ----------------------
# Programme principal
# ----------------------
# Affiche de départ
affiche("Systeme pret")
servo.write_angle(FERME_ANGLE)
while True:
if pir.value() == 1:
led.value(1)
affiche("Personne detectee")
sleep(0.5)
affiche("Entrez code :")
saisie = ""
# on attend 4 touches (on pourrait aussi attendre '#' pour valider)
while True:
key = keypad.get_key()
if key:
# reset si '*' appuyé
if key == '*':
saisie = ""
affiche("Reset")
sleep(0.4)
affiche("Entrez code :")
continue
# si '#' on valide tout de suite
if key == '#':
break
# sinon on ajoute au code
if len(saisie) < 8: # limite de sécurité
saisie += key
affiche("*" * len(saisie))
sleep(0.2)
# si on a déjà 4 chiffres on peut sortir automatiquement
if len(saisie) >= 4:
break
# validation
if saisie == CODE:
ouvrir_porte()
else:
alarme()
affiche("Systeme pret")
# petite pause pour éviter rebonds immédiats
sleep(1)
else:
led.value(0)
sleep(0.1)