Go Down

Topic: Arduino + official ethernet shield + SD -> all working together. (Read 14 times) previous topic - next topic

aboshan

#20
Mar 13, 2011, 09:45 pm Last Edit: Mar 13, 2011, 09:47 pm by aboshan Reason: 1
Gixxer,

I am glad to tell you that I tested your code and it works.
However, I had to modify the initialization of the SD card:
Code: [Select]
//------------ start of setup SD -------------------------------
 // initialize the SD card
 Serial.println("Setting up SD card...");     //To use the SD card, you set its SS pin HIGH and the Ethernet shield's SS pin LOW
   digitalWrite(ETHERNETchipSelectPin, HIGH); // turn off the W5100 chip!
digitalWrite(SDchipSelectPin, LOW); // turn on the SD chip!

 Serial.print("Initializing SD card...");
 // see if the card is present and can be initialized:
 if (!SD.begin(SDchipSelectPin)) {
   Serial.println("Card failed, or not present");
   // don't do anything more:
   //return;
   SDavailable =  false;  // set a flag to indicate that the SD is not available so that the code in the loop knows.
 }
//<<<<<<<<<<<<<<<<<<<<<<<<<MODIFIED PART >>>>>>>>>>>>>>>>>>>>>>>>>>>>//
 else{
 Serial.println("card initialized.");
 SDavailable = true;
 }
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>//
//------------ end of setup SD -------------------------------


You need to initialize SDavailable for it to be true.

Here's my full code (needs some cleanup), it basicly generates a random int between 0 and 50, sends it to a php script on my server and also to "testfile.txt" on the SD card.

the loop executes every 10 seconds, because I have a database that has a 10 second refresh rate. Feel free to remove the prevtime/newtime part if you don't want refresh control.

Code: [Select]
// Simple example to show how the Ethernet WebClient example would
// change to use the DHCP and DNS libraries

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <Dhcp.h>
#include <dns.h>

float prevTime=0;
float newTime=0;

/*
The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4
* Ethernet chip attached to SPI bus as follows:
** SS - pin 10 (by default)
*/
// to deselect a peripherial (SD or ethernet) put HIGH to its CS pin.

char* kHostname = "192.168.1.3";
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[4]; // = { 10, 0, 0, 177 };
byte server[4]; // = { 64, 233, 187, 99 }; // Google

Client client(server, 80);

boolean SDavailable;

// On the Ethernet Shield, CS is pin 4. Note that even if it's not
// used as the CS pin, the hardware CS pin (10 on most Arduino boards,
// 53 on the Mega) must be left as an output or the SD library
// functions will not work.
const int SDchipSelectPin = 4;
const int ETHERNETchipSelectPin = 10;


void setup()
{
 Serial.begin(9600);
 //pin i/o
 //pinMode(2,INPUT);
 //pinMode(13,OUTPUT);
 
 //pull-ups
 //digitalWrite(2,HIGH);
 
 //interrupts
 //attachInterrupt(1,ctr,CHANGE);
 
 pinMode(ETHERNETchipSelectPin, OUTPUT);    // pin 10 -> make sure that the default chip select pin is set to output, even if you don't use it:  pinMode(10, OUTPUT); // set the SS pin as an output (necessary!)
 pinMode(SDchipSelectPin, OUTPUT);      //    pin 4 -> On the Ethernet Shield, CS is pin 4  pinMode(4, OUTPUT); // set the SS pin as an output (necessary!)
 digitalWrite(ETHERNETchipSelectPin, LOW); // turn on the W5100 chip! by default it will be ON, so unnecessary.
 digitalWrite(SDchipSelectPin, HIGH); // but turn off the SD card functionality!
 
 // Get an IP address to use and also find out our DNS server address
 while (Dhcp.beginWithDHCP(mac) != 1)
 {
   Serial.println("Error getting IP address via DHCP, trying again...");
   delay(15000);
 }    
 delay(1000);
 byte buffer[6];
 Dhcp.getLocalIp(buffer);
 Serial.print("ip address: ");
 printArray(&Serial, ".", buffer, 4, 10);
 Serial.println("connecting...");
 
 DNSClient dns;
 // Use "server" to hold the DNS server address while we initialise
 // the DNS code
 Dhcp.getDnsServerIp(server);
 dns.begin(server);

 // Resolve the hostname to an IP address
 // Re-use "server" to hold the address for the resolved hostname
 int err = dns.gethostbyname(kHostname, server);
 if (err == 1)
 {
   Serial.print(kHostname);
   Serial.print(" resolved to ");
   Serial.print((int)server[0]);
   Serial.print(".");
   Serial.print((int)server[1]);
   Serial.print(".");
   Serial.print((int)server[2]);
   Serial.print(".");
   Serial.println((int)server[3]);
 }
 else
 {
   Serial.println("DNS lookup failed");
 }
//------------ start of setup SD -------------------------------
 // initialize the SD card
 Serial.println("Setting up SD card...");     //To use the SD card, you set its SS pin HIGH and the Ethernet shield's SS pin LOW
   digitalWrite(ETHERNETchipSelectPin, HIGH); // turn off the W5100 chip!
digitalWrite(SDchipSelectPin, LOW); // turn on the SD chip!

 Serial.print("Initializing SD card...");
 // see if the card is present and can be initialized:
 if (!SD.begin(SDchipSelectPin)) {
   Serial.println("Card failed, or not present");
   // don't do anything more:
   //return;
   SDavailable =  false;  // set a flag to indicate that the SD is not available so that the code in the loop knows.
 }
 else{
 Serial.println("card initialized.");
 SDavailable = true;
 }
//------------ end of setup SD -------------------------------

}

