#include <WiFi.h>
#include "DHTesp.h"
#include <PubSubClient.h>
const int DHT_PIN = 15;
const int PIR_PIN = 14; // Chân GPIO kết nối với cảm biến PIR
const int LED_PIN = 13;
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const char* mqttServer = "mqtt_server_address";
const int mqttPort = 1883;
const char* mqttUser = "mqtt_username";
const char* mqttPassword = "mqtt_password";
const char* mqttTopic = "your_topic"; // Chủ đề MQTT để gửi cảnh báo
const int myChannelNumber = 2261729;
const char* myApiKey = "NN16RYG7XLZ9ALCY";
const char* server = "api.thingspeak.com";
DHTesp dhtSensor;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(PIR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
WiFi.begin(WIFI_NAME, WIFI_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);
// Connect to MQTT server
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword)) {
Serial.println("Connected to MQTT");
client.subscribe(mqttTopic);
} else {
Serial.print("Failed to connect to MQTT, retrying in 5 seconds...");
delay(5000);
}
}
}
void loop() {
client.loop();
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
int motionState = digitalRead(PIR_PIN);
if (motionState == HIGH) {
Serial.println("Motion detected!");
digitalWrite(LED_PIN, HIGH);
sendAlert();
delay(5000); // Delay to avoid multiple alerts in a short time
} else {
digitalWrite(LED_PIN, LOW);
}
delay(10000); // Delay between sensor readings
}
void sendAlert() {
String alertMessage = "Intrusion Detected at " + getTime();
client.publish(mqttTopic, alertMessage.c_str());
}
String getTime() {
// Implement a function to get the current time
// You can use an NTP library or an RTC module
// For example, you can use the "NTPClient" library for NTP time sync
// Replace the implementation below with your time retrieval logic
return "YYYY-MM-DD HH:MM:SS";
}
void callback(char* topic, byte* payload, unsigned int length) {
// Handle incoming MQTT messages if needed
}