#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST"; // Thay bằng tên WiFi
const char* password = ""; // Thay bằng mật khẩu WiFi (nếu có)
// DHT sensor configuration
#define DHTPIN 15 // Pin ESP32 kết nối với chân Data của DHT22
#define DHTTYPE DHT22 // Loại cảm biến DHT (DHT11 hoặc DHT22)
DHT dht(DHTPIN, DHTTYPE);
// API URLs
const char* dht_api_url = "https://2mlbgff1ks.sharedwithexpose.com/ptiot/dht_sensor.php"; // API lưu dữ liệu cảm biến
const char* led_api_url = "https://2mlbgff1ks.sharedwithexpose.com/ptiot/led_status.php"; // API lưu trạng thái LED
// LED pin
#define LEDPIN 16
bool ledStatus = false;
void setup() {
Serial.begin(115200);
pinMode(LEDPIN, OUTPUT); // Cấu hình chân LED
digitalWrite(LEDPIN, LOW);
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
dht.begin(); // Khởi động cảm biến DHT
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
// Đọc dữ liệu từ cảm biến DHT22
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
} else {
// In giá trị cảm biến ra Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// Gửi dữ liệu cảm biến đến API
HTTPClient http;
String dht_api_full_url = String(dht_api_url) + "?temperature=" + temperature + "&humidity=" + humidity;
http.begin(dht_api_full_url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("DHT API Response: " + response);
} else {
Serial.println("Error sending DHT data");
}
http.end();
}
// Điều khiển đèn LED
ledStatus = !ledStatus; // Thay đổi trạng thái LED (bật/tắt)
digitalWrite(LEDPIN, ledStatus ? HIGH : LOW);
Serial.println(ledStatus ? "LED ON" : "LED OFF");
// Gửi trạng thái LED đến API
HTTPClient httpLed;
String led_api_full_url = String(led_api_url) + "?led_status=" + (ledStatus ? "ON" : "OFF");
httpLed.begin(led_api_full_url);
int httpLedResponseCode = httpLed.GET();
if (httpLedResponseCode > 0) {
String response = httpLed.getString();
Serial.println("LED API Response: " + response);
} else {
Serial.println("Error sending LED data");
}
httpLed.end();
} else {
Serial.println("WiFi disconnected!");
}
// Dừng 5 giây trước khi gửi dữ liệu tiếp theo
delay(5000);
}