#include "DHT.h"
#include "HTTPClient.h"
#include <WiFi.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "" ;
#define DHTPIN 14 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
const char *serverUrl = "http://demo.thingsboard.io/api/v1/B3mYTWNNKgcxxD4iI7pu/telemetry";
// Khai báo biến đối tượng HTTPClient
HTTPClient http;
void setup() {
Serial.begin(115200);
Serial.println(F("DHTxx to ThingsBoard!"));
dht.begin();
//setup wifi
WiFi.begin(ssid,password);
Serial.println("conecting");
while(WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
//Khởi tạo kết nối với máy chủ ThingsBoard
http.begin(serverUrl);
// Tạo header cho yêu cầu POST
http.addHeader("Content-Type", "application/json");
}
void loop() {
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.println(" %");
Serial.print(F("Temperature: "));
Serial.print(t);
Serial.println(" oC");
char para[50];
String jsonData = "{\"temperature\":" + String(t)+ ";\"humidity\":" + String(h) + "}";
Serial.println(jsonData);
// Gửi yêu cầu POST với dữ liệu JSON
int httpCode = http.POST(jsonData);
// Kiểm tra trạng thái yêu cầu
if (httpCode > 0) {
// Nếu kết nối thành công
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString(); // Nhận dữ liệu phản hồi
Serial.println(payload);
}
} else {
Serial.printf("HTTP request failed with error %s\n", http.errorToString(httpCode).c_str());
}
delay(5000); // Chờ 5 giây trước khi gửi yêu cầu tiếp theo
}