#include <DHTesp.h>
#include <WiFi.h>
#include <HTTPClient.h>
#define DHTPIN 15 // Define the GPIO where the DHT22 sensor is connected
#define DHTTYPE DHTesp::DHT22 // Specify the DHT sensor type
DHTesp dht;
const char* ssid = "HUAWEI-5G-2aRh";
const char* password = "ZuqhMg84";
const char* backendURL = "https://af8b-197-1-154-117.ngrok-free.app/updateSensorData";
void setup() {
Serial.begin(115200);
dht.setup(DHTPIN, DHTTYPE); // Initialize the DHT sensor
// Connect to the WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
delay(2000);
float humidity = dht.getHumidity();
float temperature = dht.getTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read DHT22 sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\tTemperature: ");
Serial.println(temperature);
// Send data to the backend
sendSensorData(temperature, humidity);
}
void sendSensorData(float temperature, float humidity) {
HTTPClient http;
// Build the backend URL
String url = backendURL;
// Create a JSON object with the sensor data
String jsonPayload = "{\"temperature\":" + String(temperature) + ", \"humidity\":" + String(humidity) + "}";
// Start the HTTP request
http.begin(url);
// Configure the request headers
http.addHeader("Content-Type", "application/json");
http.addHeader("Accept", "application/json");
// Send the POST request with the JSON payload
int httpCode = http.POST(jsonPayload);
// Handle the server response
if (httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
// Close the HTTP connection
http.end();
}