Created
January 3, 2020 22:22
-
-
Save timgray/77b0f5d696616420a8722f8fae53a901 to your computer and use it in GitHub Desktop.
UDP ESP8266
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include | |
#include | |
const char* ssid = "MySSID"; | |
const char* password = "SecretPassword"; | |
WiFiUDP Udp; | |
unsigned int localUdpPort = 4210; // local port to listen on | |
char incomingPacket[255]; // buffer for incoming packets | |
char replyPacket[] = "Hi there! Got the message :-) "; // a reply string to send back | |
void setup() | |
{ | |
Serial.begin(115200); | |
Serial.println(); | |
Serial.printf("Connecting to %s ", ssid); | |
WiFi.mode(WIFI_STA); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) | |
{ | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(" connected"); | |
Udp.begin(localUdpPort); | |
Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort); | |
} | |
void loop() | |
{ | |
int packetSize = Udp.parsePacket(); | |
if (packetSize) | |
{ | |
// receive incoming UDP packets | |
Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort()); | |
int len = Udp.read(incomingPacket, 255); | |
if (len > 0) | |
{ | |
incomingPacket[len] = 0; | |
} | |
Serial.printf("UDP packet contents: %s\n", incomingPacket); | |
// send back a reply, to the IP address and port we got the packet from | |
Udp.beginPacket("192.168.41.255", localUdpPort+1); | |
Udp.write(replyPacket); | |
Udp.endPacket(); | |
String tmp = incomingPacket; | |
if(tmp.indexOf("STATUS") >= 0) | |
{ | |
// lets send back our IP address | |
String temp = "ADDR:"+ WiFi.localIP().toString(); | |
temp.toCharArray(replyPacket,temp.length()); | |
Udp.beginPacket("255.255.255.255", localUdpPort+1); | |
Udp.write(replyPacket); | |
Udp.endPacket(); | |
} | |
if(tmp.indexOf("RSSI") >= 0) | |
{ | |
int mysignal = WiFi.RSSI(); // get the signal strength | |
String temp = "RSSI:"+ String(mysignal); | |
temp.toCharArray(replyPacket,temp.length()); | |
Udp.beginPacket("255.255.255.255", localUdpPort+1); | |
Udp.write(replyPacket); | |
Udp.endPacket(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment