Ethernet and sd card not working well toghter

Hi.

I’m trying to merge to example found on playground together.

I want to both use the sd card web server

server/http://startingelectronics.com/tutorials/arduino/ethernet-shield-web-server-tutorial/SD-card-web-server/

and the NTP sync example on the time library.

both sketch works well alone but in the same sketch, it froze in the setup.

Im using Arduino due whith an ethernet shield.
Thats my sketch so far.

#include <Time.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <EthernetUdp.h>

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 110); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
File webFile;

const int timeZone = -5;  // Eastern Standard Time (USA)
EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets



void setup()
{
  Serial.begin(9600);       // for debugging
  Ethernet.begin(mac, ip);  // initialize Ethernet device
  server.begin();           // start to listen for clients
  Serial.print("Ip address; "); Serial.println(Ethernet.localIP());
  if (Ethernet.begin(mac) == 0) {
    // no point in carrying on, so do nothing forevermore:
    while (1) {
      Serial.println("Failed to configure Ethernet using DHCP");
      delay(10000);
    }
  }


     // initialize SD card
     Serial.println("Initializing SD card...");
     if (!SD.begin(4)) {
         Serial.println("ERROR - SD card initialization failed!");
         return;    // init failed
     }
     Serial.println("SUCCESS - SD card initialized.");
     // check for index.htm file
     if (!SD.exists("index.htm")) {
         Serial.println("ERROR - Can't find index.htm file!");
         return;  // can't find index file
     }
     Serial.println("SUCCESS - Found index.htm file.");
  
  server.begin();
  Udp.begin(localPort);
  Serial.println("waiting for sync");
  //  setSyncProvider(getNtpTime);
  pinMode(10, OUTPUT);

}

time_t prevDisplay = 0; // when the digital clock was displayed

void loop()
{

  if (Serial.available() > 0) ; {

    if (timeStatus() != timeNotSet) {
      if (now() != prevDisplay) { //update the display only if time has changed
        prevDisplay = now();
        digitalClockDisplay();
      }
    }
  }

  
    EthernetClient client = server.available();  // try to get client

      if (client) {  // got client?
          boolean currentLineIsBlank = true;
          while (client.connected()) {
              if (client.available()) {   // client data available to read
                  char c = client.read(); // read 1 byte (character) from client
                  // last line of client request is blank and ends with \n
                  // respond to client only after last line received
                  if (c == '\n' && currentLineIsBlank) {
                      // send a standard http response header
                      client.println("HTTP/1.1 200 OK");
                      client.println("Content-Type: text/html");
                      client.println("Connection: close");
                      client.println();
                      // send web page
                      webFile = SD.open("index.htm");        // open web page file
                      if (webFile) {
                          while(webFile.available()) {
                              client.write(webFile.read()); // send web page to client
                          }
                          webFile.close();
                      }
                      break;
                  }
                  // every line of text received from the client ends with \r\n
                  if (c == '\n') {
                      // last character on line of received text
                      // starting new line with next character read
                      currentLineIsBlank = true;
                  }
                  else if (c != '\r') {
                      // a text character was received from client
                      currentLineIsBlank = false;
                  }
              } // end if (client.available())
          } // end while (client.connected())
          delay(1);      // give the web browser time to receive the data
          client.stop(); // close the connection
      } // end if (client)
  
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print("/");
  Serial.print(month());
  Serial.print("/");
  Serial.print(year());
  Serial.println();
}

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

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

Could you set both chip selects high to disable them ? Make pin 10 and 4 output with pinMode, and set them high with digitalWrite. After that you can do Ethernet.begin and SD.begin.

In addition to Peter_n's suggestion, call Ethernet begin() only once in your setup function.

Well spotted SurferTim, somehow I didn’t see that :o

look like it doesn’t fix it… :frowning:

getting no ip. but the sd card seem reading.
thats what I have from the serial monitor:

