#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
const char* ssid = "Wokwi-GUEST"; // Simulated SSID in Wokwi
const char* password = ""; // No password for simulated WiFi
const char* serverAddress = "http://soufiane-arduino.000webhostapp.com/dht/rest_api.php";
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
delay(1000); // Delay to allow serial monitor to initialize
// Simulate connecting to WiFi
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to WiFi");
// Initialize DHT sensor
dht.begin();
}
void loop() {
// Read temperature and humidity from DHT sensor
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if sensor reading is valid
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Create HTTP client object
HTTPClient http;
http.begin(serverAddress);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Prepare data to be sent to the server
String data = "temperature=" + String(temperature) + "&humidity=" + String(humidity);
// Send HTTP POST request to the server
int httpResponseCode = http.POST(data);
// Check for response from server
if (httpResponseCode > 0) {
String response = http.getString();
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error sending HTTP request. Response code: ");
Serial.println(httpResponseCode);
}
// End HTTP connection
http.end();
// Delay before sending next data
delay(5000); // Send data every 10 seconds
}