#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
#define BUZZER_PIN 23 // Chân kết nối còi báo
#define LDR_PIN 34 // Chân kết nối cảm biến ánh sáng (LDR)
#define led1 25 // LED đỏ
#define led2 26 // LED xanh lá
#define led3 27 // LED xanh dương
const float GAMMA = 0.7;
const float RL10 = 33;
// Cấu hình WiFi và MQTT
const char *ssid = "Wokwi-GUEST";
const char *password = "";
const char *mqtt_server = "test.mosquitto.org";
const int mqtt_port = 1883;
const char *topic_led = "21004171/output"; // Chủ đề MQTT cho LED
const char *topic_lcd = "21004171/lcd"; // Chủ đề MQTT cho LCD
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
// Kết nối WiFi
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
// Kết nối lại MQTT nếu mất kết nối
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("Connected to MQTT broker");
client.subscribe(topic_led); // Đăng ký lắng nghe chủ đề LED
client.subscribe(topic_lcd); // Đăng ký lắng nghe chủ đề LCD
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(1000);
}
}
}
// Xử lý tin nhắn từ MQTT
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Message: ");
Serial.println(message);
// Điều khiển LED
if (strcmp(topic, topic_led) == 0) {
if (message == "1") {
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
Serial.println("LED1 ON");
} else if (message == "2") {
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
Serial.println("LED2 ON");
} else if (message == "3") {
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
Serial.println("LED3 ON");
} else {
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
Serial.println("All LEDs OFF");
}
}
// Hiển thị thông báo lên LCD
if (strcmp(topic, topic_lcd) == 0) {
lcd.setCursor(0, 2);
lcd.print("Message: ");
lcd.setCursor(0, 3);
lcd.print(message);
}
}
void setup() {
pinMode(BUZZER_PIN, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
Serial.begin(115200);
lcd.init();
lcd.backlight();
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback); // Cấu hình hàm callback cho MQTT
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
// Đọc giá trị ánh sáng từ LDR
int analogValue = analogRead(LDR_PIN);
float voltage = analogValue / 4096.0 * 3.3;
float resistance = 2000 * voltage / (1 - voltage / 3.3);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Hiển thị giá trị ánh sáng và trạng thái trên LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Lux: ");
lcd.print(lux);
lcd.setCursor(0, 1);
if (lux < 10) {
lcd.print("Very dark");
} else if (lux >= 10 && lux < 50) {
lcd.print("Low light");
} else if (lux >= 50 && lux < 500) {
lcd.print("Dim light");
} else if (lux >= 500 && lux < 1000) {
lcd.print("Ambient light");
} else if (lux >= 1000 && lux < 10000) {
lcd.print("Strong light");
} else {
lcd.print("Very bright");
}
// Bật còi nếu ánh sáng rất sáng (>10.000 lux)
if (lux > 10000) {
digitalWrite(BUZZER_PIN, HIGH);
} else {
digitalWrite(BUZZER_PIN, LOW);
}
// Gửi giá trị ánh sáng lên MQTT
String luxStr = String(lux, 2);
client.publish("/PTIT_Test/p/lux", luxStr.c_str());
// In ra Serial Monitor
Serial.print("Lux: ");
Serial.println(lux);
}
}
// # pip install paho-mqtt==1.6.1
// # pip install mysql-connector-python
// import paho.mqtt.client as mqtt
// import mysql.connector
// from datetime import datetime
// import time
// # Kết nối với MySQL
// def connect_to_mysql():
// return mysql.connector.connect(
// host="localhost", # Thay bằng địa chỉ host của bạn
// user="root", # Thay bằng user MySQL của bạn
// password="", # Thay bằng password của bạn
// database="iot4" # Tên database MySQL của bạn
// )
// # Hàm lưu tin nhắn vào MySQL
// def save_message_to_db(topic, message):
// try:
// conn = connect_to_mysql()
// cursor = conn.cursor()
// query = "INSERT INTO messages (topic, message, received_at) VALUES (%s, %s, %s)"
// cursor.execute(query, (topic, message, datetime.now()))
// conn.commit()
// cursor.close()
// conn.close()
// print(f"Message saved to DB: Topic={topic}, Message={message}")
// except Exception as e:
// print(f"Error saving message to DB: {e}")
// def select_name_type(message):
// try:
// conn = connect_to_mysql()
// cursor = conn.cursor()
// # Truy vấn chỉ trả về một dòng
// query = "SELECT * FROM traffic_signs, sign_type WHERE sign_type.id_sign_type = traffic_signs.id_sign_type and name = %s"
// cursor.execute(query, (message,))
// result = cursor.fetchone() # Lấy một dòng duy nhất
// if result:
// for i in range(len(result)):
// print(f"Value of column {i}: {result[i]}")
// # Cột `name_type` là giá trị đầu tiên trong dòng trả về
// name_type = result[11]
// print(f"Value of 'name_type': {name_type}")
// return name_type
// else:
// print("No matching record found.")
// return None
// cursor.close()
// conn.close()
// except Exception as e:
// print(f"Error: {e}")
// # Callback khi kết nối MQTT thành công
// def on_connect(client, userdata, flags, rc):
// if rc == 0:
// print("Connected to MQTT Broker!")
// client.subscribe("21004171/topic") # Thay bằng topic bạn muốn lắng nghe
// else:
// print(f"Failed to connect, return code {rc}")
// # Callback khi nhận tin nhắn
// def on_message(client, userdata, msg):
// print(f"Received message: Topic={msg.topic}, Message={msg.payload.decode()}")
// name_type=select_name_type(msg.payload.decode())
// publish_message(client, "21004171/output", name_type)
// publish_message(client, "21004171/lcd", msg.payload.decode())
// # Hàm gửi tin nhắn
// def publish_message(client, topic, message):
// client.publish(topic, message)
// print(f"Message published: Topic={topic}, Message={message}")
// # Hàm chính luôn chạy
// def main():
// broker = "test.mosquitto.org" # Thay bằng địa chỉ broker của bạn
// #test.mosquitto.org
// port = 1883
// client = mqtt.Client("MQTT_Python_Client")
// client.on_connect = on_connect
// client.on_message = on_message
// while True:
// try:
// # Kết nối đến MQTT broker
// print("Connecting to MQTT Broker...")
// client.connect(broker, port)
// # Chạy MQTT client trong vòng lặp
// client.loop_forever()
// except Exception as e:
// print(f"Error: {e}")
// print("Reconnecting in 5 seconds...")
// time.sleep(5) # Chờ trước khi thử lại
// if __name__ == "__main__":
// main()
// !git clone https://github.com/THU-MIG/yolov10.git
// !mkdir -p /content/yolov10/ultralytics/weights
// !wget -P /content/yolov10/ultralytics/weights -q https://github.com/jameslahm/yolov10/releases/download/v1.0/yolov10n.pt
// !ls -lh /content/yolov10/ultralytics/weights
// # Cài đặt YOLOv10 từ GitHub
// !pip install -q git+https://github.com/ultralytics/ultralytics.git
// from ultralytics import YOLO
// !pip install paho-mqtt==1.6.1
// import paho.mqtt.client as mqtt
// BROKER = "test.mosquitto.org"
// # BROKER = "broker.hivemq.com"
// PORT = 1883
// TOPIC_PUBLISH = "21004171/topic"
// # Hàm gửi tin nhắn qua MQTT
// def publish_message(predicted_label):
// # Thiết lập client MQTT
// client = mqtt.Client()
// client.connect(BROKER, PORT, 60)
// # Gửi nội dung predicted_label lên topic
// client.publish(TOPIC_PUBLISH, predicted_label)
// print(f"Sent message: {predicted_label} to topic: {TOPIC_PUBLISH}")
// # Đóng kết nối
// client.disconnect()
// # Tải model
// model = YOLO("/content/drive/MyDrive/21004289/Results/21004289.pt")
// # Đường dẫn ảnh cần dự đoán
// image_path = "/content/drive/MyDrive/21004289/TrafficSign/test/images/000009_jpg.rf.cc33de74b89146e17af41bc7322b917c.jpg"
// # Thực hiện dự đoán
// results = model.predict(source=image_path, conf=0.25, save=True)
// # Lấy thông tin class từ kết quả
// for result in results:
// for box in result.boxes:
// # Lấy ID class và tên class
// class_id = int(box.cls.cpu().numpy())
// class_name = model.names[class_id]
// print(f"Class detected: {class_name}")
// publish_message(class_name)