Ethernet client and UDP together in same sketch

Hello

I'm trying to run Ethernet client to write data in a mysql server and read UDP to turn on/off functions on arduino.

I have already wrote 2 sketchs one for ethernet and one for UDP, they are running properly but when I try to join them in the same sketch, Udp doesn't run...

client sketch :

/////////////////////////////
// mode client //
// charge la page bdd.php //
// avec la température en argument //
// FONCTIONNEL //
/////////////////////////////

#include <Ethernet.h> //library for ethernet functions
#include <Client.h> //library for client functions
#include <SPI.h>

// Ethernet settings
uint8_t hwaddr[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xBA, 0xBE}; // mac-adress of arduino
//uint8_t ipaddr[4] = {192, 168, 0, 17}; // IP-adress of arduino
//uint8_t gwaddr[4] = {192, 168, 0, 1}; // IP-adress of gateway ( for later DNS implementation)
//uint8_t subnet[4] = {255, 255, 255, 0}; // subnetmask ( for later DNS implementation)
uint8_t serverip[4] = {88,167,XXX,XXX}; // IP-adress of server arduino sends data to

uint8_t serverport = 80; // the port the arduino talks to

EthernetClient client; // make a new instance from type "Client" named "client", giving it
// serverip and serverport
int timeout=0;
bool req_sended = 0;
bool connected = false; // yes-no variable (boolean) to store if the arduino is connected to the server
int i = 0; // variable to count the sendings to the server

//--------------------------

// heure
//int refresh=0;
int top=0;
int last_top=0;
int seconde=50;
int seconde2=0;
int minute=59;
int heure=23;
long last_time=0;
int dizaine;
//---------------------------

long freq=0;

void setup(void) // setup-function runs at the startup of the arduino
{ pinMode(9, OUTPUT);
digitalWrite(9, HIGH);

Serial.begin(9600); // start the serial port
Serial.println("demarrage...");

Ethernet. begin(hwaddr); // start up ethernet
digitalWrite(9, LOW);
}

void loop(void) // loop function runs over and over again
{

freq++;

//if (((minute%5)==0&&seconde==0)&&req_sended==0)
if ((seconde==0||seconde==30)&&req_sended==0)
{ //Serial.println(seconde);
timeout=0;
if(!connected) { // if "not" connected print: not connected :wink:
Serial.println();
Serial.println(" <----===========---->");
//Serial.println("Not connected");
digitalWrite(9, HIGH);
if (client.connect(serverip, 80)){ // if connected, set variable connected to "true" and
connected = true;

//delay(100);

client.print("GET /arduino/bdd.php?temp=22");
Serial.print("GET /arduino/bdd.php?temp=22");

client.println(" HTTP/1.1");
Serial.println(" HTTP/1.1");
client.println("Host: www.google.fr");
Serial.println("Host: www.google.fr");
client.println("User-Agent: Arduino");
Serial.println("User-Agent: Arduino");
client.println("Accept: text/html");
Serial.println("Accept: text/html");
client.println("Connection: close");
Serial.println("Connection: close");
client.println();
Serial.println();
req_sended=1;
}
else{
Serial.println("Cannot connect to Server"); // else block if the server connection fails (debugging)

}
}
while (!client.available() && timeout<200) {
timeout++; if(timeout==200){Serial.print("Time out !"); Serial.println(timeout);} delay(25); }
Serial.print("Delay : ");Serial.println(timeout);
digitalWrite(9, LOW);
}

//delay(500); //
while (client.connected() && client.available()) { // when connected and availabe:
char c = client.read(); // read the answer of the server and
Serial.print(c); // print it to serial port
} //
//Serial.println(); //
client.stop(); // stop the connection and set
connected = false; // "connected" to false

//delay(1000);
horloge();

if(top==2){top=0; //on remet le compteur des tops seconde à 0
req_sended=0;
//Serial.println();Serial.print("freq : ");Serial.println(freq);
freq=0;}

}

int horloge()
{

if(millis()-last_time>=500)
{ last_time=millis();
top++;

if(top==2){seconde+=1;}//incrementation des secondes toutes les 2x 500ms

if(seconde>59)//incrementation des minutes
{seconde=0; minute=minute++;}

if(minute>59)//incrementation des heures
{minute=0;heure=heure++;}

if(heure>23)
{heure=0;}

//---------- affichage heures min sec et séparateurs
//if(seconde%2==0){lcd.setCursor(8, 1); lcd.print(" ");}//si secondes sont paires, affiche separateur droit
//else{lcd.setCursor(8, 1); lcd.print(":");} //sinon affiche le separateur gauche

dizaine=((heure*60+minute)/10);

//affiche_heure();

}

return dizaine;
return top;

}

UDP sketch :

//////////////////////////////////
// FADER DIODE SUR PORT 9 //
// EN UDP AVEC SCRIPT PHP AJAX //
// IP: 192, 168, 0, 10 //
// PORT 8888 //
//////////////////////////////////

#include <SPI.h> // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 0, 10 }; // ip in lan
//byte gateway[] = { 192, 168, 0, 1 }; // internet access via router
//byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
//EthernetServer server = EthernetServer(80); //port 80

unsigned int localPort = 8888; // local port to listen on

// the next two variables are set when a packet is received
byte remoteIp[4]; // holds received packet's originating IP
unsigned int remotePort; // holds received packet's originating port

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged"; // a string to send back
EthernetUDP Udp;
void setup() {
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);

Serial.begin(9600);
}

void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote*, DEC);*

  • if (i < 3)*

  • {*

  • Serial.print(".");*

  • }*

  • }*

  • Serial.print(", port ");*

  • Serial.println(Udp.remotePort());*

  • memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE);*

  • // read the packet into packetBufffer and get the senders IP addr and port number*

  • Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);*

  • Serial.println("Contents:");*

  • Serial.println(packetBuffer);*

  • analogWrite(9, atoi(packetBuffer)); //utiliser la valeur reçu pour allumer la led*

  • }*

  • //delay(250);*
    }

    PHP script for udp :

    <?php* *$valeur_led = $_POST["led1"]; // récupération de la valeur transmise en méthode POST* *$host="88.167.XXX.XXX"; // Adresse ip défini dans le code arduino* *$port=8888; // Port défini dans le code arduino* *$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);* *socket_sendto($socket, $valeur_led , strlen($valeur_led), 0, $host, $port);* *socket_close($socket);* *?>
    [/quote]
    An Idea?
    Thank u for your help

This is the script where udp doesn't work:

/////////////////////////////
// mode client //
// charge la page bdd.php //
// avec la température en argument //
// FONCTIONNEL //
/////////////////////////////

#include <Ethernet.h> //library for ethernet functions
#include <Client.h> //library for client functions
#include <SPI.h>
#include <EthernetUdp.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008

// Ethernet settings
uint8_t hwaddr[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xBA, 0xBE}; // mac-adress of arduino
uint8_t ipaddr[4] = {192, 168, 0, 10}; // IP-adress of arduino
uint8_t gwaddr[4] = {192, 168, 0, 254}; // IP-adress of gateway ( for later DNS implementation)
uint8_t subnet[4] = {255, 255, 255, 0}; // subnetmask ( for later DNS implementation)
uint8_t serverip[4] = {88,167,233,135}; // IP-adress of server arduino sends data to
uint8_t serverport = 80; // the port the arduino talks to
//byte ip[] = {88,167,233,135}; // ip in lan
byte ip[] = { 192, 168, 0, 10 }; // ip in lan

//IPAddress server(88,167,233,135);

unsigned int localPort = 8888; // local port to listen on
// the next two variables are set when a packet is received
byte remoteIp[4]; // holds received packet's originating IP
unsigned int remotePort; // holds received packet's originating port
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged"; // a string to send back
EthernetUDP Udp;

EthernetClient client; // make a new instance from type "Client" named "client", giving it
// serverip and serverport

bool connected = false; // yes-no variable (boolean) to store if the arduino is connected to the server
int i = 0; // variable to count the sendings to the server

//--------------------------

// heure
//int refresh=0;
int top=0;
int last_top=0;
int seconde=50;
int seconde2=0;
int minute=59;
int heure=23;
long last_time=0;
int dizaine;
//---------------------------

void setup(void) // setup-function runs at the startup of the arduino
{ pinMode(9, OUTPUT);
digitalWrite(9, HIGH);

Serial.begin(9600); // start the serial port
Serial.println("demarrage...");

Ethernet. begin(hwaddr,ip,gwaddr,subnet); // start up ethernet
digitalWrite(9, LOW);

// start the Ethernet and UDP:
// Ethernet.begin(mac,ip);
Udp.begin(localPort);

}

