#include <ArduinoIoTCloud.h>
#include <Arduino_ConnectionHandler.h>
#include <DHT.h>
#define DHTPIN 27 // Chân data DHT22
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
const char SSID[] = "Wokwi-GUEST";
const char PASS[] = "";
const char DEVICE_LOGIN_NAME[] = "4a4f6bd2-c6bf-45ea-81e4-5e4eb2f9c978";
const char DEVICE_KEY[] = "4xKGJ6vRBKELrjbHpdAzO?2Ik";
float temperature;
float humidity;
int lightLevel;
bool relayState;
void initProperties() {
ArduinoCloud.setBoardId(DEVICE_LOGIN_NAME);
ArduinoCloud.setSecretDeviceKey(DEVICE_KEY);
ArduinoCloud.addProperty(temperature, READ, 60 * 1000);
ArduinoCloud.addProperty(humidity, READ, 60 * 1000);
ArduinoCloud.addProperty(lightLevel, READ, 10 * 1000);
ArduinoCloud.addProperty(relayState, READWRITE, ON_CHANGE, onRelayChange);
}
WiFiConnectionHandler ArduinoIoTPreferredConnection(SSID, PASS);
void setup() {
Serial.begin(9600);
delay(1500);
initProperties();
ArduinoCloud.begin(ArduinoIoTPreferredConnection);
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
pinMode(26, OUTPUT); // Chân relay
digitalWrite(26, LOW); // Relay tắt lúc đầu
dht.begin();
}
void loop() {
ArduinoCloud.update();
// Đọc cảm biến mỗi vòng lặp hoặc theo thời gian thực
lightLevel = analogRead(34);
// Cập nhật nhiệt độ và độ ẩm sau mỗi 1 phút (ArduinoCloud tự động gọi 60s)
temperature = dht.readTemperature();
humidity = dht.readHumidity();
// Cập nhật relay chân GPIO26
digitalWrite(26, relayState ? HIGH : LOW);
// Debug
Serial.print("Temp: "); Serial.print(temperature);
Serial.print(" C, Humidity: "); Serial.print(humidity);
Serial.print(" %, Light: "); Serial.println(lightLevel);
delay(2000);
}
void onRelayChange() {
// Hàm callback khi relayState thay đổi từ cloud
Serial.print("Relay changed to: ");
Serial.println(relayState);
digitalWrite(26, relayState ? HIGH : LOW);
}
{
"version": 1,
"author": "Uri Shaked",
"editor": "wokwi",
"parts": [
{ "type": "board-esp32-devkit-c-v4", "id": "esp", "top": 0, "left": 0, "attrs": {} },
{ "type": "wokwi-photoresistor-sensor", "id": "ldr1", "top": 41.6, "left": -316, "attrs": {} },
{ "type": "wokwi-dht22", "id": "dht1", "top": -143.7, "left": 148.2, "attrs": {} },
{ "type": "wokwi-relay-module", "id": "relay1", "top": 230.6, "left": 144, "attrs": {} }
],
"connections": [
[ "esp:TX", "$serialMonitor:RX", "", [] ],
[ "esp:RX", "$serialMonitor:TX", "", [] ],
[ "dht1:VCC", "esp:3V3", "red", [ "h-182.4", "v57.6" ] ],
[ "dht1:SDA", "esp:4", "green", [ "v0" ] ],
[ "dht1:GND", "esp:GND.3", "black", [ "v0" ] ],
[ "ldr1:GND", "esp:GND.1", "black", [ "h28.8", "v172.4" ] ],
[ "ldr1:VCC", "esp:3V3", "red", [ "v-28.8", "h148.61" ] ],
[ "esp:5V", "relay1:VCC", "red", [ "v48", "h139.39" ] ],
[ "esp:GND.1", "relay1:GND", "black", [ "h-43.01", "v115.2" ] ],
[ "esp:5", "relay1:IN", "green", [ "h24.04", "v153.6" ] ],
[ "esp:34", "ldr1:AO", "green", [ "h-71.81", "v19.9" ] ]
],
"dependencies": {}
}