void printArray(Print *output, char* delimeter, byte* data, int len, int base)
{
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for(int i = 0; i < len; i++)
{
if(i != 0)
output->print(delimeter);
output->print(itoa(data[i], buf, base));
}
output->println();
}

void loop()
{
 newTime=millis();
 
 // execute code every 10sec, as rrd refresh is also 10sec
 if(newTime>=prevTime+10000)
 {
   prevTime=newTime;
   
   int randomNr = random(0,50);
   
   sendtoSD(randomNr);
   sendtoethernet(randomNr);

 }
}

void sendtoethernet(int randomNr)
{
// ----------------------------Send the data via ethernet ----------------------------
   //set its SS pin (10) HIGH, and the SD card's SS (4) pin LOW
   digitalWrite(ETHERNETchipSelectPin, LOW);       // select ethernet mode -> LOW selects, HIGH deselects module
   digitalWrite(SDchipSelectPin, HIGH);       // deselect SD mode -> LOW selects, HIGH deselects module

   
   String a = "GET /rrdcounter/counterUpdate.php?value=";
   String b = " HTTP/1.0";
   String url = a + randomNr + b;
   
   if (client.connect())
   {
     Serial.println("connected");
     client.println(url);
     client.println();
     Serial.print("submitted value: ");
     Serial.println(randomNr);
   }
   else
   {
     Serial.println("connection failed");
   }
   
   while(client.available()) {
   char c = client.read();
   Serial.print(c);
   }
   
   Serial.println();
   Serial.println("disconnecting...");
   client.stop();
}
 
void sendtoSD(int randomNr)
{
// ----------------------------Save the data in the SD -------------------------------------------
 if (SDavailable != false)
 {
//To use the SD card, you set its SS pin HIGH and the Ethernet shield's SS pin LOW
 digitalWrite(ETHERNETchipSelectPin, HIGH);       // deselect ethernet mode-> LOW selects, HIGH deselects module
 digitalWrite(SDchipSelectPin, LOW);           // select SD mode-> LOW selects, HIGH deselects module

// open the file. note that only one file can be open at a time, so you have to close this one before opening another.
 File dataFile = SD.open("testfile.txt", FILE_WRITE);
// if the file is available, write to it:
 if (dataFile) {
   dataFile.print(randomNr);
   dataFile.print(",");
   dataFile.close();
   // print to the serial port too:
   Serial.print("Value written to SD: ");
   Serial.println(randomNr);
 }  
 // if the file isn't open, pop up an error:
 else {
   Serial.println("error opening testfile.txt");
 }

 }
// ---------------- end of saving data to SD -----------------------------
}



Nice job, seriously!

Sergegsx

you have made my day !!!
thanks for testing it! im so happy it worked. I really was not sure as all was written whilst learning the theory with no chance to test it. its so frustrating not being able to test it at the moment.

So I guess my objective was accomplished, to create a dead easy code to use both ethernet and SD with just one line of code

Code: [Select]

sendtoethernet(dataString);

sendtoSD(dataString);


