Advertisement
Victoryus82

udp_teszt

May 12th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. /*
  2.   UDPSendReceive.pde:
  3.   This sketch receives UDP message strings, prints them to the serial port
  4.   and sends an "acknowledge" string back to the sender
  5.  
  6.   A Processing sketch is included at the end of file that can be used to send
  7.   and received messages for testing with a computer.
  8.  
  9.   created 21 Aug 2010
  10.   by Michael Margolis
  11.  
  12.   This code is in the public domain.
  13.  
  14.   adapted from Ethernet library examples
  15. */
  16.  
  17.  
  18. #include <ESP8266WiFi.h>
  19. #include <WiFiUdp.h>
  20.  
  21. #ifndef STASSID
  22. #define STASSID "wemos"
  23. #define STAPSK  "nincs"
  24. #endif
  25.  
  26. unsigned int localPort = 8888;      // local port to listen on
  27.  
  28. // buffers for receiving and sending data
  29. char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
  30. char  ReplyBuffer[] = "acknowledged\r\n";       // a string to send back
  31.  
  32. WiFiUDP Udp;
  33.  
  34. void setup() {
  35.   Serial.begin(115200);
  36.   WiFi.mode(WIFI_STA);
  37.   WiFi.begin(STASSID, STAPSK);
  38.     Serial.println('Connecting');
  39.   while (WiFi.status() != WL_CONNECTED) {
  40.     Serial.print('.');
  41.     delay(1000);
  42.   }
  43.   Serial.print("Connected! IP address: ");
  44.   Serial.println(WiFi.localIP());
  45.   Serial.printf("UDP server on port %d\n", localPort);
  46.   Udp.begin(localPort);
  47. }
  48.  
  49. void loop() {
  50.   // if there's data available, read a packet
  51.   int packetSize = Udp.parsePacket();
  52.   if (packetSize) {
  53.     Serial.print("Received packet of size ");
  54.     Serial.println(packetSize);
  55.     Serial.print("From ");
  56.     IPAddress remote = Udp.remoteIP();
  57.     for (int i = 0; i < 4; i++) {
  58.       Serial.print(remote[i], DEC);
  59.       if (i < 3) {
  60.         Serial.print(".");
  61.       }
  62.     }
  63.     Serial.print(", port ");
  64.     Serial.println(Udp.remotePort());
  65.  
  66.     // read the packet into packetBufffer
  67.     Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
  68.     Serial.println("Contents:");
  69.     Serial.println(packetBuffer);
  70.  
  71.     // send a reply, to the IP address and port that sent us the packet we received
  72.     Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
  73.     Udp.write(ReplyBuffer);
  74.     Udp.endPacket();
  75.   }
  76.   delay(10);
  77. }
  78.  
  79. /*
  80.   test (shell/netcat):
  81.   --------------------
  82.       nc -u 192.168.esp.address 8888
  83. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement