from machine import Pin, PWM, I2C
from hcsr04 import HCSR04
from time import sleep
from wifi_lib import conecta
from umqttsimple import MQTTClient
from definitions import *
# CONSTANTS
KEY_UP = const(0)
KEY_DOWN = const(1)
keys = [['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']]
def angulo(a):
pwmPin.duty((a*(123-24))//180+24)
def init():
for row in range(0,4):
for col in range(0,4):
row_pins[row].value(0)
def scan(row, col):
""" scan the keypad """
# set the current column to high
row_pins[row].value(1)
key = None
# check for keypressed events
if col_pins[col].value() == KEY_DOWN:
key = KEY_DOWN
if col_pins[col].value() == KEY_UP:
key = KEY_UP
row_pins[row].value(0)
# return the key state
return key
sensor = HCSR04(trigger_pin=13, echo_pin=12, echo_timeout_us=1000000)
pwmPin = PWM(Pin(18, Pin.OUT), freq=50)
buzzer = PWM(Pin(23, Pin.OUT), freq=1047)
redLed = Pin(2, Pin.OUT)
greenLed = Pin(4, Pin.OUT)
rows = [14, 27, 26, 25]
cols = [33, 32, 35, 34]
row_pins = [Pin(pin_name, mode=Pin.OUT) for pin_name in rows]
col_pins = [Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN) for pin_name in cols]
print("Initializing")
conecta('Wokwi-GUEST','')
# MQTT Config
mqtt = MQTTClient(mqtt_clientID, mqtt_server, mqtt_port, mqtt_username, mqtt_password)
mqtt.connect()
init()
buzzer.duty(0)
angulo(90)
validPass = 'A52981'
lastEntry = ''
keyDown = False
keyTyped = ''
while True:
#Check keypad for input
for row in range(4):
for col in range(4):
key = scan(row, col)
if key == KEY_DOWN and keyDown == False:
keyDown = True
keyTyped = keys[row][col]
if key == KEY_UP and keyTyped == keys[row][col] and keyDown == True:
keyDown = False
lastEntry += keyTyped
keyTyped = ''
print(lastEntry)
#Check if input valid password
if len(lastEntry) >= 6:
if lastEntry == validPass:
lastEntry = ''
#Open door
angulo(0)
#Buzz sound
buzzer.duty(50)
#Light green led
greenLed.value(1)
#Wait a second
sleep(1)
#Stop buzzer
buzzer.duty(0)
#Turn off green led
greenLed.value(0)
#Now wait for distance sensor input
flag = True
while flag:
distance = sensor.distance_cm()
if (distance < 50):
sleep(1)
distance = sensor.distance_cm()
if (distance < 50):
print("Tailgate detected")
#Tailgate routine
mqtt.publish(f"v1/{mqtt_username}/things/{mqtt_clientID}/data/2", "1")
#Close
angulo(90)
flag = False
else:
#Buzz sound
buzzer.duty(50)
#Light red led
redLed.value(1)
#Wait a second
sleep(1)
#Stop buzzer
buzzer.duty(0)
#Turn off red led
redLed.value(0)
lastEntry = ''