Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Arduino.h>
- #include <ESP8266WiFi.h>
- #include <WiFiUdp.h>
- #ifndef STASSID
- #define STASSID "xxxxxxxx"
- #define STAPSK "xxxxxxxx"
- #endif
- unsigned int localPort = 8888; // local port to listen on
- WiFiUDP Udp;
- // buffers for receiving and sending data
- char rxBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; // buffer to hold incoming packet,
- char txBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; // a message to send back
- void setup() {
- Serial.begin(115200);
- WiFi.mode(WIFI_STA);
- 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);
- Udp.begin(localPort);
- }
- void loop() {
- handleUdpMessages();
- if(strlen(rxBuffer)) {
- Serial.print("Ricevuto un nuovo messaggio UDP: ");
- Serial.println(rxBuffer);
- rxBuffer[0] = '\0'; // Clear del buffer di ricezione
- }
- }
- void handleUdpMessages(){
- // if there's data available, read a packet
- int packetSize = Udp.parsePacket();
- if (packetSize) {
- Serial.printf("Ricevuto un messaggio (%d bytes) da %s:%d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
- // read the packet into packetBufffer
- int n = Udp.read(rxBuffer, UDP_TX_PACKET_MAX_SIZE);
- rxBuffer[n] = '\0'; // Aggiunta del terminatore di stringa
- // send a reply, to the IP address and port that sent us the packet we received
- snprintf(txBuffer, UDP_TX_PACKET_MAX_SIZE, "Ricevuto il messaggio: %s\n", rxBuffer);
- Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
- Udp.write(txBuffer);
- Udp.endPacket();
- }
- }
Add Comment
Please, Sign In to add comment