I'm trying to have an arduino ethernet send UDP packets to a computer on a local network. I have my target server running at 10.2.12.39, listening on port 2011. My arduino ethernet connects with an IP at 10.2.12.36. Whenever a sensor reaches a threshold, the following code runs:
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <avr/wdt.h>
byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0x40, 0x9F};
byte ip[] = {10,2,12,36};
byte secondServer[] = {10,2,12,39};
int port = 2011;
char output[12];
EthernetUDP UdpClient;
//sensor parameters
byte NUM_SENSORS = 4;
byte readPin[] = {2,3,5,4};
byte ledPin[] = {6,7,8,9};
byte val[] = {0,0,0,0};
byte sensorState[] = {0,0,0,0};
String content;
void setup() {
wdt_enable(WDTO_8S);
Serial.begin(9600);
Serial.println("Opening Serial Port...");
Serial.println("Initializing HTTP Client...");
Ethernet.begin(mac, ip);
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
delay(1000);
for(int i = 0; i < NUM_SENSORS; i++) {
pinMode(readPin[i],INPUT);
pinMode(ledPin[i],OUTPUT);
}
}
void loop() {
wdt_reset();
/* READ SENSOR */
Serial.println("Checking card readers...");
for(int i = 0; i < NUM_SENSORS; i++) {
val[i] = digitalRead(readPin[i]);
if ((sensorState[i] ^ val[i]) & (!val[i])) {
//rising edge
Serial.println("Rising edge detected!");
content = "do 6 ";
content.concat(i+1);
content.concat(" card");
content.toCharArray(output, content.length());
Serial.println("Sending UDP packet to server.");
UdpClient.beginPacket(secondServer, port);
UdpClient.write(output);
UdpClient.endPacket();
Serial.println("UDP packet sent.");
digitalWrite(ledPin[i], 1);
}
else if ((sensorState[i] ^ val[i]) & (val[i])) {
//falling edge
Serial.println("Falling edge detected!");
digitalWrite(ledPin[i],0);
}
sensorState[i] = val[i];
}
delay(100);
}
String split(String data, char delimiter, int index) {
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==delimiter || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
I always receive the first message, and then the program hangs before displaying the second serial message (after the UDP.endpacket()). I'm using a watchdog timer set to 8 seconds, so after 8 seconds the program resets.
I've tried pinging the arduino from the computer on the network, and receive pings -- but i'm not sure how to check if the port's open by asking the arduino to ping the computer.
That said, my understanding was that UDP would effectively send-it-and-forget-it, so I'm a bit confused by why sending UDP packets is causing the arduino to hang. Any suggestions as to what's going on?