Arduino WiFi Shield UDP Support

hey don't worry it was a joke :slight_smile:

About my code: actually I don't have any error, it compiles and run without any issue, but the problem is that the server on the listening machine isn't receiving anything....
Is the initialization of your class correct? Is it right I'm initializing it like this:

Udp.begin(receiverPort);

...using receiverPort as argument?

Is the composition of the UDP message correct?
Thank you again

srrichie:
Is the initialization of your class correct? Is it right I'm initializing it like this:

Udp.begin(receiverPort);

...using receiverPort as argument?

Is the composition of the UDP message correct?

Well yes and no.
If you look at the header file of WifiUDP ( Arduino/WiFiUdp.h at wifishield-bugfix · mlafauci/Arduino · GitHub ), you'll see that the method is commented like this:

  virtual uint8_t begin(uint16_t);	// initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use

so it's expecting you to pass the port the Arduino should listen on, not the one to send to. But since you are not listening on the Arduino and the local and remote port can be the same, this shouldn't be a problem.

The construction of your UDP message

Udp.beginPacket(receiverIP, receiverPort); //start udp packet
  Udp.write(valueInBytes, 8); //write sensor data to udp packet
  Udp.endPacket(); // end packet

looks right to me.
It's difficult to debug these kind of things from a distance. What I would do in such a case is try with the simplest setup that works and then change the code until it breaks. Step by step, compiling and testing with every change. At a certain point it will stop working.
So I would suggest you start with my example, start changing things and see how far you can get.
I would start by checking these:

  • do you really want delay(10000); // 10sec delay?
  • is the receiving computer really at IP 192.168.1.212 ? and is it listening at port 9100 ?
  • more really obvious mistakes that are easy to overlook :slight_smile:

Yes, I'm trying to broke apart the problems.

The first thing that looks strange is that I've tried to connect to different routers/networks, and my Arduino always Seruial.prints this networks info:

Attempting to connect to WPA SSID: phwifi
You're connected to the networkSSID: phwifi
BSSID: 0:0:0:0:0:0
signal strength (RSSI):0
Encryption Type:0

IP Address: 192.168.2.6

where the IP obviosly changes, but the other info are always zero.....

IP Address: 192.168.2.6

Just a wild guess: is it possible the receiving ip should be something like 192.168.2.something... instead of the 192.168.1.212 you were using? usually when you are on the same network, the range of IPs is limited so only the last byte is different.

I have no idea why you get this weird output like

signal strength (RSSI): 0
Encryption Type: 0

did you correctly upgrade the WifiShield firmware? Are you using the correct library?

The ip class has changed from the previously code because I'm trying different networks, sorry about the confusion
About the firmware upgrade, I'm pretty sure I did follow your instructions :frowning:

I was just reading this interesting post and trying to understand if there are any differences:

I also read that page when I was still trying with the old buggy firmware.
You can ignore everything on that page except the part about updating ports. That's the only thing I didn't document in my post I think.

Hi Tim - Thanks. Looks like I may have to do some research on DFU programming from Windows and then try the firmware update. Derek

Tim,
about your instructions: when you say to update /Applications/Arduino_104_UDP.app/Contents/Resources/Java/hardware/arduino/firmwares/wifishield/scripts/ArduinoWifiShield_upgrade.sh

should I also update the file
/Applications/Arduino_104_UDP.app/Contents/Resources/Java/hardware/arduino/firmwares/wifishield/scripts/ArduinoWifiShield_upgrade_mac.sh
?

Thanks

By the way, sorry for the late info but I've realized I'm using a shield with the HDG204 chip

So, after 30 hours of craziness, debug, trial and error, I went directly to show the board to one of the guys of Officine Arduino here in Italy.
And it looks like the shield is defective.
OMG.
:slight_smile:
Thanks you all for the support

Hey Tim !

Indeed while copying the code I added a "z" in it but it "works" here it is with the same bug i was talking about earlier :

#include <SPI.h>
#include <WiFI.h>
#include <WiFiUdp.h>
#include <Time.h>

int status = WL_IDLE_STATUS;
char ssid[] = "SSID"; // your network SSID (name) Your network name here, case sensitive!
char pass[] = "pass";  // if your network doesn't use WPA or WEP, change the line below that says "status = WiFi.begin(ssid, pass);"

/* ******** NTP Server Settings ******** */
/* us.pool.ntp.org NTP server 
   (Set to your time server of choice) */
IPAddress timeServer(64, 90, 182, 55); 

/* Set this to the offset (in seconds) to your local time
   This example is GMT + 2 */
const long timeZoneOffset = 7200L;   

/* Syncs to NTP server every 15 seconds for testing, 
   set to 1 hour or more to be reasonable */
unsigned int ntpSyncTime = 15;         


/* ALTER THESE VARIABLES AT YOUR OWN RISK */
// local port to listen for UDP packets
unsigned int localPort = 8888;
// NTP time stamp is in the first 48 bytes of the message
const int NTP_PACKET_SIZE= 48;      
// Buffer to hold incoming and outgoing packets
byte packetBuffer[NTP_PACKET_SIZE];  
// A UDP instance to let us send and receive packets over UDP
WiFiUDP Udp;                    
// Keeps track of how long ago we updated the NTP server
unsigned long ntpLastUpdate = 0;    
// Check last time clock displayed (Not in Production)
time_t prevDisplay = 0;             

void setup() {
   Serial.begin(9600);
   
     // make a little light show on the WifiShield
  pinMode(9, OUTPUT);
  for(int i = 0; i < 50; i++){
    digitalWrite(9, HIGH);
    delay(i);
    digitalWrite(9, LOW);
    delay(i);
    
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present"); 
    // don't continue:
    while(true);
  } 
  Serial.println("Wifi Shield present");

  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED) { 
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:    
    status = WiFi.begin(ssid, pass); 

    // wait 10 seconds for connection:
    delay(10000);
  } 
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
   
   //Try to get the date and time
   int trys=0;
   while(!getTimeAndDate() && trys<10) {
     trys++;
   }
}

// Do not alter this function, it is used by the system
int getTimeAndDate() {
   int flag=0;
   Udp.begin(localPort);
   sendNTPpacket(timeServer);
   delay(1000);
   if (Udp.parsePacket()){
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer
     unsigned long highWord, lowWord, epoch;
     highWord = word(packetBuffer[40], packetBuffer[41]);
     lowWord = word(packetBuffer[42], packetBuffer[43]);  
     epoch = highWord << 16 | lowWord;
     epoch = epoch - 2208988800 + timeZoneOffset;
     flag=1;
     setTime(epoch);
     ntpLastUpdate = now();
   }
   return flag;
}

// Do not alter this function, it is used by the system
unsigned long sendNTPpacket(IPAddress& address)
{
  memset(packetBuffer, 0, NTP_PACKET_SIZE); 
  packetBuffer[0] = 0b11100011;
  packetBuffer[1] = 0;
  packetBuffer[2] = 6;
  packetBuffer[3] = 0xEC;
  packetBuffer[12]  = 49; 
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;		   
  Udp.beginPacket(address, 123);
  Udp.write(packetBuffer,NTP_PACKET_SIZE);
  Udp.endPacket();
}

// Clock display of the time and date (Basic)
void clockDisplay(){
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year()); 
  Serial.println(); 
}

