TolentinoCotesta

UDP

Apr 22nd, 2021 (edited)
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Arduino.h>
  2. #include <ESP8266WiFi.h>
  3. #include <WiFiUdp.h>
  4.  
  5. #ifndef STASSID
  6. #define STASSID "xxxxxxxx"
  7. #define STAPSK  "xxxxxxxx"
  8. #endif
  9.  
  10. unsigned int localPort = 8888;      // local port to listen on
  11. WiFiUDP Udp;
  12.  
  13. // buffers for receiving and sending data
  14. char rxBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; // buffer to hold incoming packet,
  15. char txBuffer[UDP_TX_PACKET_MAX_SIZE + 1];  // a message to send back
  16.  
  17. void setup() {
  18.   Serial.begin(115200);
  19.   WiFi.mode(WIFI_STA);
  20.   WiFi.begin(STASSID, STAPSK);
  21.   while (WiFi.status() != WL_CONNECTED) {
  22.     Serial.print('.');
  23.     delay(500);
  24.   }
  25.   Serial.print("Connected! IP address: ");
  26.   Serial.println(WiFi.localIP());
  27.   Serial.printf("UDP server on port %d\n", localPort);
  28.   Udp.begin(localPort);
  29. }
  30.  
  31. void loop() {
  32.   handleUdpMessages();
  33.   if(strlen(rxBuffer)) {
  34.     Serial.print("Ricevuto un nuovo messaggio UDP: ");
  35.     Serial.println(rxBuffer);
  36.     rxBuffer[0] = '\0'; // Clear del buffer di ricezione
  37.   }
  38.  
  39.  
  40. }
  41.  
  42.  
  43. void handleUdpMessages(){
  44.   // if there's data available, read a packet
  45.   int packetSize = Udp.parsePacket();
  46.   if (packetSize) {
  47.     Serial.printf("Ricevuto un messaggio (%d bytes) da %s:%d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
  48.  
  49.     // read the packet into packetBufffer
  50.     int n = Udp.read(rxBuffer, UDP_TX_PACKET_MAX_SIZE);
  51.     rxBuffer[n] = '\0';    // Aggiunta del terminatore di stringa
  52.  
  53.     // send a reply, to the IP address and port that sent us the packet we received
  54.     snprintf(txBuffer, UDP_TX_PACKET_MAX_SIZE, "Ricevuto il messaggio: %s\n", rxBuffer);
  55.     Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
  56.     Udp.write(txBuffer);
  57.     Udp.endPacket();    
  58.   }
  59. }
Add Comment
Please, Sign In to add comment