#include <WiFi.h>
#include <WiFiUdp.h>
#include "DHT.h"
DHT dht(16,DHT22); // 16 GPIO numbering system
const int udpPort = 5219; // UDP port to listen on 5219
WiFiUDP udp;
void setup() {
Serial1.begin(115200);
Serial1.println("Connecting to WiFi...");
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial1.println("Connecting to WiFi...");
}
Serial1.println("WiFi connected.");
Serial1.print("IP Address:");
Serial1.println(WiFi.localIP());
Serial1.println("UDP server started");
udp.begin(udpPort);
}
void loop() {
char packetBuffer[255]; // Buffer to hold icoming packet
int packetSize = udp.parsePacket();
if (packetSize) {
// receiving incoming UDP packet
int len = udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
// check if the received packet is a request for humidity data
if (strcmp(packetBuffer, "GET_H") == 0) {
// replace the following line with your humidity sesor reading logic
float humidity = readHumidity(); // function to read humidity data
// send humidity data back to the client
udp.beginPacket(udp.remoteIP(), udp.remotePort());
udp.printf("Humidity: %.2f%%", humidity);
udp.endPacket();
}
}
delay(1000); // add a small delay to avoid excessive response
}
float readHumidity()
{
// Read data from a DHT sensor
float humidity = dht.readHumidity();
return humidity;
}