#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
// Wi-Fi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// HTTP server endpoint
const char* serverName = "https://moodlog-backend.onrender.com/data/predict";
// DHT sensor configuration
#define DHT_SENSOR_PIN 32 // ESP32 pin GPIO32 connected to DHT22 sensor
#define DHT_SENSOR_TYPE DHT22
DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE);
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
// Initialize DHT sensor
dht_sensor.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
void loop() {
// Read temperature in Celsius
float tempC = dht_sensor.readTemperature();
// Check if reading was successful
if (isnan(tempC)) {
Serial.println("Error reading the sensor");
} else {
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println("°C");
}
// Read humidity
float humidity = dht_sensor.readHumidity();
if (isnan(humidity)) {
Serial.println("Error reading the sensor");
} else {
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
}
// Send data to server if WiFi is connected
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// Begin HTTP connection
http.begin(serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send in the POST request
String httpRequestData = "temperature=" + String(tempC) + "&humidity=" + String(humidity);
// Send POST request
int httpResponseCode = http.POST(httpRequestData);
// Print response
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
} else {
Serial.println("WiFi Disconnected");
}
delay(2000); // Wait for 2 seconds
}