from keypad import Keypad
from ssd1306 import SSD1306_I2C
from machine import Pin, PWM, I2C
import time
secretCode = '24861694'
isLocked = False
inbuffer = "--------"
guesses = 0
countDown = 59
led1 = Pin('GP15', Pin.OUT)
led2 = Pin('GP14', Pin.OUT)
pwm = PWM('GP16', freq = 50)
i2c = I2C(0, sda=Pin('GP0'), scl=Pin('GP1')) # Set up I2C
display = SSD1306_I2C(128, 64, i2c) # Create display 128x64 pixels
buzzer = PWM('GP9')
attempt = 1
led1.off()
led2.on()
def keyPressed(keyValue):
global isLocked, inbuffer, guesses # Global variables are stored between function calls
if isLocked:
if keyValue == '#': # User is trying to unlock
if inbuffer == secretCode: # Success only if the code matches
isLocked = False
led1.off()
guesses = 0
buzzer.freq(1000)
buzzer.duty_u16(30000)
for i in range(5):
led2.on()
time.sleep(0.2)
led2.off()
time.sleep(0.2)
led2.on()
buzzer.duty_u16(0)
else:
buzzer.freq(400)
buzzer.duty_u16(30000)
for i in range(5):
led1.on()
time.sleep(0.2)
led1.off()
time.sleep(0.2)
led1.on()
guesses += 1
buzzer.duty_u16(0)
inbuffer = "--------" # Wrong code so reset the buffer
else: # New number needs storing in the buffer:
inbuffer = inbuffer[1:] + keyValue # Move buffer to the left and add new value
print(keyValue, end="")
elif keyValue == '*': # Unlocked and '*' pressed so change the
isLocked = True
led2.off()
led1.on() # state to locked.
# Setup keypad object with the correct pins and with keyPressed() as the callback function
kp = Keypad(rows = (Pin(28), Pin(27), Pin(26), Pin(22)),
columns = (Pin(21), Pin(20), Pin(19), Pin(18)),
callback = keyPressed)
while True:
if isLocked == True:
pwm.duty_u16(4825)
elif isLocked == False:
pwm.duty_u16(1600)
if guesses != 5:
if isLocked == True:
display.fill(0)
#display.circle(23,31,12,12,1,True)
#display.rect(12,30,23,5,0,True)
display.text(inbuffer, 40, 20)
display.text("Locked",45,38)
display.text(f"Incorrect: {guesses}/5", 15, 50)
display.show()
time.sleep(0.05)
else:
display.fill(0)
display.text("Unlocked", 35, 35)
display.show()
time.sleep(0.05)
else:
buzzer.freq(400)
buzzer.duty_u16(30000)
display.fill(0)
display.text(str(countDown * attempt), 40, 20)
display.show()
time.sleep(1)
countDown -= 1
if countDown == 0:
guesses = 0
buzzer.duty_u16(0)
attempt += 1