// Utility function for clock display: prints preceding colon and leading 0
void printDigits(int digits){
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

// This is where all the magic happens...
void loop() {
    // Update the time via NTP server as often as the time you set at the top
    if(now()-ntpLastUpdate > ntpSyncTime) {
      int trys=0;
      while(!getTimeAndDate() && trys<10){
        trys++;
      }
      if(trys<10){
        Serial.println("ntp server update success");
      }
      else{
        Serial.println("ntp server update failed");
      }
    }
    
    // Display the time if it has changed by more than a second.
    if( now() != prevDisplay){
      prevDisplay = now();
      clockDisplay();  
    }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

ohhopi:
Indeed while copying the code I added a "z" in it but it "works" here it is with the same bug i was talking about earlier :

Hi Ohhopi,

So I understand you still get the same feed back from Serial: "ntp server update failed"

What did you try to find where the bug is? Did you try my suggestion to start from a tested working example and seeing when it starts failing? Another good thing to do is add a lot of debug printouts. So everytime you think your code does something the Serial prints this out for you so you are sure it is actually the way you expect it to be.

One thing I see that is probably not right is this:
in getTimeAndDate() :

   sendNTPpacket(timeServer);
   delay(1000);

Which means you are doing this request every second. According to this pagehttp://tf.nist.gov/tf-cgi/servers.cgi you shouldn't query the servers more than once every 4 seconds. You'll see in the UDPNTPClient example that they wait 10 seconds between each call.

I understand what do you say before...but if i want to the udp connection with the shield wifi(R3) plus an arduino Due what i have to do, because i follow the same passage but something goes wrong. This is the message

In file included from c:\users\alepao\desktop\arduino-1.5.2\hardware\tools\g++_arm_none_eabi\bin../lib/gcc/arm-none-eabi/4.4.1/../../../../arm-none-eabi/include/stdio.h:46,
from C:\Users\alepao\Documents\Arduino\libraries\WiFi/utility/debug.h:13,
from C:\Users\alepao\Documents\Arduino\libraries\WiFi\WiFiClient.cpp:6:
c:\users\alepao\desktop\arduino-1.5.2\hardware\tools\g++_arm_none_eabi\bin../lib/gcc/arm-none-eabi/4.4.1/../../../../arm-none-eabi/include/sys/types.h:93: error: conflicting declaration 'typedef short unsigned int u_short'
C:\Users\alepao\Documents\Arduino\libraries\WiFi\utility/socket.h:71: error: 'u_short' has a previous declaration as 'typedef uint16 u_short'
C:\Users\alepao\Documents\Arduino\libraries\WiFi\WiFiClient.cpp: In member function 'virtual int WiFiClient::read(uint8_t*, size_t)':
C:\Users\alepao\Documents\Arduino\libraries\WiFi\WiFiClient.cpp:107: error: no matching function for call to 'ServerDrv::getDataBuf(uint8_t&, uint8_t*&, size_t*)'
C:\Users\alepao\Documents\Arduino\libraries\WiFi\utility/server_drv.h:26: note: candidates are: static bool ServerDrv::getDataBuf(uint8_t, uint8_t*, uint16_t*)

Hi,

I have manage to make the UDP work properly on the WIFI shield without too much hassle.
The new version of the Arduino environment (1.0.5) already includes the WIFI shield libraries, and among its examples it has one that uses UDP: go to Examples -> WIFI -> WifiUdpNtpClient

First try:

I have just uploaded the sketch to the Arduino (after setting the proper WIFI SSID and password) but it did not work. In fact, watching at the messages on the serial port I saw:

Attempting to connect to SSID: XXXX
Connected to wifi
SSID: LST-D204
IP Address: 192.168.1.132
signal strength (RSSI):-53 dBm

Starting connection to server...
0
0
0
0
0

At some point, where in the Arduino sketch says Serial.println( Udp.parsePacket() ); it was printing me out this 0, meaning that probably the library was not supported by the firmware.

Firmware update:

Be careful about the firmware. It seems that there are two git repositories with the shield's code

this: GitHub - arduino/wifishield: Arduino Wifi Shield

and this: https://github.com/arduino/Arduino/tree/master/hardware/arduino/firmwares/wifishield/binary

I have used the second one, which was more recent and I think is also the one that is more official, so remember, WIFI shield's firmware is here:
https://github.com/arduino/Arduino/tree/master/hardware/arduino/firmwares/wifishield/binary !!!!!

You have to donwload the files wifi_dnld.elf and wifiHD.elf.

Then I have followed the instructions given here:

they are not very good, but all the steps are described at least.
As I work on Windows I had to download the Atmel's tools here http://www.atmel.com/tools/FLIP.aspx

Then I removed the shield from the Arduino, put the jumper in programming mode and connected the mini USB port to the computer.
If the driver for the AT32UC3 is not found you have it available in your computer inside the Flip folder, in my case here: C:\Program Files (x86)\Atmel\Flip 3.4.7\usb

The I have updated BOTH the HDG104 and the AT32UC3 firmwares.
For updating the HDG104 firmware type:

C:\Program Files (x86)\Atmel\Flip 3.4.7\bin>batchisp.exe -device AT32UC3A1256 -hardware usb -operation erase f memory flash blankcheck loadbuffer D:\D
ownloads\Development\Arduino\wifi_dnld.elf program verify start reset 0

(will have to change the path to the wifi_dnld.elf file that you have downloaded from the GIT repository)

you will see:

Running batchisp 1.2.5 on Fri May 31 14:17:14 2013

AT32UC3A1256 - USB - USB/DFU


Device selection....................... PASS
Hardware selection..................... PASS
Opening port........................... PASS
Reading Bootloader version............. PASS    1.0.2
Erasing................................ PASS
Selecting FLASH........................ PASS
Blank checking......................... PASS    0x00000 0x3ffff
Parsing ELF file....................... PASS    D:\Downloads\Development\Arduino\wifi_dnld.elf
WARNING: The user program and the bootloader overlap!
Programming memory..................... PASS    0x00000 0x2902b
Verifying memory....................... PASS    0x00000 0x2902b
Starting Application................... PASS    RESET   0

Summary:  Total 11   Passed 11   Failed 0

Then for updating AT32UC3 firmware you have to type:

C:\Program Files (x86)\Atmel\Flip 3.4.7\bin>batchisp.exe -device AT32UC3A1256 -hardware usb -operation erase f memory flash blankcheck loadbuffer D:\D
ownloads\Development\Arduino\wifiHD.elf program verify start reset 0

In my case, after the previous update, the board got stuck so I got:

Running batchisp 1.2.5 on Fri May 31 14:18:09 2013

AT32UC3A1256 - USB - USB/DFU


Device selection....................... PASS
Hardware selection..................... PASS
Opening port........................... AtLibUsbDfu: 3EB 2FF8 no device present.
FAIL    Could not open USB device.
ISP done.

So I just removed the USB cable and put it back again, so once again:

C:\Program Files (x86)\Atmel\Flip 3.4.7\bin>batchisp.exe -device AT32UC3A1256 -hardware usb -operation erase f memory flash blankcheck loadbuffer D:\D
ownloads\Development\Arduino\wifiHD.elf program verify start reset 0

and you'll see:

Running batchisp 1.2.5 on Fri May 31 14:26:28 2013



AT32UC3A1256 - USB - USB/DFU


Device selection....................... PASS
Hardware selection..................... PASS
Opening port........................... PASS
Reading Bootloader version............. PASS    1.0.2
Erasing................................ PASS
Selecting FLASH........................ PASS
Blank checking......................... PASS    0x00000 0x3ffff
Parsing ELF file....................... PASS    D:\Downloads\Development\Arduino\wifiHD.elf
WARNING: The user program and the bootloader overlap!
Programming memory..................... PASS    0x00000 0x3fe2b
Verifying memory....................... PASS    0x00000 0x3fe2b
Starting Application................... PASS    RESET   0

Summary:  Total 11   Passed 11   Failed 0

Good! now connect the Wifi Shield to the Arduino again and run the WifiUdpNtpClient example.
If everything works you should see on your serial port:

Attempting to connect to SSID: XXXX
Connected to wifi
SSID: LST-D204
IP Address: 192.168.1.132
signal strength (RSSI):-53 dBm

Starting connection to server...
48
packet received
Seconds since Jan 1 1900 = 3578992778
Unix time = 1370003978
The UTC time is 12:39:38

which means that everything is working :wink:

Hi everyone

I'm trying to use WiFiUdp.h with Arduino DUE R3 and WiFi Shield R3.
For reason I'm not able to load e WiFi Udp NTP Client.

Is there any support for Arduino DUE for WiFiUdp.h?

I'm missing something?

Any help will be greatly appreciated.

Thanks

Many thanks Tim !

Now UDP Communication works fine :slight_smile:

Max

Many thanks dariosalvi! Your tutorial helped me get my brand new wifi shield working with UDP and TCP connections. Cheers! :slight_smile:

Many thanks dariosalvi, I followed your procedure and got the exact screen printout as yours in upgrading the shield. However when I put the shield back and tried the WiFiUdpNtpClient, I didn't get the same result, looks like that I can't connect to the server. What I discovered is that the router returned an IP address of 0.0.0.0, then I used the scanNetworks sketch to check on the router I used. What I found is that this sketch showed my shield's MAC address is 0:0:0:0:0:0 ! As I remembered my shield MAC address was some number other than all zeros! Does that mean I eraseed the MAC address also during the upgrade? Anyone has the same problem? Help please!

Hi everyone!!!
I have a bit problem with example WiFiUdpSendRecieveSting
First time I debug, it works very well. (I send 3 string "acb")

Port open
Attempting to connect to SSID: Connectify-Minh
Connected to wifi
SSID: Connectify-Minh
IP Address: 192.168.12.101
signal strength (RSSI):-49 dBm

Starting connection to server...
Received packet of size 3
From 192.168.12.1, port 2390
Contents:
acb
Received packet of size 3
From 192.168.12.1, port 2390
Contents:
acb
Received packet of size 3
From 192.168.12.1, port 2390
Contents:
acb

Second time I debug, it just recieved once and didn't send "acknowledged".... (I send 3 string "acb")

Port open
Attempting to connect to SSID: Connectify-Minh
Connected to wifi
SSID: Connectify-Minh
IP Address: 192.168.12.101
signal strength (RSSI):-49 dBm

Starting connection to server...
Received packet of size 3
From 0.0.0.0, port 0
Contents:
123

Third time, it doesn't run anymore.

Port open

Plz show me my misstake!!! Thank for your help :smiley: