#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingsBoard server details
const char* thingsboardServer = "http://demo.thingsboard.io"; // Server URL
const char* accessToken = "EGm0hpmr8R5xEv2j36we"; // Access token for the device
// DHT Sensor
#define DHTPIN 18 // GPIO pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize DHT sensor
dht.begin();
}
void loop() {
// Wait a few seconds between measurements
delay(2000);
// Reading temperature and humidity
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again)
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print temperature and humidity to Serial Monitor
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(h);
Serial.println(" %");
// Prepare the JSON payload
String payload = "{";
payload += "\"temperature\":" + String(t) + ",";
payload += "\"humidity\":" + String(h);
payload += "}";
// Send data to ThingsBoard
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(thingsboardServer) + "/api/v1/" + accessToken + "/telemetry";
http.begin(url); // Use complete URL directly
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("HTTP Response code: " + String(httpResponseCode));
Serial.println("Response: " + response);
} else {
Serial.println("Error on sending POST: " + String(httpResponseCode));
}
http.end();
} else {
Serial.println("Error in WiFi connection");
}
}