Pages: [1]   Go Down
Author Topic: xbee + ethernet shield + arduino uno r2  (Read 1166 times)
0 Members and 1 Guest are viewing this topic.
Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi everyone,

I hope I don´t be wrong posting here. Well, I have a little doubt... I attached a xbee shield an ethernet shield over an arduino UNO. So when I try to just listenig through the XBee, when an http message comes from the net the arduino UNO resets.

I don't know if they are sharing ports, D0 and D1? Is there a conflict? As the serial use it, I added the newsoftserial library.

Maybe you know what are the tips that I should follow  when you use these two shield at the same time.

Thank you for your time and sorry for my English.
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
I attached a xbee shield
Which one?

Quote
an ethernet shield
Same question.

Quote
I don't know if they are sharing ports, D0 and D1?
We don't either.

Quote
Is there a conflict?
Maybe. Maybe not.

Quote
As the serial use it, I added the newsoftserial library.
Just including the library accomplishes nothing. You must actually use it. To do that, of course, you need to have some code. Where is it?

Quote
Maybe you know what are the tips that I should follow  when you use these two shield at the same time.
There are. They involve using the correct pins and writing the correct code. We can't see that you did either one correctly, yet.

Logged

Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi thank you for your fast answer.

The XBee Shield is http://www.arduino.cc/playground/shields/xbee01 It is almost the same mine is ArduinoXBee v1.1

The Ethernet Shield is "shield model Ethernet R3"

Over a Arduino UNO R2. I know that the Ethernet Shield R3 have more pins but my Ethernet Shield that fits perfectly on ARduino UNO R2.
But this shield don´t read the microSD.

I copy my code ... It could be a mess sorry. Thank you.

Logged

Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
#include <XBee.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>  // ocupa 5KB  
#include <NewSoftSerial.h>

#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

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();

NewSoftSerial mySerial(2, 3);

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x09, 0xF1 };
byte ip[]  = {192, 168, 112, 31 };
Server server(80);

// VARIABLES GLOBALES

uint8_t fioList[fioMax] = {};
uint8_t fioNumber = 0;
uint8_t uid[] = {0,0,0,0};
uint8_t initFrame[] = {REQUEST,1,INIT};

// Ethernet Shield uses pins 10,11,12,13.
#define bufferMax 128
int bufferSize;
char buffer[bufferMax], bufferData[bufferMax];;

// SD
File myFile;
#define ssPin       10
#define chipSelect   4

unsigned long time1, time2;
int sleepCycleCoord = 0, asynchronusCoord = 0;
boolean flag1 = true, flag2 = false;

void setup() {

  Ethernet.begin(mac, ip);
  server.begin();
  mySerial.begin(9600);
  pinMode(8,OUTPUT);    
  pinMode(ssPin,OUTPUT);
  if (!SD.begin(chipSelect)) {  
    mySerial.println("initialization failed!");
    return;
  }
  mySerial.print("\nCOORDINADOR\n");
  fioNumber = 0;
  sendRequest(0xFF, initFrame, 3, millis()*0xFF);
}

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 packetType, 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
        packetType = rx16.getData(PACKET_TYPE);            // TIPO TRAMA data[0]          
        switch (packetType) {                                
          case INFO:      // TRAMA INFO
            mySerial.print("\nreadRequest\n");
            digitalWrite(8, HIGH);      
            fioAddress = rx16.getRemoteAddress16();
            for ( int k = 0; k < 4; 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

Logged

Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
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 address, uint8_t data[], uint8_t length, uint8_t frameId) {
 
  uint16_t fio_address = 0x0000;
  uint8_t ack, option = 0, i = 0, timeWait;

  if (address == 0xFF) {
    fio_address = 0xFFFF;
    i=3;
    timeWait = 100;
  }
  else {
    fio_address = 0x0000 + address;
    timeWait = 1000;
  }
 
  Tx16Request tx = Tx16Request(fio_address, 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(timeWait)) {  // got a response!
      if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {  // should be a znet tx status
        xbee.getResponse().getZBTxStatusResponse(txStatus);
        // get the delivery status, the fifth byte
        ack = txStatus.getStatus();
      }  // STATUS:  0 = success, 1 = when all retries are expered and no ACK is received
    } 
    i += 1;
  }while( (i < 3) && (ack != SUCCESS) );

  if (ack == SUCCESS) {
    mySerial.println("\nack");
    return true;
  }
  else {
    return false;
  }
}

void listenForClient() {
  Client client = server.available(); // espera a que haya datos disponilbles
  if ( client )
    waitForRequest(client); 
}

void waitForRequest(Client client) {
  boolean currentLineIsBlank = true, flag = true;
  char c;
  bufferSize = 0;
  while (client.connected()) {
    while (client.available()) {     
      c = client.read(); //mySerial.print(c);
      if (c == '\n' && currentLineIsBlank) {
        // Here is where the POST data is. 
        while(client.available()) { // sino hay datos, no entra solo si hay datos
          c = client.read();
          bufferData[bufferSize++] = c;
        }
        bufferData[bufferSize] = 0;
        //Serial.print("\nDatos del Post: ");
        //Serial.print(bufferData);
        flag = true;
        parseReceivedRequest(client);
      }
      else if (c == '\n') { // NEW LINE
        if (flag) {
          //Serial.print('\n');
          buffer[bufferSize] = 0;  // no me pinta salto de linea si bufferSize+1
          //Serial.print(buffer);
          bufferSize = 0;
          flag = false;
        }
        currentLineIsBlank = true;
      }
      else if (c != '\r') { // you've gotten a character on the current line
        currentLineIsBlank = false;
        if ( bufferSize < bufferMax && flag )
          buffer[bufferSize++] = c;
      }
    } // client.available
  } // client.connected
} // end void

void parseReceivedRequest(Client client) { // Petición recibida del tipo: "GET /192.168.112.31/fio HTTP/1.1"
  mySerial.println(buffer);
  if ( strstr(buffer, "GET / HTTP/1.1") ) {  //  Serial.print("pinta la web");
    webPrint(client);
  }
  else if ( strstr(buffer, "GET /fioList HTTP/1.1") ) { //  Serial.println("respuesta fioList");
         sendGetResponse(client);     
  }
  else if ( strstr(buffer, "POST /changes HTTP/1.1") ) {  //  Serial.println("respuesta a un POST");
         client.println("HTTP/1.1 200 OK");
         client.println(); 
         //sendPostResponse(client);
         createRequest(bufferData);
  }

  client.flush();
  client.stop();
}

/*void sendPostResponse ( Client client) {
    client.println("HTTP/1.1 200 OK");
    client.println(); 
}*/

void sendGetResponse(Client client) {
  char filename[9];
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: application/json");
  client.println("Connection: close");
  client.println();
  client.print("{\"fioList\":[");
  client.print("{\"asynchronus\":\"");
  client.print(asynchronusCoord);
  client.print("\",\"sleepCycle\":\"");
  client.print(sleepCycleCoord);
  client.print("\"},");
  for (int k = 0; k < fioNumber; k++) {
    sprintf (filename, "F%d.JS", fioList[k]); // si Fx.js guardado en la microSd como Fx.JS
    filePrint(filename, client);
    if ( (k+1) != fioNumber)
      client.println(",");
  }
  client.println("]}");
}

void webPrint (Client client) { 
  filePrint("SRV_2.txt", client);
}
// fuente: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1295739118
void filePrint (char filename[9], Client client){
  if (myFile = SD.open(filename, FILE_READ)) { 
    while ( myFile.available() ) {
      client.print( (char) myFile.read() );
    }
    myFile.close();                 // CERRAR FICHERO
  }
  else{
    mySerial.print("no leido");
  }
}
 
  // OFF modo pregunta ( SIEMPRE DESPIERTO )
  // PERIODO modo envio de informacion periodica ( CON CICLOS DE SUEÑO )
  // ASINCRONO modo solo envio de info si es que hay cambios ( SIEMPRE DESPIERTO )
  // ASINCRONO + PERIODO modo envio de info si hay cambio ( CON CICLO DE SUEÑO )