Ip address; 0.0.0.0
Initializing SD card…
SUCCESS - SD card initialized.
SUCCESS - Found index.htm file.
waiting for sync

And the void setup is now:

void setup()
{
pinMode(4,OUTPUT);
pinMode(10,OUTPUT);
digitalWrite(4,HIGH);
digitalWrite(10,HIGH);

  Serial.begin(9600);       // for debugging
  Ethernet.begin(mac, ip);  // initialize Ethernet device
      delay(10000);
  server.begin();           // start to listen for clients
  Serial.print("Ip address; "); Serial.println(Ethernet.localIP());
/*  if (Ethernet.begin(mac) == 0) {
    // no point in carrying on, so do nothing forevermore:
    while (1) {
      Serial.println("Failed to configure Ethernet using DHCP");
      delay(10000);
    }
  }*/


     // initialize SD card
     Serial.println("Initializing SD card...");
     if (!SD.begin(4)) {
         Serial.println("ERROR - SD card initialization failed!");
         return;    // init failed
     }
     Serial.println("SUCCESS - SD card initialized.");
     // check for index.htm file
     if (!SD.exists("index.htm")) {
         Serial.println("ERROR - Can't find index.htm file!");
         return;  // can't find index file
     }
     Serial.println("SUCCESS - Found index.htm file.");
  
  server.begin();
  Udp.begin(localPort);
  Serial.println("waiting for sync");
  //  setSyncProvider(getNtpTime);
  pinMode(10, OUTPUT);

}

I have a time NTP request running with an Arduino Mega 2560 and Ethernet shield. I made that once, and it is running since then.

The return of 0.0.0.0 indicates that you can not connect to the W5100 chip. Or do you have another Ethernet Shield ?

Could you try to print the LocalIP before the Server.begin() ? You can also remove that 10 seconds delay.

Do you have Ethernet Shield version "R3" ? That version automatically switched to get it's power to the 3.3V when attached to an Arduino Due. Do you also use the newest Arduino IDE 1.5.8 BETA ?

Peter_n: Print the localIp before the sever.begin doesn't change a thing. getting 0.0.0.0 ip.

I don't have another internet shield but this one working with another sketch. I can't tell the version of it. this info is not printed on it. the only info I have is "Mega compatible".

I'm using version 1.5.6r-2 of the arduino IDE.

I think the Ethernet Shield is an old version. But first you have to use Arduino IDE 1.5.8 BETA. New improvements are made all the time, so you have to use the newest version.

If 1.5.8 BETA is still not working, you probably have a older Ethernet Shield. You can use it for a Mega or Uno board, but you have to buy a 'R3' version for the Due.

There is a possibility that you use a library that is not compatible with the Due. Did you install a library or are you only using the default libraries ?

Try this short test sketch. Does it show 192.168.2.2 in the serial monitor?

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,2,2);

void setup() {
  Serial.begin(9600);

  // disable SD SPI
  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

  // Start ethernet
  Serial.print(F("Starting ethernet..."));
  Ethernet.begin(mac, ip);
  Serial.println(Ethernet.localIP());
}

void loop() {
}

Peter_n

I think the Ethernet Shield is an old version.
But first you have to use Arduino IDE 1.5.8 BETA. New improvements are made all the time, so you have to use the newest version.

If 1.5.8 BETA is still not working, you probably have a older Ethernet Shield. You can use it for a Mega or Uno board, but you have to buy a ‘R3’ version for the Due.

I’ve tried whit 1.5.8. no change. this is a picture of my shield. Maybe you can identify if a have an R3 or not. if not, what can be my alternative (except to buy an other one for now… :stuck_out_tongue: ) ?

SurferTim

Try this short test sketch. Does it show 192.168.2.2 in the serial monitor?

yes it display until I add the NTP sketck and the sd web page together

OK. Try adding a little bit of your code. This gets all the devices and services running. Let’s see where it fails. Does this work ok?

