#include <Keypad.h>
#include <PubSubClient.h>
#include <WiFi.h>
const char* mqtt_server = "broker.hivemq.com";
const char* MQTT_ID = "f9f4c324-1184-4d0f-a33d-4a561f980ced";
int status = WL_IDLE_STATUS;
int Port = 1883;
int buzzer = 21;
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
uint8_t colPins[COLS] = { 16, 4, 2, 15 };
uint8_t rowPins[ROWS] = { 19, 18, 5, 17 };
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
WiFiClient wifiClient;
PubSubClient client(wifiClient);
String pass = "";
void setup() {
Serial.begin(115200);
pinMode(buzzer, OUTPUT);
WIFIConnect();
client.setServer(mqtt_server, Port);
client.setCallback(callback);
}
void loop() {
delay(10);
if (!client.connected()) {
MQTT_Reconnect();
}
client.loop();
char key = keypad.getKey();
if (key != NO_KEY) {
if (key != '#') {
pass = pass + key;
} else {
gui(pass);
Serial.print(pass);
pass = "";
}
}
}
void WIFIConnect() {
Serial.println("Connecting to SSID: Wokwi-GUEST");
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected");
Serial.print(", IP address: ");
Serial.println(WiFi.localIP());
}
void MQTT_Reconnect() {
while (!client.connected()) {
if (client.connect(MQTT_ID)) {
Serial.println("MQTT connected");
client.subscribe("key");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.println("Message arrived on topic: " + String(topic));
String stMessage;
for (int i = 0; i < length; i++) {
stMessage += (char)message[i];
}
Serial.println("Message: " + stMessage);
if (stMessage == "on") {
digitalWrite(buzzer, HIGH);
delay(200);
digitalWrite(buzzer, LOW);
} else if (stMessage == "off") {
for (int i = 0; i < 3; i++) {
digitalWrite(buzzer, HIGH);
delay(200);
digitalWrite(buzzer, LOW);
}
}
}
void gui(String a) {
client.publish("key", a.c_str());
}