void generateJson (uint8_t address, uint8_t temperature, uint8_t humidity, uint8_t sleepCycle, uint8_t asynchronus, uint8_t uid[]) {
  char filename[9];
  sprintf (filename, "F%d.JS", address);
  // String jsonString; Usando string no lo escribe correctamente
  if ( SD.exists(filename) ) {
    SD.remove(filename);
  }
  myFile = SD.open(filename, FILE_WRITE); // CREACION FICHERO
  if (myFile) {  // si esta abierto ...
   myFile.print("{\"name\":\"fio");
   myFile.print( address, DEC);
   myFile.print("\",\"address\":\"");
   myFile.print(address, DEC);
   myFile.print("\",\"temperature\":\"");
   myFile.print(temperature, DEC);
   myFile.print("\",\"humidity\":\"");
   myFile.print(humidity, DEC);
   myFile.print("\",\"asynchronus\":\"");
   myFile.print(asynchronus, DEC);
   myFile.print("\",\"sleepCycle\":\"");
   myFile.print(sleepCycle, DEC);
   myFile.print("\",\"uid\":\"");
   for ( int k = 0; k < 4; k++ ) {
     myFile.print(uid[k], HEX);
   }
   myFile.print("\"}");
   myFile.close();// CERRAR FICHERO 
  }   
}

void createRequest(char buffer[]) {
  uint8_t frameId = millis()*0x00FF;
  char *asyn, *slpC, *equal;
  char sleepCycle[3], asynchronus[2];
  sleepCycle[0] = 0;
  asynchronus[0] = 0;
  equal = strstr(buffer, "=") + 1;
  slpC = strstr(equal, "&");
  strncat(sleepCycle, equal, slpC-equal);
  equal = strstr(slpC, "=") + 1;
  asyn = strstr(equal, "&");
  strncat(asynchronus, equal, asyn-equal);
  //sleepCycle=20&asynchronus=0
  int asynchronus2 = atoi(asynchronus);
  int sleepCycle2  = atoi(sleepCycle);
 
  uint8_t data[] = {CONFIGURATION,2,sleepCycle2, asynchronus2};  // Configuration request: [0,2,SLEEP_CYCLE,ASYNCHRONUS]
  uint8_t length = sizeof(data);
  /*
  if ( sendRequest( 0xFF, data, length, frameId) == false ) {
    Serial.print("envio fallido");
    saveRequest(0xFF, data, length, frameId);
    flag2 = true; // al no ser enviada se levanta la bandera de pendientes
  }
  else {  // se consiguió enviar
    sleepCycleCoord = sleepCycle2;
    asynchronusCoord = asynchronus2;
    if (flag1 == true){ // solo vale true la primera vez que se envía el cambio de ciclo.
      flag1 == false;
      time1 = millis(); // time 1 toma su primer valor
    }
  }*/
}


void saveRequest(uint8_t address, uint8_t data[], uint8_t length, uint8_t frameId) {
  char filename[9];
  int k = 0;
  sprintf (filename, "%d.txt", 1);
  eraseRequest(filename);
  myFile = SD.open(filename, FILE_WRITE); 
  if (myFile) {  // si esta abierto ...
    myFile.print(address, HEX); myFile.print('\n');
    myFile.print(frameId, HEX); myFile.print('\n');
    while (k < length) { 
      myFile.print(data[k], HEX); myFile.print('\n');
      k++;
    }
    myFile.close(); 
  }     
}

void sendPendingRequest() { 
  uint8_t frameId, address, k = 0, data[] = {};
  char filename[6];
  sprintf (filename, "%d.txt", "1");
  if ( SD.exists(filename) ) {
    myFile = SD.open(filename); 
    if (myFile) {  // si esta abierto ...
      address = myFile.read();
      frameId = myFile.read();
      while ( myFile.available() ){
        data[k] = myFile.read();
        k++;
      }
      myFile.close();  // CERRAR FICHERO
      if ( sendRequest( address, data, sizeof(data), frameId ) == true ){
        flag2 = false;  // baja la bandera de pendientes
        eraseRequest(filename);
      }
    }  // myFile
  } // SD.exists(filename)
}

void eraseRequest(char filename[9]) {
  SD.remove(filename);
}
Logged

Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It´s hard to explain to me in English ... but I could try.

This code belongs to a coordinator in a 802.15.4 network. It recolects the information of its remote nodes.

This information as you can see it treated by two functions, first it listens (readRequest) if there is a frame it save the information in the microSD as a file (generateJson).

Besides, It listens to incoming request from the internet, there are only 3 GET /HTTP1.1. GET /fioList HTTP1.1 and POST /changes. So as you can see there are functions that answer to them.

The microSD have as files as remote nodes are, and the html code of the webpage in html. So when you receive a GET /HTTP1.1 The board print to the client the page that reads from the microSD card.

The same  when a GET /fioList arrives ....

and when a POST message arrives the coordinator just pick up the two variables and send to nodes or save it for doing later.

Please ask me everything you don´t get. I know ... this is too much ... sorry and thank you.
Logged

Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi again,

I have an Arduino Ethernet, working with Arduino IDE v1.0.1, Xbee library (   XBee Arduino Library Version 0.3 - Supports Arduino 1.0) The code is practically the same, but I´m going to paste. Well, I tried the program only with the ethernet and it works. The web page is printed and the get and post request from the internet are answered. The problem appeared when I introduced this:

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();

so even if I don´t inilialize the module it doesn´t work. What I mean is including xbee.begin(9600), including or not the problem appears.

What is it the problem? With Serial.begin if I tried to know what´s happened on the monitor you could see this:

GEGET / HTTP/1.1

strange symbols GET / HTTP/1.1
strange symbols GET / HTTP/1.1
strange symbols GET / HTTP/1.1
strange symbols GET / HTTP/1.1
.... forever and ever

And in the browser instead of print the web page sometimes appears this over all the window:
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

and sometimes do nothing like if the page starts to load but at the end nothing happens. In the meantime on the monitor you can see like a GET frame came again and again in a infinite cycle as I showed you.

TEST 2. If I don´t use the serial to print on the monitor ....then I can´t check anything on the monitor and the web page is loading, nothing is charge ... I used CHROME so If I push F12 it allow to see the http frames, the code of the page... and I see that a GET is sent but ... it remains as pending and the code is never charged.

so is there conflicts between the libraries? Have I that respects some ports, change its maybe? Have I to enable the pin 10 as HIGH always I need to read from the SD? Maybe I forgetting basic tips or maybe just looking at the code you realize whats my problem.

thank you!
Logged

Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
#include <XBee.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>  // ocupa 5KB 

#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


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();


byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x09, 0xF1 };
IPAddress ip(193,144,196,6);//casa {192,168,1,4}; laboratorio{ 192, 168, 112, 31 }; CeFoNT {193,144,196,6} //
EthernetServer server(80); // Puerto 80, HTTP

// VARIABLES GLOBALES

uint8_t fioList[fioMax] = {}, fioNumber = 0, uid[] = {0,0,0,0}, initFrame[] = {REQUEST,1,INIT};

// Ethernet Shield uses pins 10,11,12,13.
#define bufferMax 128
int bufferSize;
char buffer[bufferMax], bufferData[bufferMax];;

// SD
File myFile;
#define ssPin       10
#define chipSelect   4

unsigned long time1, time2;
int sleepCycleCoord = 0, asynchronusCoord = 0;
boolean flag1 = true, flag2 = false;

