problem with UDP.print()

Hi everyone
my problem is that i want the send 3 sensor data over ethernet UDP in one time
and i don’t know the way to do that
thank’s for your time

#include <Ethernet.h> //Load Ethernet Library
#include <EthernetUdp.h> //Load UDP Library
#include <SPI.h> //Load the SPI Library

byte mac = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE}; //Assign a mac address
IPAddress ip(192, 168, 1, 252); //Assign my IP adress
unsigned int localPort = 4000; //Assign a Port to talk over
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
String datReq; //String for our data
int packetSize; //Size of Packet
EthernetUDP Udp; //Define UDP Object
float temp; //temp means temperature
float speed;
float charge;
float dataSend = {temp, speed, charge};
int temp_ADC;
int speed_ADC;
int charge_ADC;

void setup() {

Serial.begin(9600); //Turn on Serial Port
Ethernet.begin(mac, ip); //Initialize Ethernet
Udp.begin(localPort); //Initialize Udp
delay(1500); //delay
}

void loop() {

packetSize = Udp.parsePacket(); //Read theh packetSize

if(packetSize>0){ //Check to see if a request is present

Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Reading the data request on the Udp
String datReq(packetBuffer); //Convert packetBuffer array to string datReq

if (datReq ==“ordre”) { //See if Red was requested

temp_ADC = analogRead(0); //read analog input on pin A0
temp = temp_ADC * 5.0 * 100.0/1024.0; // ADC to celcius conversion
speed = analogRead(1); //read analog input on pin A1
charge= analogRead(2); //read analog input on pin A2
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize Packet send
Udp.print(temp); //Send string back to client
Udp.print(speed); //Send string back to client
Udp.print(charge); //Send string back to client
Udp.endPacket(); //Packet has been sent
delay(1500); //delay

}
}
memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE);

}

You forgot to say what your sketch was doing wrong.

You also forgot to say what device/application will be receiving the packet.

the client is python

the problem is ; iwant the send a packed contain 3 sensor data in one time because python read the 3 sensor data in one time to do a live plot

Is the python script sending a packet to the Arduino, then the Arduino sends the data back to the python script?

In what format is the python script expecting the data? Text or raw?

yes python send dataReq and the arduino response

the python expect Text

I do it the other way around, but maybe my code will help you. I found it is better to use the Arduino as the “client” and the PC as the “server”.

Here is my Arduino “client” code. It sends a packet to the “server” (python script) and gets a response packet. Change the network settings, UDPport and UDPServer variables. Or you can use dhcp to get an IP.

#include <SPI.h>         
#include <Ethernet.h>
#include <EthernetUdp.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {  
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192,168,2,2);
IPAddress gateway(192,168,2,1);
IPAddress subnet(255,255,255,0);

unsigned int UDPport = 5005;// local port to listen for UDP packets

IPAddress UDPServer(192,168,1,253); // destination device server

const int UDP_PACKET_SIZE= 48;

byte packetBuffer[ UDP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 

unsigned int noChange = 0;

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

unsigned long currentTime;
unsigned long secondTime;

unsigned long msPerSecond = 100UL;

int UDPCount = 0;

void setup() 
{
  Serial.begin(115200);

  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

//  pinMode(10,OUTPUT);
//  digitalWrite(10,HIGH);

// start Ethernet and UDP
  Serial.print(F("Starting w5100..."));
  Ethernet.begin(mac,ip,gateway,gateway,subnet);

/*
  while(!Ethernet.begin(mac)) {
    Serial.println(F("failed. Retrying in 5 seconds."));
    delay(5000);
    Serial.print(F("Starting w5100..."));
  }
*/

  Serial.println(Ethernet.localIP());
  
  Udp.begin(UDPport);

  delay(2000);

  currentTime=millis();
  secondTime = currentTime;
  
  Serial.println("Ready");
}



void loop()
{
  currentTime = millis();

  getUDPpacket();


  if(currentTime - secondTime > msPerSecond) {
      byte rtnVal = Ethernet.maintain();
      switch(rtnVal) {
        case 1: Serial.println(F("\r\nDHCP renew fail"));        
                break;
        case 2: Serial.println(F("\r\nDHCP renew ok"));        
                break;
        case 3: Serial.println(F("\r\nDHCP rebind fail"));        
                break;
        case 4: Serial.println(F("\r\nDHCP rebind ok"));        
                break;
                
      }
      
          
      Serial.println(F("\r\nUDP send"));
      sendUDPpacket(UDPServer); // send an NTP packet to a time server
      secondTime += msPerSecond;
  }
}

unsigned int udpCount = 0;

// send an NTP request to the time server at the given address 
unsigned long sendUDPpacket(IPAddress& address)
{
  udpCount++;
  
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, UDP_PACKET_SIZE); 


  sprintf((char*)packetBuffer,"Arduino count %u",udpCount);

  Udp.beginPacket(address, UDPport); //NTP requests are to port 123
  Udp.write(packetBuffer,UDP_PACKET_SIZE);
  Udp.endPacket(); 
}


