Read integer from UDP

Hi guys, can anyone help me how can I read the integer from UDP with below sketch?

the sketch:

sender side:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "MikroTik";
const char* password = "12345678";
unsigned int localPort = 2390; 

WiFiUDP Udp;
void setup() {
    delay(1000);
    Serial.begin(115200);
    WiFi.begin(ssid, password);
  Udp.begin(localPort);
}

void loop() {
 Udp.beginPacket("10.5.50.23", localPort);
 Udp.write(analogRead(A0));
 Udp.endPacket();
 delay(10);
}

receiver side:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "MikroTik";
const char* password = "12345678";
unsigned int localPort = 2390; 
char packetBuffer[255];
WiFiUDP Udp;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }
  Udp.begin(localPort);
}

void loop() {
  delay(10);
  if (Udp.parsePacket()) {
    int len = Udp.read(packetBuffer, 255);
    if (len > 0) {
      packetBuffer[len] = 0;
      Serial.println(packetBuffer); 
    }
  }
}

The write(uint8_t) method writes a byte to the UDP packet. analogRead() returns an int (2 byte value) which will get truncated to one byte by the write(uint8_t) method. You should read the analog into an int variable and then use the write(const uint8_t *buffer, size_t size) method.

Your receiver is assuming it is receiving an ASCII string. You need to read the binary data and place it into an integer variable. Alternatively, you can convert the analog value in the transmitter to an ASCII string and transmit it as such.

1 Like

thanks for reply. I changed the Udp.write to Udp.print and the problem solved.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.