# Import necessary libraries
import network
import time
from umqtt.simple import MQTTClient
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import machine
import time
from machine import I2C, Pin, SoftI2C
# define the pin numbers for the rows and columns
rowPins = [26, 27, 14, 12]
colPins = [13, 15, 2]
# Define constants
ROWS = 4
COLS = 3
# define the key map
keys = [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
['*', '0', '#']
]
# Setup GPIO for keypad
row_gpio = [machine.Pin(pin, machine.Pin.IN, machine.Pin.PULL_UP) for pin in rowPins]
col_gpio = [machine.Pin(pin, machine.Pin.OUT) for pin in colPins]
# Set up I2C parameters for the LCD display
I2C_ADDR = 0x27
totalRows = 4
totalColumns = 20
# Create an I2C object for communication with LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-get-access-control-system-demo-tihomir"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "elsys/tihomir/access/control"
# Function to connect to Wi-Fi
def connect_to_wifi():
print("Connecting to Wi-Fi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Function to connect to MQTT broker
def connect_to_mqtt_broker():
connect_to_wifi()
print("Connecting to MQTT server... ", end="")
client.connect()
print("Connected!")
# Function to read from user input on the keypad
def read_keypad():
# Scan the keypad
for col, col_pin in enumerate(col_gpio):
col_pin.value(0)
for row, row_pin in enumerate(row_gpio):
if row_pin.value() == 0:
# Key pressed, return the corresponding character
return keys[row][col]
col_pin.value(1)
return None
# Make code with keypad. Enter and send the code is #
def code_maker():
code = ""
try:
while True:
key = read_keypad()
if key:
print(key)
lcd.putstr(key)
if key == '#':
code += key
break # Exit the loop when '#' is pressed
else:
code += key
time.sleep_ms(165) # Adjust the sleep time as needed
except KeyboardInterrupt:
pass
# Check if the code starts with '*', remove it if true
if code.startswith('*'):
code = code[1:]
return code
# Initial print on the display
def initPrint():
lcd.clear()
lcd.putstr("Press key to send\ncode!# - send\n")
# Type code and then send it with MQTT
def make_and_send_message():
print("Enter code:")
code = code_maker()
print("Code: " + code)
time.sleep(1)
lcd.clear()
client.publish(MQTT_TOPIC, code)
lcd.putstr("Sent!\nCode: {}".format(code))
time.sleep(1)
initPrint()
# Startup
lcd.putstr("Hello! :)\nLoading...")
# Set up MQTT client
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
connect_to_mqtt_broker()
initPrint()
try:
while True:
make_and_send_message()
except KeyboardInterrupt:
pass