Hi,
this is the code. If I comment all related to udp it works normally but when not the board don´t respond to any request from the internet.
/* 6 Noviembre
Errores:
* #include <string.h>
myFile.print() no acepta un string crea archivos ilegibles
error, al crear un fichero FX.JS mete información de Y
* Alimentar XBee Shield con alimentacion aparte, se pueden generar picos de consumo
que resetea la placa
* Debug
#include <NewSoftSerial.h> o #include <SoftwareSerial.h>
NewSoftSerial mySerial( rxPin, txPin); o SoftwareSerial mySerial( rxPin, txPin)
Consideraciones:
* Direcciones: considera 1byte (1 al FE) hasta 254 modulos ( @miento: 2 bytes, 0xFFFF @broadcast)
Utilidades:
* #include <MemoryFree.h>
incluidas en el loop
Serial.print("freeMemory()=");
Serial.println(freeMemory());
* #include <utility/w5100.h> // Advance Ethernet functions
incluidas en el setup
W5100.setRetransmissionTime(0x07D0); //setRetransmissionTime sets the Wiznet's timeout period, where each unit is 100us, so 0x07D0 (decimal 2000) means 200ms.
W5100.setRetransmissionCount(3); //setRetransmissionCount sets the Wiznet's retry count.
*/
// Librerias:
#include <XBee.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h> // ocupa 5KB
#include <Udp.h>
// Variables Globales
#define PACKET_TYPE 0 // data[0]
#define PACKET_LENGTH 1 // data[1]
#define DATA_TYPE 2 // data[2]
#define REQUEST 1
#define RESPONSE 2
#define INFO 3
#define INIT 4
#define CONFIGURATION 0
#define TEMPERATURE_FIELD 3
#define HUMIDITY_FIELD 5
#define SLEEPCYCLE_FIELD 7
#define ASYNCHRONUS_FIELD 9
#define UID_FIELD 11
#define fioMax 30
#define bufferMax 128
#define ssPin 10
#define chipSelect 4
// XBee
XBee xbee = XBee();
XBeeResponse response = XBeeResponse(); // paquete tipo respuesta
Rx16Response rx16 = Rx16Response(); // direccion de 16 bits, se puede usar la de 64
TxStatusResponse txStatus = TxStatusResponse();
// Ethernet Shield uses pins 10,11,12,13
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x09, 0xF1 };
byte ip[] = { 192, 168, 112, 31 }; //casa { 192, 168, 1, 4}; laboratorio{ 192, 168, 112, 31 }; CeFoNT { 193, 144, 196, 6 };
byte gateway[] = { 192, 168, 112, 1 };
byte subnet[] = { 255, 255, 255, 0 };
Server server(80); // Puerto 80, HTTP
// SD
File myFile;
// VARIABLES GLOBALES
uint8_t fioList[fioMax] = {}; // {@1,@2,@3,...,@fioMax} Lista que contiene las direcciones de los remotos.
uint8_t fioNumber = 0; // numero de nodos remotos, inicialmente cero.
uint8_t uid[] = {0,0,0,0,0}; // contenedor de UID de la tarjetas
uint8_t initFrame[] = {REQUEST,1,INIT}; // Trama INIT
int bufferSize;
char buffer[bufferMax], bufferData[bufferMax]; // Buffer donde se guardan las tramas HTTP y el contenido de el POST.
unsigned long time1, time2;
int sleepCycleCoord = 0, asynchronusCoord = 0;
boolean flag1 = true, flag2 = false;
//////////////////////////// NTP SERVICE ////////////////////////////
unsigned int localPort = 8888; // local port to listen for UDP packets
byte timeServer[] = { 192, 43, 244, 18 }; // time.nist.gov NTP server
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
//////////////////////////// NTP SERVICE ////////////////////////////
void setup() {
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
xbee.begin(9600);
pinMode(8,OUTPUT);pinMode(7,OUTPUT);pinMode(6,OUTPUT);
pinMode(6, LOW);
pinMode(7, HIGH);
// Inicializacion de tarjeta
pinMode(ssPin,OUTPUT);
if (!SD.begin(chipSelect)) {
//mySerial.println("initialization failed!");
return;
}
//mySerial.print("\nCOORDINADOR\n");
// funcion que borra los ficheros antiguos Fxx.JS y de cambio de ciclo.
// BROADCAST INICIAL (puede repetirse para conocer el estado de la red)
sendRequest(initFrame, 3, millis()*0xFF);
pinMode(7, LOW);
}
void loop() {
readRequest(); // lee paquetes de entrada continuamente
listenForClient();
time2 = millis();
if (flag2 == true) { // si hay pendiente por hacer...
if (time1-time2 >= sleepCycleCoord)
sendPendingRequest();
time1 = millis(); // una vez alcanzado el tiempo de sueño se tiene que renovar
}
}
void readRequest() {
uint8_t fioAddress; // variables locales
if (xbee.readPacket(10)){
if (xbee.getResponse().isAvailable()) {
if (xbee.getResponse().getApiId() == RX_16_RESPONSE) { // se trata de un paquete RX
xbee.getResponse().getRx16Response(rx16); // almacena el paquete recibido en el objeto rx16
switch (rx16.getData(PACKET_TYPE)) {
case INFO: // TRAMA INFO
digitalWrite(8, HIGH);
fioAddress = rx16.getRemoteAddress16();
for ( int k = 0; k < 5; k++ ) {
uid[k] = rx16.getData(UID_FIELD + k);}
generateJson( fioAddress, rx16.getData(TEMPERATURE_FIELD), rx16.getData(HUMIDITY_FIELD), rx16.getData(SLEEPCYCLE_FIELD), rx16.getData(ASYNCHRONUS_FIELD), uid); // Renueva los datos de la fio en concreto
checkNewAddress(fioAddress);
digitalWrite(8, LOW);
break;
} // switch
} // getApiId
} // available
} // readPacket
} // readRequest
void checkNewAddress ( uint8_t address) { // fioNumber, fioList variables globales
for (int i = 0; i <= fioNumber; i++) {
if (fioNumber == 0) { // TODAVIA NO HAY ELEMENTOS UNIDOS AL COORDINADOR
fioList[i] = address;
fioNumber = 1;
i = fioNumber +1;
}
else{ // La lista no está vacía, chequea elemento a elemento
if ( fioList[i] == address) {
i = fioNumber +1;
}
else {
if (i == fioNumber) { // Luego de chequear toda la lista, si no coincide es un elemento nuevo
fioList[i] = address;
fioNumber++;
i = fioNumber +1;
}
} // end else2
} // end else1
} // end for
} // end checkNewAddress
boolean sendRequest(uint8_t data[], uint8_t length, uint8_t frameId) {
uint8_t ack, option = 0, i = 3;
Tx16Request tx = Tx16Request(0xFFFF, option, data, length, frameId);
do {
xbee.send(tx);
// Tx16Request (uint16_t addr16, uint8_t option, uint8_t *payload, uint8_t payloadLength, uint8_t frameId) (OBLIGATORIO PONERLOS TODOS!!)
// Tx16Request (uint16_t addr16, uint8_t *payload, uint8_t payloadLength) Creates a Unicast Tx16Request with the ACK option and DEFAULT_FRAME_ID.
if (xbee.readPacket(1000)) { // got a response!
if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) { // should be a znet tx status
xbee.getResponse().getZBTxStatusResponse(txStatus);
ack = txStatus.getStatus(); // get the delivery status, the fifth byte
} // STATUS: 0 = success, 1 = when all retries are expered and no ACK is received
}
i += 1;
}while( (i < 3) && (ack != SUCCESS) );
if (ack == SUCCESS)
return true;//mySerial.println("\nack");
else
return false;
}