#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
// ==================== KHAI BÁO CHÂN GPIO ====================
// Chân điều khiển LED
#define LED_PIN 25
// Chân kết nối cảm biến DHT22
#define DHT_PIN 4
// Chân nhận tín hiệu từ cảm biến PIR
#define PIR_PIN 27
// Chân giao tiếp I2C của LCD
#define I2C_SDA 21
#define I2C_SCL 22
// Loại cảm biến DHT
#define DHT_TYPE DHT22
// ==================== CẤU HÌNH WIFI ====================
// Thông tin Wi-Fi mô phỏng của Wokwi
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
// ==================== CẤU HÌNH HTTP ====================
// Endpoint HTTP GET
const char* GET_URL = "https://postman-echo.com/get";
// Endpoint HTTP POST
const char* POST_URL = "https://postman-echo.com/post";
// ==================== KHỞI TẠO THIẾT BỊ ====================
// Khởi tạo cảm biến DHT22
DHT dht(DHT_PIN, DHT_TYPE);
// Khởi tạo LCD 16x2 với địa chỉ I2C 0x27
LiquidCrystal_I2C lcd(0x27, 16, 2);
// ==================== BIẾN TOÀN CỤC ====================
// Chu kỳ đọc dữ liệu cảm biến (2 giây)
const unsigned long READ_INTERVAL = 2000;
// Lưu thời điểm đọc dữ liệu gần nhất
unsigned long previousReadTime = 0;
// Lưu nhiệt độ và độ ẩm
float temperature = 0;
float humidity = 0;
// Lưu trạng thái chuyển động trước đó
int previousMotionState = -1;
// ==================== KẾT NỐI WIFI ====================
bool connectWiFi() {
Serial.println();
Serial.println("[WiFi] Connecting to WiFi...");
// Thiết lập chế độ kết nối Wi-Fi
WiFi.mode(WIFI_STA);
// Bắt đầu kết nối Wi-Fi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
int timeout = 0;
// Chờ kết nối tối đa 15 giây
while (WiFi.status() != WL_CONNECTED && timeout < 30) {
delay(500);
Serial.print(".");
timeout++;
}
// Kiểm tra kết nối thành công
if (WiFi.status() == WL_CONNECTED) {
Serial.println();
Serial.println("[WiFi] Connected successfully!");
// In địa chỉ IP được cấp cho ESP32
Serial.print("[WiFi] IP Address: ");
Serial.println(WiFi.localIP());
return true;
} else {
Serial.println();
Serial.println("[WiFi] Connection failed!");
Serial.print("[WiFi] Status: ");
Serial.println(WiFi.status());
return false;
}
}
// ==================== XỬ LÝ HTTP RESPONSE ====================
// Hàm gửi HTTP request và nhận kết quả trả về
void printHttpResponse(
HTTPClient& http,
int httpCode,
const char* requestName
) {
Serial.println();
Serial.print("[");
Serial.print(requestName);
Serial.println("]");
// Kiểm tra mã trạng thái HTTP
if (httpCode > 0) {
Serial.print("HTTP Status Code: ");
Serial.println(httpCode);
// Đọc nội dung response từ server
String response = http.getString();
Serial.println("Server Response:");
Serial.println(response);
} else {
// Nếu request thất bại thì hiển thị nguyên nhân
Serial.print("HTTP Request Failed: ");
Serial.println(http.errorToString(httpCode));
}
// Giải phóng tài nguyên HTTP
http.end();
}
// ==================== HTTP GET ====================
// Gửi dữ liệu bằng HTTP GET
// Dữ liệu được đóng gói dưới dạng URL-encoded
void sendHttpGet(
float temperature,
float humidity,
int motion
) {
Serial.println();
Serial.println("[HTTP GET] Sending request...");
// Tạo URL chứa các tham số cần gửi
String url = String(GET_URL);
url += "?temperature=" + String(temperature, 1);
url += "&humidity=" + String(humidity, 1);
url += "&motion=" + String(motion);
// Tạo đối tượng HTTPS client
WiFiClientSecure client;
// Bỏ qua xác thực chứng chỉ TLS (chỉ dùng cho mô phỏng)
client.setInsecure();
// Khởi tạo HTTP client
HTTPClient http;
if (http.begin(client, url)) {
// Gửi HTTP GET request
int httpCode = http.GET();
// In kết quả trả về từ server
printHttpResponse(http, httpCode, "HTTP GET");
} else {
Serial.println("[HTTP GET] Unable to connect to server!");
}
}
// ==================== HTTP POST FORM ====================
// Gửi dữ liệu bằng HTTP POST
// Dữ liệu được đóng gói dưới dạng application/x-www-form-urlencoded
void sendHttpPostForm(
float temperature,
float humidity,
int motion
) {
Serial.println();
Serial.println("[HTTP POST FORM] Sending request...");
// Tạo HTTPS client
WiFiClientSecure client;
// Bỏ qua xác thực chứng chỉ TLS (chỉ dùng cho mô phỏng)
client.setInsecure();
// Khởi tạo HTTP client
HTTPClient http;
if (http.begin(client, POST_URL)) {
// Khai báo kiểu dữ liệu gửi trong request body
http.addHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
// Đóng gói dữ liệu theo định dạng URL-encoded
String postData = "";
postData += "temperature=" + String(temperature, 1);
postData += "&humidity=" + String(humidity, 1);
postData += "&motion=" + String(motion);
// Gửi HTTP POST request cùng dữ liệu trong body
int httpCode = http.POST(postData);
// In kết quả trả về từ server
printHttpResponse(http, httpCode, "HTTP POST FORM");
} else {
Serial.println("[HTTP POST FORM] Unable to connect to server!");
}
}
// ==================== HTTP POST JSON ====================
// Gửi dữ liệu bằng HTTP POST
// Dữ liệu được đóng gói dưới dạng JSON trong request body
void sendHttpPostJson(
float temperature,
float humidity,
int motion
) {
Serial.println();
Serial.println("[HTTP POST JSON] Sending request...");
// Tạo HTTPS client
WiFiClientSecure client;
// Bỏ qua xác thực chứng chỉ TLS (chỉ dùng cho mô phỏng)
client.setInsecure();
// Khởi tạo HTTP client
HTTPClient http;
if (http.begin(client, POST_URL)) {
// Khai báo kiểu dữ liệu gửi trong request body là JSON
http.addHeader(
"Content-Type",
"application/json"
);
// Tạo chuỗi JSON chứa dữ liệu cảm biến
String jsonData = "{";
jsonData += "\"temperature\":" + String(temperature, 1);
jsonData += ",\"humidity\":" + String(humidity, 1);
jsonData += ",\"motion\":" + String(motion);
jsonData += "}";
// Gửi HTTP POST request cùng dữ liệu JSON trong body
int httpCode = http.POST(jsonData);
// In kết quả trả về từ server
printHttpResponse(http, httpCode, "HTTP POST JSON");
} else {
Serial.println("[HTTP POST JSON] Unable to connect to server!");
}
}
// ==================== SETUP ====================
void setup() {
// Khởi tạo Serial Monitor với tốc độ 115200 baud
Serial.begin(115200);
// Cấu hình các chân GPIO
pinMode(LED_PIN, OUTPUT);
pinMode(PIR_PIN, INPUT);
// Ban đầu tắt LED
digitalWrite(LED_PIN, LOW);
// Khởi tạo cảm biến DHT22
dht.begin();
// Khởi tạo giao tiếp I2C
Wire.begin(I2C_SDA, I2C_SCL);
// Khởi tạo LCD
lcd.init();
// Bật đèn nền LCD
lcd.backlight();
// Hiển thị thông báo khởi động
lcd.setCursor(0, 0);
lcd.print("ESP32 SYSTEM");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
// In thông báo khởi động qua Serial
Serial.println("================================");
Serial.println("ESP32 SENSOR MONITORING SYSTEM");
Serial.println("================================");
// Kết nối Wi-Fi
if (!connectWiFi()) {
Serial.println("[SYSTEM] WiFi unavailable. Will retry later.");
}
// Xóa nội dung LCD
lcd.clear();
Serial.println("[SYSTEM] Initialization completed!");
}
// ==================== LOOP ====================
void loop() {
// 1. ĐỌC TRẠNG THÁI CẢM BIẾN PIR
// Đọc tín hiệu từ cảm biến PIR
int motionState = digitalRead(PIR_PIN);
// Kiểm tra có chuyển động hay không
if (motionState == HIGH) {
// Có chuyển động: bật LED
digitalWrite(LED_PIN, HIGH);
} else {
// Không có chuyển động: tắt LED
digitalWrite(LED_PIN, LOW);
}
// Chỉ ghi log khi trạng thái PIR thay đổi
if (motionState != previousMotionState) {
if (motionState == HIGH) {
Serial.println("[PIR] Motion detected - LED ON");
} else {
Serial.println("[PIR] No motion - LED OFF");
}
previousMotionState = motionState;
}
// 2. KIỂM TRA CHU KỲ ĐỌC CẢM BIẾN
// Lấy thời gian hiện tại
unsigned long currentTime = millis();
// Kiểm tra đã đủ 2 giây kể từ lần đọc trước hay chưa
if (currentTime - previousReadTime >= READ_INTERVAL) {
// Cập nhật thời điểm đọc dữ liệu
previousReadTime = currentTime;
// 3. ĐỌC DỮ LIỆU DHT22
// Đọc độ ẩm từ DHT22
humidity = dht.readHumidity();
// Đọc nhiệt độ từ DHT22
temperature = dht.readTemperature();
// Kiểm tra dữ liệu đọc được có hợp lệ hay không
if (isnan(humidity) || isnan(temperature)) {
Serial.println("[DHT22] ERROR: Failed to read sensor!");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("DHT22 ERROR");
return;
}
// 4. HIỂN THỊ DỮ LIỆU LÊN LCD
lcd.clear();
// Hiển thị nhiệt độ tại dòng thứ nhất
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature, 1);
lcd.print((char)223);
lcd.print("C");
// Hiển thị độ ẩm tại dòng thứ hai
lcd.setCursor(0, 1);
lcd.print("Humi: ");
lcd.print(humidity, 1);
lcd.print("%");
// 5. GỬI LOG DỮ LIỆU QUA SERIAL
Serial.println();
Serial.println("================================");
Serial.print("[DHT22] Temperature: ");
Serial.print(temperature);
Serial.println(" C");
Serial.print("[DHT22] Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("[PIR] Motion: ");
Serial.println(motionState == HIGH ? "DETECTED" : "NOT DETECTED");
Serial.print("[LED] Status: ");
Serial.println(motionState == HIGH ? "ON" : "OFF");
Serial.println("================================");
// 6. KIỂM TRA KẾT NỐI WIFI
if (WiFi.status() != WL_CONNECTED) {
Serial.println("[WiFi] Connection lost!");
// Thử kết nối lại Wi-Fi
if (!connectWiFi()) {
Serial.println("[SYSTEM] Skip HTTP requests because WiFi is unavailable.");
return;
}
}
// 7. GỬI HTTP GET
sendHttpGet(
temperature,
humidity,
motionState
);
// 8. GỬI HTTP POST URL-ENCODED
sendHttpPostForm(
temperature,
humidity,
motionState
);
// 9. GỬI HTTP POST JSON
sendHttpPostJson(
temperature,
humidity,
motionState
);
// 10. HOÀN TẤT
Serial.println();
Serial.println("[SYSTEM] All HTTP requests completed!");
Serial.println("================================");
}
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4