from keypad import Keypad
from machine import Pin, PWM, I2C
from ssd1306 import SSD1306_I2C
import time
# Initialize I2C for OLED display
i2c = I2C(1, sda=Pin('GP6'), scl=Pin('GP15'))
display = SSD1306_I2C(128, 64, i2c)
# Secret code and lock state variables
secretCode = '23668195'
isLocked = False
inbuffer = "--------"
# Setup PWM for some lock mechanism (like servo motor or similar)
pwm = PWM(Pin('GP27'), freq=50)
print("State = UNLOCKED")
# Function to update OLED display based on lock status
def updateDisplay():
display.fill(0) # Clear the display
display.text("LOCKED" if isLocked else "UNLOCKED", 40, 30) # Display status in the middle of the screen
display.show() # Update the display with new content
# Function to handle key press events
def keyPressed(keyValue):
global isLocked, inbuffer
if isLocked:
if keyValue == '#': # User is trying to unlock
if inbuffer == secretCode: # Success only if the code matches
isLocked = False
print(" - Correct, State = UNLOCKED")
pwm.duty_u16(8050) # Unlock mechanism (example: servo motor action)
else:
print(" - Incorrect code.")
inbuffer = "--------" # Reset the buffer after a code attempt
else: # Add key to the input buffer
inbuffer = inbuffer[1:] + keyValue # Shift buffer and append new key
print(keyValue, end="")
elif keyValue == '*': # Unlocked and '*' pressed so change the state to locked
isLocked = True
print("State = LOCKED")
pwm.duty_u16(4825) # Lock mechanism (example: servo motor action)
# Update the display with the current lock state
updateDisplay()
# Setup keypad object with the correct pins and with keyPressed() as the callback function
kp = Keypad(rows=(Pin(26), Pin(22), Pin(21), Pin(20)),
columns=(Pin(19), Pin(18), Pin(17), Pin(16)),
callback=keyPressed)
# Initial display update
updateDisplay()