-
Vojtěch Novotný authoredVojtěch Novotný authored
esp_code.ino 2.83 KiB
#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
// WiFi credentials
const char *ssid = "WIFI_NAME";
const char *password = "PWIFI_PW";
// Server url
const char *serverUrl = "http://1a68d31fc96915376990672871a32080.serveo.net/docs/thproject/index.php?p=";
// DHT sensor setup
#define DHTPIN 18 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
// Room identification - this varies for each ESP32, replace "room1", "room2", ...
const String roomId = "roomX";
// Time between measurements (in milliseconds)
const unsigned long interval = 60000; // 1 minute
unsigned long previousMillis = 0;
void setup()
{
Serial.begin(115200);
// Initialize DHT sensor
dht.begin();
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
unsigned long currentMillis = millis();
// Check if it's time to send data
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
// Read temperature and humidity
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if readings are valid
if (isnan(humidity) || isnan(temperature))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// Send data to server
sendDataToServer(temperature, humidity, roomId);
}
}
void sendDataToServer(float temperature, float humidity, String room)
{
// Check WiFi connection status
if (WiFi.status() == WL_CONNECTED)
{
HTTPClient http;
// Construct the URL with parameters
String url = String(serverUrl) + "data&room=" + room + "&temp=" + temperature + "&humidity=" + humidity;
// Begin HTTP connection
http.begin(url);
// Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode > 0)
{
String response = http.getString();
Serial.println("HTTP Response code: " + String(httpResponseCode));
Serial.println("Response: " + response);
}
else
{
Serial.print("HTTP Error: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
else
{
Serial.println("WiFi Disconnected");
// Attempt to reconnect
WiFi.reconnect();
}
}