void setup() {
  pinMode(8,OUTPUT);     // led avisa de llegada de tramas
  pinMode(7,OUTPUT);
  digitalWrite(7, HIGH);
 
  pinMode(ssPin,OUTPUT);  // desactivar w5100 mientras setea la uSD
  digitalWrite(ssPin, HIGH);
  if (!SD.begin(chipSelect)) {  // inicia la tarjeta SD
    //Serial.println("initialization failed!");
    return;
  }
  Ethernet.begin(mac, ip);
  digitalWrite(ssPin, HIGH);
  delay(2000);
  server.begin();
  delay(1000);
  xbee.begin(9600);
  delay(1000);
  //Serial.begin(9600);
  //delay(500);
  //Serial.print("\nCOORDINADOR\n");
  //fioNumber = 0;
  // funcion que borra los ficheros antiguos Fxx.JS y de cambio de ciclo.
  //sendRequest( initFrame, 3, millis()*0xFF ); // BROADCAST INICIAL (puede repetirse para conocer el estado de la red)
  digitalWrite(7,LOW);
}
Logged

Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
void loop() {
  listenForClient();
  }*/
}
void listenForClient() {
  EthernetClient client = server.available(); // espera a que haya datos disponilbles
  boolean currentLineIsBlank = true, flag = true;
  bufferSize = 0;
  if ( client ) {
    while (client.connected()) {
      while (client.available()) {     
        char c = client.read(); // Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
          while(client.available()) { // Datos si es un POST
            c = client.read();
            bufferData[bufferSize++] = c;
          }
          bufferData[bufferSize] = 0;  //Serial.println(bufferData);
          client.println("HTTP/1.1 200 OK");
          client.println(); 
          createRequest(bufferData);
          client.flush();
          client.stop();
        }
        else if (c == '\n') { // NEW LINE
          if (flag) {
            flag = false;
            currentLineIsBlank = true;
            buffer[bufferSize] = 0;  // no me pinta salto de linea si bufferSize+1
            bufferSize = 0; // Serial.println(buffer);
            if ( strstr(buffer, "GET / HTTP/1.1") ) {
              filePrint("SRV.txt", client);
              client.flush();
              client.stop();
            }
            else
              if ( strstr(buffer, "GET /fioList HTTP/1.1") ){
                sendGetResponse(client);     
                client.flush();
                client.stop();
              }
              else
                if ( !strstr(buffer, "POST /changes HTTP/1.1") ) {
                  client.flush();
                  client.stop();
                }
          }
        }
        else if (c != '\r') { // caracter de la misma linea
          currentLineIsBlank = false;
          if ( (bufferSize < bufferMax) && flag )
            buffer[bufferSize++] = c;
        }
      }  // client.available
    }  // client.connected
  }  // end if
}  // endListenForClient
 
// Petición recibida del tipo: "GET /192.168.112.31/fio HTTP/1.1"

void sendGetResponse(EthernetClient client) {
  client.println("HTTP/1.1 200 OK\nContent-Type: application/json\nConnection: close");
  client.println();
  client.print("{\"fioList\":[\"asynchronus\":\"");
  client.print(asynchronusCoord);
  client.print("\",\"sleepCycle\":\"");
  client.print(sleepCycleCoord);
  client.print("\"},");
  for (int k = 0; k < fioNumber; k++) {
    char filename[9];
    sprintf (filename, "F%d.JS", fioList[k]); // si Fx.js guardado en la microSd como Fx.JS
    filePrint(filename, client);
    if ( (k+1) != fioNumber)
      client.println(",");
  }
  client.println("]}");
}

// fuente: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1295739118

void filePrint (char filename[10], EthernetClient client){
  if ((myFile = SD.open(filename, FILE_READ))) { 
    while ( myFile.available() )
      client.print( (char) myFile.read() );
    myFile.close();  // CERRAR FICHERO
  }
}

void generateJson (uint8_t address, uint8_t temperature, uint8_t humidity, uint8_t sleepCycle, uint8_t asynchronus, uint8_t uid[]) {
  char filename[9];
  sprintf (filename, "F%d.JS", address);  // String jsonString; Usando string no lo escribe correctamente
  if ( SD.exists(filename) )  // Si ya existía lo borra
    SD.remove(filename);
  // CREACION FICHERO
  if ((myFile = SD.open(filename, FILE_WRITE))) {  // si esta abierto ...
   myFile.print("{\"name\":\"fio");
   myFile.print( address, DEC);
   myFile.print("\",\"address\":\"");
   myFile.print(address, DEC);
   myFile.print("\",\"temperature\":\"");
   myFile.print(temperature, DEC);
   myFile.print("\",\"humidity\":\"");
   myFile.print(humidity, DEC);
   myFile.print("\",\"asynchronus\":\"");
   myFile.print(asynchronus, DEC);
   myFile.print("\",\"sleepCycle\":\"");
   myFile.print(sleepCycle, DEC);
   myFile.print("\",\"uid\":\"");
   for ( int k = 0; k < 4; k++ )
     myFile.print(uid[k], HEX);
   myFile.print("\"}");
   myFile.close();  // CERRAR FICHERO 
  }   
}

