#include <DHTesp.h>
#include <WiFi.h>
#include "ThingsBoard.h"
#define COUNT_OF(x) ((sizeof(x) / sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
#define WIFI_AP_NAME "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define THINGSBOARD_SERVER "cloud.thingsboard.io"
#define THINGSBOARD_ACCESSTOKEN "jvpMHPnNaSFVJN8LPfJO"
#define SERIAL_DEBUG_BAUD 115200
WiFiClient espClient;
ThingsBoard tb(espClient);
int status = WL_IDLE_STATUS;
DHTesp dht;
#define DHT_PIN 13
// Main application loop delay
int quant = 20;
// Period of sending temperature/humidity data.
int send_delay = 2000;
// Time passed after temperature/humidity data was sent, milliseconds.
int send_passed = 0;
float temperature = 0;
float humidity = 0;
const float TEMPERATURE_THRESHOLD = 20.0;
const int LED_PIN = 5;
const int LED_PIN_NEW = 18;
const int BUZZER_PIN = 15; // Chân nơi nút được kết nối
const float TEMPERATURE_THRESHOLD_HIGH = 50.0; // Ngưỡng nhiệt độ để kích hoạt chuông
const float HUMIDITY_THRESHOLD_LOW = 15.0; // Ngưỡng độ ẩm để kích hoạt chuông
const int TRIG_PIN = 4;
const int ECHO_PIN = 2;
RPC_Response processDelayChange(const RPC_Data &data)
{
Serial.println("Received the set delay RPC method");
// Process data
// ...
return String("Delay change processed");
}
RPC_Response processGetDelay(const RPC_Data &data)
{
Serial.println("Received the get value method");
// ...
return String("Get delay value processed");
}
RPC_Response processSetGpioState(const RPC_Data &data)
{
Serial.println("Received the set GPIO RPC method");
int pin = data["pin"];
bool enabled = data["enabled"];
// Process GPIO data
// ...
return String("Set GPIO state processed");
}
RPC_Response processGetGpioState(const RPC_Data &data)
{
Serial.println("Received the get GPIO RPC method");
// Process GPIO data
// ...
return String("Get GPIO state processed");
}
// RPC handlers
RPC_Callback callbacks[] = {
{ "setValue", processDelayChange },
{ "getValue", processGetDelay },
{ "setGpioStatus", processSetGpioState },
{ "getGpioStatus", processGetGpioState },
};
void setup()
{
Serial.begin(SERIAL_DEBUG_BAUD);
WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
InitWiFi();
// Initialize temperature sensor
dht.setup(DHT_PIN, DHTesp::DHT22);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN_NEW, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop()
{
delay(quant);
send_passed += quant;
// Reconnect to WiFi, if needed
if (WiFi.status() != WL_CONNECTED)
{
reconnect();
return;
}
// Reconnect to ThingsBoard, if needed
if (!tb.connected())
{
// Connect to the ThingsBoard
Serial.print("Connecting to: ");
Serial.print(THINGSBOARD_SERVER);
Serial.print(" with token ");
Serial.println(THINGSBOARD_ACCESSTOKEN);
if (!tb.connect(THINGSBOARD_SERVER, THINGSBOARD_ACCESSTOKEN))
{
Serial.println("Failed to connect");
return;
}
}
// Subscribe for RPC, if needed
static bool subscribed = false;
if (!subscribed)
{
Serial.println("Subscribing for RPC... ");
// Perform a subscription. All consequent data processing will happen in
// callbacks as denoted by callbacks[] array.
if (!tb.RPC_Subscribe(callbacks, COUNT_OF(callbacks)))
{
Serial.println("Failed to subscribe for RPC");
return;
}
Serial.println("Subscribe done");
subscribed = true;
}
// Check if it is time to send DHT22 temperature and humidity
if (send_passed > send_delay)
{
Serial.println();
Serial.print("Sending data... ");
TempAndHumidity lastValues = dht.getTempAndHumidity();
if (isnan(lastValues.humidity) || isnan(lastValues.temperature))
{
Serial.println("Failed to read from DHT sensor!");
}
else
{
temperature = lastValues.temperature;
Serial.print("temperature: ");
Serial.print(temperature);
humidity = lastValues.humidity;
Serial.print(" humidity: ");
Serial.print(humidity);
tb.sendTelemetryFloat("temperature", temperature);
tb.sendTelemetryFloat("humidity", humidity);
}
send_passed = 0;
}
if (temperature < TEMPERATURE_THRESHOLD)
{
// Bật đèn (chân 12 trong trường hợp này)
digitalWrite(LED_PIN, HIGH);
}
else
{
// Tắt đèn
digitalWrite(LED_PIN, LOW);
}
if (temperature > TEMPERATURE_THRESHOLD_HIGH && humidity < HUMIDITY_THRESHOLD_LOW)
{
// Kích hoạt chuông (chân 15 trong trường hợp này)
digitalWrite(BUZZER_PIN, HIGH);
// Gửi dữ liệu lên ThingsBoard
tb.sendTelemetryFloat("buzzer_status", 1.0); // Gửi giá trị 1.0 khi chuông được kích hoạt
}
else
{
// Tắt chuông
digitalWrite(BUZZER_PIN, LOW);
// Gửi dữ liệu lên ThingsBoard
tb.sendTelemetryFloat("buzzer_status", 0.0); // Gửi giá trị 0.0 khi chuông được tắt
}
float distance = measureDistance();
if (distance < 50)
{
digitalWrite(LED_PIN_NEW, HIGH); // Turn on LED if distance is less than 50
}
else
{
digitalWrite(LED_PIN_NEW, LOW); // Turn off LED
}
tb.loop();
}
float measureDistance()
{
// Trigger HC-SR04 to measure distance
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the pulse duration on the ECHO pin
unsigned long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in centimeters
float distance = duration * 0.034 / 2;
return distance;
}
void InitWiFi()
{
Serial.println("Connecting to AP ...");
WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
void reconnect()
{
// Loop until we're reconnected
status = WiFi.status();
if (status != WL_CONNECTED)
{
WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
}