#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <PubSubClient.h>
#define ROW_NUM 4 // four rows
#define COLUMN_NUM 4 // four columns
char keys[ROW_NUM][COLUMN_NUM] = {
{'1','2','3', 'A'},
{'4','5','6', 'B'},
{'7','8','9', 'C'},
{'*','0','#', 'D'}
};
byte pin_rows[ROW_NUM] = {12, 14, 27, 26}; // GPIO19, GPIO18, GPIO5, GPIO17 connect to the row pins
byte pin_column[COLUMN_NUM] = {25, 33, 32, 35}; // GPIO16, GPIO4, GPIO0, GPIO2 connect to the column pins
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM);
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 column and 2 rows
int cursorColumn = 0;
String inputString = "";
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "test.mosquitto.org";
const int mqttPort = 1883;
const char* mqttTopic = "password_topic";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
lcd.init(); // initialize the lcd
lcd.backlight();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("password_client")) {
Serial.println("Connected to MQTT");
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key == '*') {
// Delete the previously typed characters
if (inputString.length() > 0) {
inputString.remove(inputString.length() - 1);
cursorColumn--;
lcd.setCursor(cursorColumn, 0);
lcd.print(" ");
lcd.setCursor(cursorColumn, 0);
}
} else if (key == '#') {
// Check the entered password
if (inputString == "4699") {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Correct password");
delay(2000);
lcd.clear();
publishMessage("Correct password");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Wrong password");
delay(2000);
lcd.clear();
publishMessage("Wrong password");
}
inputString = "";
cursorColumn = 0;
} else {
lcd.setCursor(cursorColumn, 0); // move cursor to (cursorColumn, 0)
lcd.print(key); // print key at (cursorColumn, 0)
inputString += key;
cursorColumn++; // move cursor to next position
if (cursorColumn == 16) { // if reaching limit, clear LCD
lcd.clear();
cursorColumn = 0;
}
}
}
if (!client.connected()) {
reconnect();
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
// Handle incoming MQTT messages, if needed
}
void reconnect() {
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("password_client")) {
Serial.println("Connected to MQTT");
client.subscribe(mqttTopic);
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void publishMessage(const char* message) {
if (client.connected()) {
client.publish(mqttTopic, message);
}
}