void getUDPpacket() {
  if ( Udp.parsePacket() ) {  
    // We've received a packet, read the data from it

    if(Udp.remoteIP() == UDPServer) {
      Serial.print(F("UDP IP OK  "));
    }
    else {
      Serial.println(F("UDP IP Bad"));
      return;
    }
    if(Udp.remotePort() == UDPport) {
      Serial.println(F("Port OK"));
    }
    else {
      Serial.println(F("Port Bad"));
      return;
    }

    
    Udp.read(packetBuffer,UDP_PACKET_SIZE);  // read the packet into the buffer

    Serial.print(F("Received: "));
    Serial.println((char*)packetBuffer);
  }
}

Here is the python script. It is very basic. It waits for a packet from the Arduino, then sends a response. Change the IP to the PC running the python script.

import socket

UDP_IP = "192.168.1.253"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
	data, addr = sock.recvfrom(48) # buffer size is 48 bytes
	print "received message:", data, " from ", addr[0], " port ",addr[1]
	sock.sendto(data, (addr[0], addr[1]))

im so sorry im new with arduino can you explain more the arduino sketch

im so confused

i have 4 sensor on analog pin 1, 2, 3 and 4 and i want to read those pin and send the value over udp

The sketch and script are about as simple as UDP can get.

The Arduino checks for a UDP packet every time through the loop. It insures the packet is from the same IP and port it sent the packet to.

It sends a UDP packet 10 times per second to the server. You can change that by modifying the msPerSecond variable.

Read the pins, then send them in the packet as text using some type of separator, like a comma.

plz chek the code there is problem

im too much confused

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192,168,1,4);
IPAddress gateway(192,168,2,1);
IPAddress subnet(255,255,255,0);

unsigned int UDPport = 5005;// local port to listen for UDP packets

IPAddress UDPServer(192,168,1,4); // destination device server

const int UDP_PACKET_SIZE= 48;

byte packetBuffer[ UDP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

unsigned int noChange = 0;

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

unsigned long currentTime;
unsigned long secondTime;

unsigned long msPerSecond = 100UL;

int UDPCount = 0;
int temp_ADC;
float temp; //temp means temperature
float speed;
float charge;
float courant;

void setup()
{
Serial.begin(115200);

pinMode(4,OUTPUT);
digitalWrite(4,HIGH);

// pinMode(10,OUTPUT);
// digitalWrite(10,HIGH);

// start Ethernet and UDP
Serial.print(F(“Starting w5100…”));
Ethernet.begin(mac,ip,gateway,gateway,subnet);

/*
while(!Ethernet.begin(mac)) {
Serial.println(F(“failed. Retrying in 5 seconds.”));
delay(5000);
Serial.print(F(“Starting w5100…”));
}
*/

Serial.println(Ethernet.localIP());

Udp.begin(UDPport);

delay(2000);

currentTime=millis();
secondTime = currentTime;

Serial.println(“Ready”);
}

void loop()
{
currentTime = millis();

getUDPpacket();

if(currentTime - secondTime > msPerSecond) {
byte rtnVal = Ethernet.maintain();
switch(rtnVal) {
case 1: Serial.println(F("\r\nDHCP renew fail"));
break;
case 2: Serial.println(F("\r\nDHCP renew ok"));
break;
case 3: Serial.println(F("\r\nDHCP rebind fail"));
break;
case 4: Serial.println(F("\r\nDHCP rebind ok"));
break;

}

temp_ADC = analogRead(0); //read analog input on pin A0
temp = temp_ADC * 5.0 * 100.0/1024.0; // ADC to celcius conversion
speed = analogRead(1); //read analog input on pin A1
charge = analogRead(2); //read analog input on pin A2
courant = analogRead(3); //read analog input on pin A3
// packetBuffer = (‘temp’, ‘speed’, ‘charge’, ‘courant’);

Serial.println(F("\r\nUDP send"));
sendUDPpacket(UDPServer); // send an NTP packet to a time server
secondTime += msPerSecond;
}
}

unsigned int udpCount = 0;

// send an NTP request to the time server at the given address
unsigned long sendUDPpacket(IPAddress& address)
{
udpCount++;

// set all bytes in the buffer to 0
memset(packetBuffer, 0, UDP_PACKET_SIZE);

sprintf((char*)packetBuffer,“Arduino count %u”,udpCount);

Udp.beginPacket(address, UDPport); //NTP requests are to port 123
Udp.write(packetBuffer,UDP_PACKET_SIZE);
Udp.endPacket();
}

void getUDPpacket() {
if ( Udp.parsePacket() ) {
// We’ve received a packet, read the data from it

if(Udp.remoteIP() == UDPServer) {
Serial.print(F("UDP IP OK "));
}
else {
Serial.println(F(“UDP IP Bad”));
return;
}
if(Udp.remotePort() == UDPport) {
Serial.println(F(“Port OK”));
}
else {
Serial.println(F(“Port Bad”));
return;
}

Udp.read(packetBuffer,UDP_PACKET_SIZE); // read the packet into the buffer

Serial.print(F("Received: "));
Serial.println((char*)packetBuffer);
}
}

You must use the PC IP for the UDPServer variable. You have the Arduino trying to send a packet to itself.

and what about put temp speed charge courant in packet and sended

it show a problem and i put it like comment (//)

Do the packet assembly in the sendUDPPacket function.

// here is where you put your data into the packet
  sprintf((char*)packetBuffer,"%u,%u,%u",speed, charge,current);

  Udp.beginPacket(address, UDPport); //NTP requests are to port 123
// here is where you send it
  Udp.write(packetBuffer,UDP_PACKET_SIZE);
  Udp.endPacket();

thank's a lot