Using ethernet and SD card

I have a 2560 Mega R3 and Ethernet shield R3. I want to use both the Ethernet and SD card in my sketch. I did some searching and I'm a bit confused about how to handle the chip select (CS). For Ethernet communication, CS is pin 53 on the mega and the SD is pin 4. I read that I need to make sure pin 53 is defined as an output. Here is what I have in setup()

void setup(void) {
  Serial.begin(9600);
  
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);

  // Initialize Ethernet
  Ethernet.begin(mac);
  delay(1000);
  
  // Initialize SD Card
  if ( SD.begin(chipSelect) )
  { Serial.println("card initialized."); }
  else
  { Serial.println("Card failed, or not present"); }
}

In the rest of my sketch I'm sending Tweets using twitter.h library, sending data to xively using the xively.h library and data logging to the SD card with the sd.h library. It all seems to work okay. But I wanted to know if I should be doing something with the chip select pins. Currently I don't do anything outside of what is done in setup().

D53 is set to OUTPUT by the Ethernet.begin() and SD.begin() calls. You really should disable all other SPI devices before initializing them. In your case, I would disable the SD SPI while starting the w5100. Failure to do so will occasionally result in the ethernet dhcp failing. I added that check in your setup below.

void setup(void) {
  Serial.begin(9600);
  
  // disable SD while starting w5100
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);

  // Initialize Ethernet
  Serial.print(F("Starting w5100..."));
  if(Ethernet.begin(mac)) Serial.println(Ethernet.localIP());
  else Serial.println(F("failed"));

  // Initialize SD Card
  if ( SD.begin(chipSelect) )
  { Serial.println("card initialized."); }
  else
  { Serial.println("Card failed, or not present"); }
}

I normally start the SD first because I sometimes keep the network settings on my SD card, but that is just personal preference.

Thanks for the info on disabling SD card first. While looping in the main sketch, will each SPI device handle enable and disable itself automatically via CS pins?

Yes, the library code deals with the slave select pins after they are all started.

Search the forum for zoomkat's recent server code that uploads files (pages) from the SD card. That will help in a couple ways. It will also show you how to get a 400% increase in upload speed by using a 64 byte buffer.