#include <Time.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <EthernetUdp.h>

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 110); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
File webFile;

const int timeZone = -5;  // Eastern Standard Time (USA)
EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets



void setup()
{
  Serial.begin(9600);       // for debugging

  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

  Ethernet.begin(mac, ip);  // initialize Ethernet device
  Serial.print("Ip address; "); Serial.println(Ethernet.localIP());

  // initialize SD card
  Serial.print("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("failed!");
    return;    // init failed
  }
  Serial.println("initialized.");
  
  Serial.println("Starting server");
  server.begin();           // start to listen for clients

  Serial.println("Starting UDP");
  Udp.begin(localPort);

  Serial.println("Setup complete");
}

void loop() {
}

My apology in advance for any typos.

YESSSSSSSSSSSSSSSSSSSSSSSSSSSSS
ALL debuggued !!!

now the fun continue ! … :stuck_out_tongue:

Thanks a lot all for your time !

thats the final code for people how want to do the same thing !! :stuck_out_tongue:

#include <Time.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <EthernetUdp.h>

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 110); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
File webFile;

const int timeZone = -5;  // Eastern Standard Time (USA)
EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets



void setup()
{
pinMode(4,OUTPUT);
//pinMode(10,OUTPUT);
digitalWrite(4,HIGH);
//digitalWrite(10,HIGH);

  Serial.begin(9600);       // for debugging
  Ethernet.begin(mac, ip);  // initialize Ethernet device
  Serial.print("Ip address; "); Serial.println(Ethernet.localIP());


     // initialize SD card
     Serial.println("Initializing SD card...");
     if (!SD.begin(4)) {
         Serial.println("ERROR - SD card initialization failed!");
         return;    // init failed
     }
     Serial.println("SUCCESS - SD card initialized.");
     // check for index.htm file
  Serial.println("Starting server");
  server.begin();           // start to listen for clients
     if (!SD.exists("index.htm")) {
         Serial.println("ERROR - Can't find index.htm file!");
         return;  // can't find index file
     }
     Serial.println("SUCCESS - Found index.htm file.");
      delay(10000);  

  Udp.begin(localPort);
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);


}

time_t prevDisplay = 0; // when the digital clock was displayed

void loop()
{

  if (Serial.available() > 0) ; {

    if (timeStatus() != timeNotSet) {
      if (now() != prevDisplay) { //update the display only if time has changed
        prevDisplay = now();
        digitalClockDisplay();
      }
    }
  }

  
    EthernetClient client = server.available();  // try to get client

      if (client) {  // got client?
          boolean currentLineIsBlank = true;
          while (client.connected()) {
              if (client.available()) {   // client data available to read
                  char c = client.read(); // read 1 byte (character) from client
                  // last line of client request is blank and ends with \n
                  // respond to client only after last line received
                  if (c == '\n' && currentLineIsBlank) {
                      // send a standard http response header
                      client.println("HTTP/1.1 200 OK");
                      client.println("Content-Type: text/html");
                      client.println("Connection: close");
                      client.println();
                      // send web page
                      webFile = SD.open("index.htm");        // open web page file
                      if (webFile) {
                          while(webFile.available()) {
                              client.write(webFile.read()); // send web page to client
                          }
                          webFile.close();
                      }
                      break;
                  }
                  // every line of text received from the client ends with \r\n
                  if (c == '\n') {
                      // last character on line of received text
                      // starting new line with next character read
                      currentLineIsBlank = true;
                  }
                  else if (c != '\r') {
                      // a text character was received from client
                      currentLineIsBlank = false;
                  }
              } // end if (client.available())
          } // end while (client.connected())
          delay(1);      // give the web browser time to receive the data
          client.stop(); // close the connection
      } // end if (client)
  
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print("/");
  Serial.print(month());
  Serial.print("/");
  Serial.print(year());
  Serial.println();
}

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

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}