Im sure it will be useful for other people.
* Si preguntas, pon el código de tu programa, hace mucho mas fácil ayudarte. Y me ahorro un mensaje pidiendo que lo hagas.
* Si consigues solucionar tu problema, dedica unos minutos a explicar en tu post como lo conseguiste para beneficio de todos.
* Cambia el 'Subject' de tu hilo y añade 'SOLUCIONADO' cuando hayas llegado a una solución al problema que planteaste.
* Utiliza un 'Subject' para tu hilo que explique de que va el hilo.
Si estas empezando:
* Comienza a usar Arduino
* Guías de iniciación a Arduino
* Ejemplos
* Referencia del Lenguaje
* Conceptos básicos
Guia de usuario de arduino
Tutoriales en Ingles
Si necesitas que alguien te escriba el código: http://www.freelancer.com/  o esta  http://www.guru.com/

Sergegsx

#22
Mar 13, 2011, 10:55 pm Last Edit: Mar 13, 2011, 11:04 pm by Gixxer Reason: 1
latest version with aboshan comments implemented. thanks !

once i have the chance to test it i will clean it up.

Code: [Select]

/*
  Official Ethernet shield + SD working together.

This sketch connects to the internet and sends a value to a php file for it
to process it to its convenience (ie: store it in mysql database), it also
saves the value to de SD card using the Arduino Wiznet Ethernet shield.

Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13

The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4
* Ethernet chip attached to SPI bus as follows:
** SS - pin 10 (by default)
// to deselect a peripherial (SD or ethernet) put HIGH to its CS pin.

created 13 Mar 2011
by S. Escuder

*/

//Libraries
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>

//Server IP address
byte server[] = { 173,194,33,104 }; // Google
//Setup a client
Client client(server, 80);
byte ip[] = { 192,168,1,69 };  // Using a Router
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte gateway[] = { 192, 168, 1, 1 };   //your router's IP address

boolean SDavailable;

// On the Ethernet Shield, CS is pin 4. Note that even if it's not
// used as the CS pin, the hardware CS pin (10 on most Arduino boards,
// 53 on the Mega) must be left as an output or the SD library
// functions will not work.
const int SDchipSelectPin = 4;
const int ETHERNETchipSelectPin = 10;

void setup()
{
// ---- start setup SERIAL PORT --------------------------------------------------
Serial.begin(9600);
Serial.println(" ********************** Arduino Started ********************** ");
// ---- end setup SERIAL PORT --------------------------------------------------


// ------------ Set pin modes ... ----------------------------------------------
  pinMode(ETHERNETchipSelectPin, OUTPUT);    // pin 10 -> make sure that the default chip select pin is set to output, even if you don't use it:  pinMode(10, OUTPUT); // set the SS pin as an output (necessary!)
  pinMode(SDchipSelectPin, OUTPUT);      //    pin 4 -> On the Ethernet Shield, CS is pin 4  pinMode(4, OUTPUT); // set the SS pin as an output (necessary!)
  // both units are turned off here.
  //digitalWrite(10, HIGH); // but turn off the W5100 chip!
  //digitalWrite(4, HIGH); // but turn off the SD card functionality!
// ------------ End Set pin modes ... -------------------------------------------

 
// --------  Start ethernet --------------------------------
  digitalWrite(ETHERNETchipSelectPin, LOW); // turn on the W5100 chip! by default it will be ON, so unnecessary.
  digitalWrite(SDchipSelectPin, HIGH); // but turn off the SD card functionality!
  Ethernet.begin(mac, ip, gateway);     //, subnet);
// ----------- end setup ethernet --------------------------


//------------ start of setup SD -------------------------------
  // initialize the SD card
  Serial.println("Setting up SD card...");    //To use the SD card, you set its SS pin HIGH and the Ethernet shield's SS pin LOW
    digitalWrite(ETHERNETchipSelectPin, HIGH); // turn off the W5100 chip!
digitalWrite(SDchipSelectPin, LOW); // turn on the SD chip!

  Serial.print("Initializing SD card...");
  // see if the card is present and can be initialized:
  if (!SD.begin(SDchipSelectPin)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    //return;
    SDavailable =  false;  // set a flag to indicate that the SD is not available so that the code in the loop knows.
  }
  else{
  Serial.println("Card initialized.");
  SDavailable = true;
  }

//------------ end of setup SD -------------------------------
}




void loop() {
// ++++++++++++++++++ GET SOME DATA ++++++++++++++++++++++++++
// make a string for assembling the data to log:
  String dataString = "";

  // read three sensors and append to the string:
  for (int analogPin = 0; analogPin < 3; analogPin++) {
    int sensor = analogRead(analogPin);
    dataString += String(sensor);
    if (analogPin < 2) {
      dataString += ",";
    }
  }
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

sendtoethernet(dataString);

sendtoSD(dataString);

delay(10000);

}


