/* Select ERa host location (VN: Viet Nam, SG: Singapore) */
#define ERA_LOCATION_VN
// #define ERA_LOCATION_SG
// You should get Auth Token in the ERa App or ERa Dashboard
#define ERA_AUTH_TOKEN "0cc98a91-f6fd-428c-bfcc-d8202aae0ceb"
#include <Buzzer.h>
#include <Arduino.h> // Cung cấp các hàm cơ bản cho Arduino
#include <ERa.hpp>//Thư viện cho các ứng dụng điều khiển từ xa hoặc giao tiếp.
#include <DHT.h>// Đọc dữ liệu từ cảm biến DHT về nhiệt độ và độ ẩm.
// Định nghĩa cảm biến DHT
#define DHTPIN 22 // Chân DATA của DHT22 nối với GPIO15
#define DHTTYPE DHT22 // Loại cảm biến: DHT22
#define buzzerPin 23 // chân của còi
DHT dht(DHTPIN, DHTTYPE);
//thông tin wifi mình sẽ kết nối
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
WiFiClient mbTcpClient;//tạo ra một đối tượng cho phép thiết bị Arduino của bạn giao tiếp
//với các máy chủ qua mạng WiFi
// /* hàm nãy sẽ chạy mỗi khi era được kết nối */
ERA_CONNECTED() {
ERA_LOG(ERA_PSTR("ERa"), ERA_PSTR("ERa connected!"));
}
/* hàm nãy sẽ chạy mỗi khi era được kết nối */
ERA_DISCONNECTED() {
ERA_LOG(ERA_PSTR("ERa"), ERA_PSTR("ERa disconnected!"));
}
void senddata() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if the readings are valid
if (isnan(humidity) || isnan(temperature)) {
ERA_LOG(ERA_PSTR("DHT"), ERA_PSTR("Failed to read from DHT sensor!"));
return;
}
if(temperature>=50){
tone(buzzerPin,1000);
delay(1000);
noTone(buzzerPin);
}
// gửi data đến virtulpin
ERa.virtualWrite(V3, humidity); // Send humidity to V3
ERa.virtualWrite(V5, int(temperature)); // Send temperature to V5
// Log the readings
ERA_LOG(ERA_PSTR("DHT"), ERA_PSTR("Humidity: %.2f%% Temperature: %.2f°C"), humidity, temperature);
}
/* cập nhật dữ liệu mỗi giây */
void timerEvent() {
ERA_LOG(ERA_PSTR("Timer"), ERA_PSTR("Uptime: %d"), ERaMillis() / 1000L);
senddata(); // gọi hàm senddata
}
void setup() {
#if defined(ERA_DEBUG)
Serial.begin(9600);
#endif
#if defined(BUTTON_PIN)
/* Khởi tạo nút . */
initButton();
/* Cho phép đọc/ghi thông tin xác thực WiFi*/
ERa.setPersistent(true);
#endif
/* Khởi tạo cảm biến DHT */
dht.begin();
/* Thiết lập Client cho Modbus TCP/IP */
ERa.setModbusClient(mbTcpClient);
/*Đặt quét WiFi. Nếu được kích hoạt, bo mạch sẽ quét
và kết nối với Wifi. */
ERa.setScanWiFi(true);
/* Khởi tạo thư viện ERa. */
ERa.begin(ssid, pass);
/* Thiết lập bộ đếm thời gian gọi hàm mỗi giây.*/
ERa.addInterval(1000L, timerEvent);
}
void loop() {
ERa.run();
}