#include <WiFi.h>
#include "PubSubClient.h"
const char *MQTTServer = "broker.emqx.io"; // Địa chỉ MQTT broker
const char *MQTT_Topic = "dengiaothong"; // Todengiaothongpic để điều khiển LED
const char *MQTT_ID = "d4d3d2cd-773c-4c21-badc-7083063c02eb"; // ID của client MQTT
int Port = 1883; // Cổng của MQTT broker
WiFiClient espClient;
PubSubClient client(espClient);
// Định nghĩa chân LED
const int ledPin = 5; // Chân GPIO kết nối với LED
// Kết nối WiFi
void WIFIConnect() {
Serial.println("Connecting to WiFi...");
WiFi.begin("Wokwi-GUEST", ""); // Kết nối với mạng WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
// Kết nối lại với MQTT server nếu mất kết nối
void MQTT_Reconnect() {
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
if (client.connect(MQTT_ID)) {
Serial.println("MQTT connected");
client.subscribe(MQTT_Topic); // Đăng ký nhận tin nhắn từ topic
Serial.print("Subscribed to topic: ");
Serial.println(MQTT_Topic);
} else {
Serial.print("Failed to connect, rc=");
Serial.print(client.state());
Serial.println(" retrying in 5 seconds...");
delay(5000);
}
}
}
// Hàm xử lý tin nhắn nhận được từ MQTT
void callback(char *topic, byte *message, unsigned int length) {
String receivedMessage;
for (unsigned int i = 0; i < length; i++) {
receivedMessage += (char)message[i];
}
Serial.print("Message received on topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println(receivedMessage);
// Điều khiển LED dựa trên tin nhắn nhận được
if (receivedMessage == "on") {
digitalWrite(ledPin, HIGH); // Bật LED
Serial.println("LED ON");
} else if (receivedMessage == "off") {
digitalWrite(ledPin, LOW); // Tắt LED
Serial.println("LED OFF");
} else {
Serial.println("Invalid message received");
}
}
void setup() {
Serial.begin(115200);
WIFIConnect(); // Kết nối WiFi
client.setServer(MQTTServer, Port); // Cấu hình MQTT server
client.setCallback(callback); // Đặt callback để xử lý tin nhắn
pinMode(ledPin, OUTPUT); // Cấu hình chân LED
digitalWrite(ledPin, LOW); // Đảm bảo LED tắt khi bắt đầu
}
void loop() {
if (!client.connected()) {
MQTT_Reconnect(); // Nếu mất kết nối, thử kết nối lại
}
client.loop(); // Xử lý các tin nhắn MQTT đến
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Control with MQTT</title>
<script src="https://cdn.jsdelivr.net/npm/mqtt/dist/mqtt.min.js"></script> <!-- Thư viện MQTT.js -->
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.control-panel {
text-align: center;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
}
.btn {
font-size: 20px;
padding: 15px 30px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 10px;
}
.btn:hover {
background-color: #0056b3;
}
#status {
font-size: 18px;
color: #333;
}
</style>
</head>
<body>
<div class="control-panel">
<h1>LED Control</h1>
<button class="btn" id="onButton">Turn LED ON</button>
<button class="btn" id="offButton">Turn LED OFF</button>
<div id="status">LED is OFF</div>
</div>
<script>
// Thiết lập MQTT
const mqttBroker = "wss://broker.emqx.io:8084/mqtt"; // Địa chỉ MQTT broker (websocket)
const topic = "dengiaothong"; // Topic điều khiển LED
const clientId = "web-client-" + Math.random().toString(16).substr(2, 8); // Tạo ID client
// Kết nối MQTT
const client = mqtt.connect(mqttBroker, {
clientId: clientId,
clean: true,
connectTimeout: 4000,
reconnectPeriod: 1000,
});
client.on("connect", () => {
console.log("Connected to MQTT broker!");
});
client.on("error", (err) => {
console.log("Error: " + err);
});
client.on("message", (topic, message) => {
console.log("Message received: " + message.toString());
// Cập nhật trạng thái LED
const statusElement = document.getElementById("status");
if (message.toString() === "on") {
statusElement.innerText = "LED is ON";
} else if (message.toString() === "off") {
statusElement.innerText = "LED is OFF";
}
});
// Đăng ký vào topic MQTT
client.on("connect", () => {
client.subscribe(topic, (err) => {
if (!err) {
console.log("Subscribed to topic: " + topic);
}
});
});
// Xử lý sự kiện khi nhấn nút bật LED
document.getElementById("onButton").addEventListener("click", () => {
client.publish(topic, "on"); // Gửi tin nhắn "on" để bật LED
console.log("LED ON");
});
// Xử lý sự kiện khi nhấn nút tắt LED
document.getElementById("offButton").addEventListener("click", () => {
client.publish(topic, "off"); // Gửi tin nhắn "off" để tắt LED
console.log("LED OFF");
});
</script>
</body>
</html>