#include <WiFi.h>
#include <WiFiUdp.h>
#include <DHT.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// DHT settings
#define DHTPIN 13 // GPIO connected to DHT sensor
#define DHTTYPE DHT22 // Change to DHT22 if using DHT22
DHT dht(DHTPIN, DHTTYPE);
// UDP settings
WiFiUDP udp;
const int udpPort = 1234;
char incomingPacket[255];
void setup() {
Serial.begin(115200);
dht.begin();
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected!");
Serial.print("ESP32 IP Address: ");
Serial.println(WiFi.localIP());
// Start UDP server
udp.begin(udpPort);
Serial.printf("UDP server started on port %d\n", udpPort);
}
void loop() {
int packetSize = udp.parsePacket();
if (packetSize) {
int len = udp.read(incomingPacket, 255);
if (len > 0) {
incomingPacket[len] = '\0';
}
Serial.print("Received: ");
Serial.println(incomingPacket);
// If client requests data
if (strcmp(incomingPacket, "GET_DATA") == 0) {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
String response;
if (isnan(temperature) || isnan(humidity)) {
response = "Sensor Error";
} else {
response = "Temperature: " + String(temperature) +
" C, Humidity: " + String(humidity) + " %";
}
// Send response to client
udp.beginPacket(udp.remoteIP(), udp.remotePort());
udp.print(response);
udp.endPacket();
Serial.println("Response sent");
}
}
}