void createRequest(char buffer[]) {
  uint8_t frameId = millis()*0x00FF;
  char *param, *equal, sleepCycle[3], asynchronus[2];
  sleepCycle[0] = 0;
  asynchronus[0] = 0;
  //sleepCycle=20&asynchronus=0
  equal = strstr(buffer, "=") + 1;
  param = strstr(equal, "&");
  strncat(sleepCycle, equal, param-equal);  //sleepCycle
  equal = strstr(param, "=") + 1;
  strncat(asynchronus, equal, 1);  //asynchronus
  //Serial.print(atoi(sleepCycle));  Serial.print(atoi(asynchronus));
  uint8_t data[] = {CONFIGURATION, 2, atoi(sleepCycle), atoi(asynchronus)};  // Configuration request: [0,2,SLEEP_CYCLE,ASYNCHRONUS]
  uint8_t length = sizeof(data);
/*
  if ( sendRequest( data, length, frameId) == false ) {
    saveRequest(data, length, frameId);
    flag2 = true; // al no ser enviada se levanta la bandera de pendientes
  }
  else {  // se consiguió enviar
    sleepCycleCoord = atoi(sleepCycle);
    asynchronusCoord = atoi(asynchronus);
    if (flag1 == true){ // solo vale true la primera vez que se envía el cambio de ciclo.
      flag1 == false;
      time1 = millis(); // time 1 toma su primer valor
    }
  }*/
}

void saveRequest(uint8_t data[], uint8_t length, uint8_t frameId) {
  uint8_t k = 0;
  char filename[9];
  sprintf (filename, "%d.txt", 1);
  SD.remove(filename);  // borrar la anterior
  // CREACION FICHERO
  if ((myFile = SD.open(filename, FILE_WRITE))) {  // si esta abierto ...
    myFile.print(frameId, HEX);
    while (k < length) { 
      myFile.println(data[k], HEX);
      k++;
    }
    myFile.close();  // CERRAR FICHERO
  }     
}

void sendPendingRequest() { 
  uint8_t frameId, address, k = 0, data[] = {};
  char filename[9];
  sprintf (filename, "%d.txt", 1);
 
  if ( SD.exists(filename) ) {
    if ((myFile = SD.open(filename))) {  // ABRIR FICHERO
      frameId = myFile.read();
      while ( myFile.available() ){
        data[k] = myFile.read();
        k++;
      }
      myFile.close();  // CERRAR FICHERO
 /*    if ( sendRequest( data, sizeof(data), frameId ) == true ){
        flag2 = false;  // baja la bandera de pendientes
        SD.remove(filename);
      }*/
    }  // myFile
  }  // SD.exists(filename)
}  // sendPendingRequest

Logged

Santander
Offline Offline
Newbie
*
Karma: 0
Posts: 47
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,

sorry I forget it, I´ve also an arduino uno R3 and its respectevely ethenet shield. So I can tested on both on the ethernet arduino and the arduino uno R3
Logged

Miramar Beach, Florida
Offline Offline
Faraday Member
**
Karma: 138
Posts: 5835
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm not and XBee user, but it appears that shield uses the hardware serial port. Here is the test code from this page.
http://www.cooking-hacks.com/index.php/documentation/tutorials/arduino-xbee-shield
Code:
  void setup()
   {
   Serial.begin(9600);
   }

   void loop()
   {
   Serial.print('H');
   delay(1000);
   Serial.print('L');
   delay(1000);
   }
You should be able to monitor this with your serial monitor. However, I would presume from this that you will not be able to use the hardware serial port for anything else, including debugging messages from the ethernet...edit: unless you want to send the ethernet debugging output to the other XBee.
« Last Edit: October 30, 2012, 01:56:58 pm by SurferTim » Logged

Pages: [1]   Go Up
Jump to: