#include <WiFi.h>
#include <WiFiUdp.h>
#ifndef STASSID
#define STASSID "LIEA-Tx-Gx"
#define STAPSK "StrongPass123"
#endif
unsigned int localPort = 4321;
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; // buffer to hold incoming packet,
char AckBuffer[] = "acknowledged\r\n"; // a test string to send back...
char ReplyBuffer[UDP_TX_PACKET_MAX_SIZE + 1];
WiFiUDP MyUDP;
void setup() {
Serial.begin(115200);
WiFi.begin(STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(500);
}
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
Serial.printf("UDP server on port %d\n", localPort);
MyUDP.begin(localPort);
}
void loop() {
int i = 0;
// if there's data available, read a packet
int packetSize = MyUDP.parsePacket();
if (packetSize) {
Serial.printf("Received packet of size %d from %s:%d\n (to %s:%d)\n", packetSize,
MyUDP.remoteIP().toString().c_str(), MyUDP.remotePort(),
MyUDP.destinationIP().toString().c_str(), MyUDP.localPort());
// read the packet into packetBufffer
int n = MyUDP.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
packetBuffer[n] = 0;
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
MyUDP.beginPacket(MyUDP.remoteIP(), MyUDP.remotePort());
MyUDP.write(AckBuffer);
MyUDP.endPacket();
MyUDP.beginPacket(MyUDP.remoteIP(), MyUDP.remotePort());
sprintf(ReplyBuffer, "Hello %d from Rasp Pi W!\n\r", i++);
MyUDP.write(ReplyBuffer);
MyUDP.endPacket();
}
}