void sendtoethernet(String dataString){
  // ----------------------------Send the data via ethernet ----------------------------
//set its SS pin (10) HIGH, and the SD card's SS (4) pin LOW
digitalWrite(ETHERNETchipSelectPin, LOW);       // select ethernet mode -> LOW selects, HIGH deselects module
digitalWrite(SDchipSelectPin, HIGH);       // deselect SD mode -> LOW selects, HIGH deselects module

  if (client.connect()) {   
    client.print("GET http://website.com/upload.php?P=");
    client.print(dataString);
    client.println();
    client.stop();
  }
else {
    Serial.println(" ***************** Failed to connect to client ***************** ");
  }
}


void sendtoSD(String dataString){
// ----------------------------Save the data in the SD -------------------------------------------
if (SDavailable != false){
//To use the SD card, you set its SS pin HIGH and the Ethernet shield's SS pin LOW
digitalWrite(ETHERNETchipSelectPin, HIGH);       // deselect ethernet mode-> LOW selects, HIGH deselects module
digitalWrite(SDchipSelectPin, LOW);           // select SD mode-> LOW selects, HIGH deselects module

// open the file. note that only one file can be open at a time, so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.print("Value written to SD: ");
    Serial.println(dataString);
  } 
  // if the file isn't open, pop up an error:

  else {
    Serial.println("error opening datalog.txt");
  }

}
// ---------------- end of saving data to SD -----------------------------
}



// to be implemented later
/*
void switch2microSD() {
  //
  digitalWrite(10,HIGH);
  digitalWrite(4,LOW);
  delay(5);
}

void switch2eth() {
  //
  digitalWrite(10,LOW);
  digitalWrite(4,HIGH);
  delay(5);

}
*/
* Si preguntas, pon el código de tu programa, hace mucho mas fácil ayudarte. Y me ahorro un mensaje pidiendo que lo hagas.
* Si consigues solucionar tu problema, dedica unos minutos a explicar en tu post como lo conseguiste para beneficio de todos.
* Cambia el 'Subject' de tu hilo y añade 'SOLUCIONADO' cuando hayas llegado a una solución al problema que planteaste.
* Utiliza un 'Subject' para tu hilo que explique de que va el hilo.
Si estas empezando:
* Comienza a usar Arduino
* Guías de iniciación a Arduino
* Ejemplos
* Referencia del Lenguaje
* Conceptos básicos
Guia de usuario de arduino
Tutoriales en Ingles
Si necesitas que alguien te escriba el código: http://www.freelancer.com/  o esta  http://www.guru.com/

colbec

Here is my serial output from Gixxer latest version.

Code: [Select]

********************** Arduino Started **********************

Setting up SD card...

Initializing SD card...Card initialized.

***************** Failed to connect to client *****************

error opening datalog.txt

***************** Failed to connect to client *****************

error opening datalog.txt



Since aboshan has no problem this could be just my setup. SD files seem to be ok for my approach (see earlier in thread) so I'm not sure what is different. Using new UNO and Arduino0022. Only changes to code are to use fixed IP suitable for my subdomain, remove references to gateway since this will be correctly deduced by the system, and change MAC addr.

Since it is only a few days until Gixxer has his hardware in hand will wait and see what transpires at that time.

Sergegsx

COLBEC I have the same problem

Code: [Select]

Initializing SD card...card initialized.
error opening datalog.txt
679,878,42
684,886,43
683,887,42
685,888,42


aboshan can you tell me the exact SD card you are using? i have tried with a nokia SD card that comes with mobile phones.
also, how is your card formatted?

I think its an SD card problem cause the example that comes with arduino 22 gives me the same problem.
* Si preguntas, pon el código de tu programa, hace mucho mas fácil ayudarte. Y me ahorro un mensaje pidiendo que lo hagas.
* Si consigues solucionar tu problema, dedica unos minutos a explicar en tu post como lo conseguiste para beneficio de todos.
* Cambia el 'Subject' de tu hilo y añade 'SOLUCIONADO' cuando hayas llegado a una solución al problema que planteaste.
* Utiliza un 'Subject' para tu hilo que explique de que va el hilo.
Si estas empezando:
* Comienza a usar Arduino
* Guías de iniciación a Arduino
* Ejemplos
* Referencia del Lenguaje
* Conceptos básicos
Guia de usuario de arduino
Tutoriales en Ingles
Si necesitas que alguien te escriba el código: http://www.freelancer.com/  o esta  http://www.guru.com/

Go Up