#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define THINGSBOARD_SERVER "http://thingsboard.cloud"
#define TOKEN "em0wqval3om5nukxbpoi" // Replace with your ThingsBoard device token
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
void sendDataToThingsboard(float temperature, float humidity) {
WiFiClient client;
HTTPClient http;
String url = String(THINGSBOARD_SERVER) + "/api/v1/" + String(TOKEN) + "/telemetry";
String data = "{\"temperature\": " + String(temperature) + ", \"humidity\": " + String(humidity) + "}";
http.begin(client, url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(data);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error sending data to Thingsboard: ");
Serial.println(httpResponseCode);
}
http.end();
}
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, 6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
}
void loop() {
delay(2000); // Wait a few seconds between measurements
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
sendDataToThingsboard(temperature, humidity);
}