#include <WiFi.h>
#include <PubSubClient.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);
#define buzz 27
const char * MQTTServer = "broker.emqx.io";
const char * MQTT_Topic = "PTUDIOT/buzzer";
// Tạo ID ngẫu nhiên tại: https://www.guidgen.com/
const char * MQTT_ID = "19eca5f8-7e56-48a3-ab64-6cf33a133392";
int Port = 1883;
int password = 8005;
WiFiClient espClient;
PubSubClient client(espClient);
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.print("MQTT Topic: ");
Serial.print(MQTT_Topic);
Serial.print(" connected");
client.subscribe(MQTT_Topic);
Serial.println("");
} 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.print("Message arrived on topic: ");
Serial.println(topic);
Serial.print("Message: ");
String stMessage;
lcd.clear();
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
stMessage += (char)message[i];
}
lcd.setCursor(0, 0);
password= stMessage.toInt();
delay(1000);
}
const int row = 4;
const int col = 4;
char keys[row][col] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins [row] = {14,12,19,18};
byte colPins [col] = {5,4,2,15};
Keypad customKeypad = Keypad ( makeKeymap(keys), rowPins, colPins, row, col);
char customKey;
int number = 0;
void setup() {
Serial.begin(9600);
WIFIConnect();
client.setServer(MQTTServer, Port);
client.setCallback(callback);
pinMode(buzz, OUTPUT);
lcd.init();
lcd.setBacklight(HIGH);
}
void loop() {
delay(10);
if (!client.connected()) {
MQTT_Reconnect();
}
client.loop();
lcd.setCursor (0,0);
lcd.print("Input Password");
customKey = customKeypad.getKey();
switch(customKey){
case '0'...'9':
lcd.setCursor(0,1);
number = number * 10 + (customKey - '0');
lcd.print(number);
break;
case '#':
if (number == password){
lcd.clear();
lcd.setCursor(0,1);
lcd.print("OK");
delay(1000);
tone(buzz,1000);
delay(50);
noTone(buzz);
} else {
lcd.clear();
lcd.setCursor(0,1);
lcd.print("wrong");
delay(2000);
}
break;
case '*':
lcd.clear();
lcd.setCursor(0,1);
number=0;
break;
}
}