0% found this document useful (0 votes)
4 views2 pages

Udp

UDP transfer code mechanism

Uploaded by

rocketraccoon123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Udp

UDP transfer code mechanism

Uploaded by

rocketraccoon123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <ESP8266WiFi.

h>
#include <WiFiUdp.h>
#include "DHT.h"

#define DHTPIN D3
#define DHTTYPE DHT11

// Replace with your network credentials


const char* ssid = "IITH-Guest-PWD-IITH@2024";
const char* password = "IITH@2024";

// UDP settings
const char* udpAddress = "172.16.66.40"; // Your server IP
const int udpPort = 5002;

int ir = D1;
int led = D0;
DHT dht(DHTPIN, DHTTYPE);
WiFiUDP udp;

void setup() {
Serial.begin(115200);
Serial.println(F("DHT UDP test!"));

dht.begin();
pinMode(ir, INPUT);
pinMode(led, OUTPUT);

// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("Local IP: ");
Serial.println(WiFi.localIP());

// Initialize UDP
udp.begin(udpPort);
Serial.println("UDP initialized");
}

void loop() {
int value = digitalRead(ir);

if (WiFi.status() == WL_CONNECTED) {
delay(4000);

float h = dht.readHumidity();
float t = dht.readTemperature();
Serial.print("temp and humid--");
Serial.print(h);
Serial.print("---");
Serial.println(t);

if (isnan(h) || isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}

// Send UDP packet


// Format: "device1,temperature,humidity"
String udpMessage = "device1," + String(t) + "," + String(h);

udp.beginPacket(udpAddress, udpPort);
udp.print(udpMessage);
int result = udp.endPacket();

if (result == 1) {
Serial.println("UDP packet sent successfully");
Serial.println("Message: " + udpMessage);

// Optional: Listen for response from server


int packetSize = udp.parsePacket();
if (packetSize) {
char incomingPacket[255];
int len = udp.read(incomingPacket, 255);
if (len > 0) {
incomingPacket[len] = 0;
}
Serial.print("UDP response: ");
Serial.println(incomingPacket);

// Handle LED control based on response if needed


String response = String(incomingPacket);
if (response.indexOf("0") >= 0) {
digitalWrite(led, HIGH);
}
if (response.indexOf("1") >= 0) {
digitalWrite(led, LOW);
}
}
} else {
Serial.println("Failed to send UDP packet");
}
} else {
Serial.println("WiFi disconnected, attempting to reconnect...");
WiFi.begin(ssid, password);
}

delay(5000);
}

You might also like