void loop(void) // loop function runs over and over again
{

listen_udp();

if (seconde==59)
{
digitalWrite(9, HIGH);
if(!connected) { // if "not" connected print: not connected :wink:
Serial.println("Not connected");

if (client.connect(serverip, 80)){ // if connected, set variable connected to "true" and
connected = true;

//delay(100);

client.print("GET /arduino/bdd.php?temp=22");
Serial.print("GET /arduino/bdd.php?temp=22");

client.println(" HTTP/1.1");
Serial.println(" HTTP/1.1");
client.println("Host: www.google.fr");
Serial.println("Host: www.google.fr");
client.println("User-Agent: Arduino");
Serial.println("User-Agent: Arduino");
client.println("Accept: text/html");
Serial.println("Accept: text/html");
client.println("Connection: close");
Serial.println("Connection: close");
client.println();
Serial.println();

}
else{
Serial.println("Cannot connect to Server"); // else block if the server connection fails (debugging)

}
}
else {

delay(200); //
while (client.connected() && client.available()) { // when connected and availabe:
char c = client.read(); // read the answer of the server and
Serial.print(c); // print it to serial port
} //
Serial.println(); //
client.stop(); // stop the connection and set
connected = false; // "connected" to false

}
digitalWrite(9, LOW);
//delay(1000);
}

horloge();
if(top==2){top=0; }//on remet le compteur des tops seconde à0

}

int horloge()
{

if(millis()-last_time>=500)
{ last_time=millis();
top++;

if(top==2){seconde+=1;}//incrementation des secondes toutes les 2x 500ms

if(seconde>59)//incrementation des minutes
{seconde=0; minute=minute++;}

if(minute>59)//incrementation des heures
{minute=0;heure=heure++;}

if(heure>23)
{heure=0;}

//---------- affichage heures min sec et séparateurs
//if(seconde%2==0){lcd.setCursor(8, 1); lcd.print(" ");}//si secondes sont paires, affiche separateur droit
//else{lcd.setCursor(8, 1); lcd.print(":");} //sinon affiche le separateur gauche

dizaine=((heure*60+minute)/10);

//affiche_heure();

}

return dizaine;
return top;

}

void listen_udp()
{
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote*, DEC);*

  • if (i < 3)*

  • {*

  • Serial.print(".");*

  • }*

  • }*

  • Serial.print(", port ");*

  • Serial.println(Udp.remotePort());*

  • memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE);*

  • // read the packet into packetBufffer and get the senders IP addr and port number*

  • Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);*

  • Serial.println("Contents:");*

  • Serial.println(packetBuffer);*

  • analogWrite(9, atoi(packetBuffer)); //utiliser la valeur reçu pour allumer la led*

  • }*
    }
    [/quote]
    Thank you again

This is incorrect:

Ethernet. begin(hwaddr,ip,gwaddr,subnet);                  // start up ethernet

There is no dns server ip. That follows the ip. Like this:

Ethernet. begin(hwaddr,ip,dns,gwaddr,subnet);                  // start up ethernet

If you are not using dns you can use the gateway ip

Ethernet. begin(hwaddr,ip,gwaddr,gwaddr,subnet);                  // start up ethernet

See if that is better.

Hello SurferTim,

You know what?

That's working good !!!!!!!!!!

Thank you so much.

Bye

Fly

Sorry for my english :wink:

Me again :wink:

All is ok on local server

Now I try to upload PHP files on distant server, client function is ok but UDP doesn't work.

Probably IP settings...

Bye

That looks like you are trying to receive UDP packets with a function name of listen_udp(), but unless your router forwards the UDP packet and performs a Network Address Translation on it, you will not get it from a public ip address. You would be limited to receiving (server) from localnet ips only. But client is ok anywhere.

Thank you for reply,

My router (freebox) is setup to translate UDP abd TCP port 8888 on 192.168.0.10:8888.

I don't know if PHP server socket module is enabled... How can I check it?

Fly

For information this is the warning I get:

Warning: socket_sendto() [function.socket-sendto]: unable to write to socket [101]: Network is unreachable in /mnt/165/sdb/a/b/roupet/arduino/udp_control_led.php on line 10

:~

flyaway:
For information this is the warning I get:

Warning: socket_sendto() [function.socket-sendto]: unable to write to socket [101]: Network is unreachable in /mnt/165/sdb/a/b/roupet/arduino/udp_control_led.php on line 10

:~

That usually means you are referring to a localnet address that does not exist. If the NAT in the router is functioning, you should access it by using the public ip assigned to the wan interface on the router. Can you ping the public ip of your router from that server?

I have a PHP wamp server running on a PC behind this router and I'm able to reach it with public ip from anywhere.

When I try to make arduino running as a web server that's ok too from anywhere with public ip.

Is that the warning means that udp function is enabled on server? (the server is a free server provided by my internet provider).