var zoomy = "
\n\ \n\

\n\ \"\" \n\

\n\ \n\
\n\ \n\

Whatsit?

\n\
\n\ \n\

\n\ We just got the latest version of the Arduino Ethernet shield with a MicroSD card slot and I promised Bill Greiman I'd try out the latest version of his SdFatLib library so I decided to code up a simple Webified file browser. Its a quicky project and demonstrates what you can do, but it isn't 100% perfect so you should be ready to modify it if you'd like to do other stuff, 'K? \n\

\n\ \n\

\n\ This is a good beginning to a logging web-monitor, or remote storage system.\n\

\n\ \n\
\n\ \n\

Get familiar

\n\
\n\ \n\

\n\ Before you do this tutorial you'll want to get familiar with what you're working on. This isn't a beginner tutorial, its best used by those who already have quite a bit Arduino or microcontroller experience and are 'fluent' in C/C++/Java!\n\

\n\ \n\

\n\ Also, read up on how to use the Ethernet shield and Ethernet library . Then review my notes on SD card usage and installing the library we'll be using \n\

\n\ \n\

\n\ You should have already gotten the Ethernet shield working with your network setup, too.\n\

\n\ \n\

\n\ While we're happy to share this code, please note that this project is just example code. It is completely unsupported. Enjoy it! Mod it! Hack it! But please don't expect more than what is posted here! You can download the latest code from GitHub (click Download Source in the top right) \n\

\n\ \n\
\n\ \n\

Initializing Micro-SD card on an Ethernet shield

\n\
\n\ \n\

\n\ \"\"\n\

\n\ \n\

\n\ The latest Arduino Ethernet shield comes with a handy MicroSD card slot so that you can store and retrieve data through the shield. Very handy! Lets show how to talk to the card.\n\

\n\ \n\

\n\ Be sure to have the very latest version of SdFatLib , as you'll need some of the newer capabilities!\n\

\n\ \n\

\n\ First thing to note is that the SS (Slave Select) pin for the card is digital 4 (although as of the writing of this mini-tutorial, the schematic hasn't been updated, you'll have to trust me!)\n\

\n\ \n\

\n\ Open up the SdFatInfo example sketch and change the line in loop() from\n\

\n\
  uint8_t r = card.init(SPI_HALF_SPEED); 
\n\ \n\

\n\ To:\n\

\n\
  pinMode(10, OUTPUT);                       // set the SS pin as an output (necessary!)\n\
  digitalWrite(10, HIGH);                    // but turn off the W5100 chip!\n\
  uint8_t r = card.init(SPI_HALF_SPEED, 4);  // Use digital 4 as the SD SS line
\n\ \n\

\n\ Be sure to add those two extra lines right before-hand! They Enable the SPI interface. If you're on a Mega, use pin 53 instead of 10\n\

\n\ \n\

\n\ Now upload and test the card, you should see something like this:\n\

\n\ \n\

\n\ \"\"\n\

\n\ \n\

\n\ Indicating you talked to the card all right\n\

\n\ \n\
\n\ \n\

List files

\n\
\n\ \n\

\n\ Put some text files on your SD card, using a computer, so that you have data to read. Make sure they are in the root directory, and not in a folder\n\

\n\ \n\

\n\ Then run the SdFatLs example sketch from the SdFat library, you should see it list all the files you have on the card, again, you'll have to make the changes from above to update the card.init() part to the new SS pin\n\

\n\ \n\

\n\ \"\"\n\

\n\ \n\

\n\ For example, the card I'll be using has two files on it from some previous datalogging.\n\

\n\ \n\
\n\ \n\

Merge WebServer + SdFatLs

\n\
\n\ \n\

\n\ We'll begin by combining WebServer (the example sketch that comes with the Ethernet lib) and SdFatLs to make a web server that lists the files on the SD card. You can download the file here (you'll need to copy&paste it, do so carefully!)then follow along!\n\

\n\ \n\

\n\ Part one is the Ethernet and SD card objects and a simple error function (void error_P(const char* str)) that prints out errors and halts the program if there are serious problems. \n\

\n\ \n\

\n\ You should, of cousre, set your mac and ip as necessary, use the ip and mac that worked from your previous Ethernet shield explorations!\n\

\n\ \n\

\n\ The card, volume, and root are objects that help us traverse the complex structure of an SD card \n\

\n\ \n\

\n\ The error function is not too exciting, it just prints out the error and sits in a while(1); loop forever\n\

\n\
/*\n\
 * This sketch will list all files in the root directory and \n\
 * then do a recursive list of all directories on the SD card.\n\
 *\n\
 */\n\
 \n\
#include <SdFat.h>\n\
#include <SdFatUtil.h>\n\
#include <Ethernet.h>\n\
 \n\
/%%**%%%%**%%%%**%%%%**%%%%**%%%%**%% ETHERNET STUFF %%**%%%%**%%%%**%%%%**%%%%**%%%%**%%/\n\
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };\n\
byte ip[] = { 192, 168, 1, 177 };\n\
Server server(80);\n\
 \n\
/%%**%%%%**%%%%**%%%%**%%%%**%%%%**%% SDCARD STUFF %%**%%%%**%%%%**%%%%**%%%%**%%%%**%%/\n\
Sd2Card card;\n\
SdVolume volume;\n\
SdFile root;\n\
 \n\
// store error strings in flash to save RAM\n\
#define error(s) error_P(PSTR(s))\n\
 \n\
void error_P(const char* str) {\n\
  PgmPrint("error: ");\n\
  SerialPrintln_P(str);\n\
  if (card.errorCode()) {\n\
    PgmPrint("SD error: ");\n\
    Serial.print(card.errorCode(), HEX);\n\
    Serial.print(\',\');\n\
    Serial.println(card.errorData(), HEX);\n\
  }\n\
  while(1);\n\
}
\n\ \n\

\n\ Part 2 is the setup() function. It sets up the Serial object so we can debug the connection in real time. It then prints out the RAM usage. You'll need a Atmega328Arduino for this experiment, and you should see at leat 1000 bytes of RAM free. Once this gets to under 250 bytes, you may be running too low!\n\

\n\ \n\

\n\ Then we do the trick where we make the hardware SS pin #10 to an OUTPUT and HIGH to disable the wiznet chip while we check the card contents. If you're on a Mega, change this to 53. Then we initialize the card which should go fine since you already tested this before\n\

\n\ \n\

\n\ Then we verify the card structure, print out all the files, and print "Done!". Finally we stuck the Ethernet initialization code at the end here! Now we have both the Ethernet and SD card working\n\

\n\
void setup() {\n\
  Serial.begin(9600);\n\
 \n\
  PgmPrint("Free RAM: ");\n\
  Serial.println(FreeRam());  \n\
 \n\
  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with\n\
  // breadboards.  use SPI_FULL_SPEED for better performance.\n\
  pinMode(10, OUTPUT);                       // set the SS pin as an output (necessary!)\n\
  digitalWrite(10, HIGH);                    // but turn off the W5100 chip!\n\
 \n\
  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");\n\
 \n\
  // initialize a FAT volume\n\
  if (!volume.init(&card)) error("vol.init failed!");\n\
 \n\
  PgmPrint("Volume is FAT");\n\
  Serial.println(volume.fatType(),DEC);\n\
  Serial.println();\n\
 \n\
  if (!root.openRoot(&volume)) error("openRoot failed");\n\
 \n\
  // list file in root with date and size\n\
  PgmPrintln("Files found in root:");\n\
  root.ls(LS_DATE | LS_SIZE);\n\
  Serial.println();\n\
 \n\
  // Recursive list of all directories\n\
  PgmPrintln("Files found in all dirs:");\n\
  root.ls(LS_R);\n\
 \n\
  Serial.println();\n\
  PgmPrintln("Done");\n\
 \n\
  // Debugging complete, we start the server!\n\
  Ethernet.begin(mac, ip);\n\
  server.begin();\n\
}
\n\ \n\

\n\ We'll skip ahead to the loop() where we wait for clients (checking via server.available()) and then read the client request before responding. This is basically copy-and-pasted from the Webserver example sketch that comes with the Ethernet library (well, the first and last parts of the loop are at least). \n\

\n\ \n\

\n\ There's a little trick where to simplify the code, the writer of this sketch doesn't actually check to see what file the web browser wants, it always spits out the same thing. In this case, we're going to have it spit out the files by using a helper function called ListFiles(client, 0) which we skipped over but will show next. The 0 in the second argument to the function just tells the function whether to print out the file sizes\n\

\n\
void loop()\n\
{\n\
  Client client = server.available();\n\
  if (client) {\n\
    // an http request ends with a blank line\n\
    boolean current_line_is_blank = true;\n\
    while (client.connected()) {\n\
      if (client.available()) {\n\
        char c = client.read();\n\
        // if we\'ve gotten to the end of the line (received a newline\n\
        // character) and the line is blank, the http request has ended,\n\
        // so we can send a reply\n\
        if (c == \'\\n\' && current_line_is_blank) {\n\
          // send a standard http response header\n\
          client.println("HTTP/1.1 200 OK");\n\
          client.println("Content-Type: text/html");\n\
          client.println();\n\
 \n\
          // print all the files, use a helper to keep it clean\n\
          //ListFiles(client, 0);\n\
          client.println("<h2>Files:</h2>");\n\
          ListFiles(client, 0);\n\
 \n\
          break;\n\
        }\n\
        if (c == \'\\n\') {\n\
          // we\'re starting a new line\n\
          current_line_is_blank = true;\n\
        } else if (c != \'\\r\') {\n\
          // we\'ve gotten a character on the current line\n\
          current_line_is_blank = false;\n\
        }\n\
      }\n\
    }\n\
    // give the web browser time to receive the data\n\
    delay(1);\n\
    client.stop();\n\
  }\n\
}
\n\ \n\

\n\ Now we'll go back and exampine the ListFiles function. This is a bit tedious, but worth looking at. We've simplified it by removing recursive listing, which means we don't list files in any subdirectories. \n\

\n\ \n\

\n\ The dir_t p object is a "Directory Entry" holder. It will store the information for each entry in the directory.\n\

\n\ \n\

\n\ We first reset the root directory by rewind()'ing it. Then we read the directory file by file. Some files are unused or are the "." and ".." (up directory) links, which we ignore. We also only list FILEs or SUBDIRectories.\n\

\n\ \n\

\n\ Then we print the name out by going through all 11 characters (remember the file names are in 8.3 format) and ignore the space. We also stick the '.' between the first 8 and last 3 characters.\n\

\n\ \n\

\n\ If its a directory type file, we put a slash at the end to indicate it. If its not, we can print out the file size in bytes.\n\

\n\ \n\

\n\ Finally, after each file name we stick in a "<br>" which will go to the next line in a web browser\n\

\n\
void ListFiles(Client client, uint8_t flags) {\n\
  // This code is just copied from SdFile.cpp in the SDFat library\n\
  // and tweaked to print to the client output in html!\n\
  dir_t p;\n\
 \n\
  root.rewind ();\n\
  while (root.readDir(p) > 0) {\n\
    // done if past last used entry\n\
    if (p.name[0] == DIR_NAME_FREE) break;\n\
 \n\
    // skip deleted entry and entries for . and  ..\n\
    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == \'.\') continue;\n\
 \n\
    // only list subdirectories and files\n\
    if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;\n\
 \n\
 \n\
    // print file name with possible blank fill\n\
    //root.printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0);\n\
 \n\
 \n\
    for (uint8_t i = 0; i < 11; i++) {\n\
      if (p.name[i] == \' \') continue;\n\
      if (i == 8) {\n\
        client.print(\'.\');\n\
      }\n\
      client.print(p.name[i]);\n\
    }\n\
    if (DIR_IS_SUBDIR(&p)) {\n\
      client.print(\'/\');\n\
    }\n\
 \n\
    // print modify date/time if requested\n\
    if (flags & LS_DATE) {\n\
       root.printFatDate(p.lastWriteDate);\n\
       client.print(\' \');\n\
       root.printFatTime(p.lastWriteTime);\n\
    }\n\
    // print size if requested\n\
    if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {\n\
      client.print(\' \');\n\
      client.print(p.fileSize);\n\
    }\n\
    client.println("<br>");\n\
  }\n\
}
\n\ \n\

\n\ OK after all that work, lets upload that sketch to the Arduino! Make sure you have the correct ip address for your network, then use a browser on the same network to visit your website. Here is what I got - there are those two files from my previous datalogging experiments!\"\"\n\

\n\ \n\
\n\ \n\

Browsing files!

\n\
\n\ \n\

\n\ Obviously, we should make it so you can clicky those file names, eh? Well! Thats the next sketch, you can download the latest version from github here (click Download Source) in the top right hand corner!\n\

\n\ \n\

\n\ Fix the ip address to match your network, and SS pin (if you're on a Mega) \n\

\n\ \n\

\n\ Not a lot has changed between the previous code, the setup is the same, the big changes are in the loop() code. The bones are the same - we look for new client connections. But this time we read the client request into a character buffer (clientline) until we get a newline character (such as \\n or \\r). This indicates we have read an entire line of text. To 'finish' the string, we put a null character (0) at the end.\n\

\n\ \n\

\n\ We then use strstr which will look for substrings. If we have a "GET / HTTP" request for the root directory, we do the same as before, printing out the list of files.\n\

\n\ \n\

\n\ If we have no space after "GET /" that means its something like "GET /file" which means we will have to extract the filename. We make a pointer to the string and start it right after the first slash. Then we look for the beginning of the "HTTP/1.1" string which follows the filename request and turn the first character into a string-terminator. Now we have the name of the file which we can try to open.\n\

\n\ \n\

\n\ If we fail to open the file, we will return a 404. Otherwise, we print out all of the file contents.\n\

\n\
// How big our line buffer should be. 100 is plenty!\n\
#define BUFSIZ 100\n\
 \n\
void loop()\n\
{\n\
  char clientline[BUFSIZ];\n\
  int index = 0;\n\
 \n\
  Client client = server.available();\n\
  if (client) {\n\
    // an http request ends with a blank line\n\
    boolean current_line_is_blank = true;\n\
 \n\
    // reset the input buffer\n\
    index = 0;\n\
 \n\
    while (client.connected()) {\n\
      if (client.available()) {\n\
        char c = client.read();\n\
 \n\
        // If it isn\'t a new line, add the character to the buffer\n\
        if (c != \'\\n\' && c != \'\\r\') {\n\
          clientline[index] = c;\n\
          index++;\n\
          // are we too big for the buffer? start tossing out data\n\
          if (index >= BUFSIZ) \n\
            index = BUFSIZ -1;\n\
 \n\
          // continue to read more data!\n\
          continue;\n\
        }\n\
 \n\
        // got a \\n or \\r new line, which means the string is done\n\
        clientline[index] = 0;\n\
 \n\
        // Print it out for debugging\n\
        Serial.println(clientline);\n\
 \n\
        // Look for substring such as a request to get the root file\n\
        if (strstr (clientline, "GET / ") != 0) {\n\
          // send a standard http response header\n\
          client.println("HTTP/1.1 200 OK");\n\
          client.println("Content-Type: text/html");\n\
          client.println();\n\
 \n\
          // print all the files, use a helper to keep it clean\n\
          client.println("<h2>Files:</h2>");\n\
          ListFiles(client, LS_SIZE);\n\
        } else if (strstr (clientline, "GET /") != 0) {\n\
          // this time no space after the /, so a sub-file!\n\
          char *filename;\n\
 \n\
          filename = clientline + 5; // look after the "GET /" (5 chars)\n\
          // a little trick, look for the " HTTP/1.1" string and \n\
          // turn the first character of the substring into a 0 to clear it out.\n\
          (strstr (clientline, " HTTP"))[0] = 0;\n\
 \n\
          // print the file we want\n\
          Serial.println(filename);\n\
 \n\
          if (! file.open(&root, filename, O_READ)) {\n\
            client.println("HTTP/1.1 404 Not Found");\n\
            client.println("Content-Type: text/html");\n\
            client.println();\n\
            client.println("<h2>File Not Found!</h2>");\n\
            break;\n\
          }\n\
 \n\
          Serial.println("Opened!");\n\
 \n\
          client.println("HTTP/1.1 200 OK");\n\
          client.println("Content-Type: text/plain");\n\
          client.println();\n\
 \n\
          int16_t c;\n\
          while ((c = file.read()) > 0) {\n\
              // uncomment the serial to debug (slow!)\n\
              //Serial.print((char)c);\n\
              client.print((char)c);\n\
          }\n\
          file.close();\n\
        } else {\n\
          // everything else is a 404\n\
          client.println("HTTP/1.1 404 Not Found");\n\
          client.println("Content-Type: text/html");\n\
          client.println();\n\
          client.println("<h2>File Not Found!</h2>");\n\
        }\n\
        break;\n\
      }\n\
    }\n\
    // give the web browser time to receive the data\n\
    delay(1);\n\
    client.stop();\n\
  }\n\
}
\n\ \n\

\n\ Lets look at the new file listing code as well, its very similar, but now we've added a bit of HTML so that each file is part of a <ul> list and the name is a URL link.\n\

\n\
void ListFiles(Client client, uint8_t flags) {\n\
  // This code is just copied from SdFile.cpp in the SDFat library\n\
  // and tweaked to print to the client output in html!\n\
  dir_t p;\n\
 \n\
  root.rewind ();\n\
  client.println("<ul>");\n\
  while (root.readDir(p) > 0) {\n\
    // done if past last used entry\n\
    if (p.name[0] == DIR_NAME_FREE) break;\n\
 \n\
    // skip deleted entry and entries for . and  ..\n\
    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == \'.\') continue;\n\
 \n\
    // only list subdirectories and files\n\
    if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;\n\
 \n\
    // print any indent spaces\n\
    client.print("<li><a href=\\"");\n\
    for (uint8_t i = 0; i < 11; i++) {\n\
      if (p.name[i] == \' \') continue;\n\
      if (i == 8) {\n\
        client.print(\'.\');\n\
      }\n\
      client.print(p.name[i]);\n\
    }\n\
    client.print("\\">");\n\
 \n\
    // print file name with possible blank fill\n\
    for (uint8_t i = 0; i < 11; i++) {\n\
      if (p.name[i] == \' \') continue;\n\
      if (i == 8) {\n\
        client.print(\'.\');\n\
      }\n\
      client.print(p.name[i]);\n\
    }\n\
 \n\
    client.print("</a>");\n\
 \n\
    if (DIR_IS_SUBDIR(&p)) {\n\
      client.print(\'/\');\n\
    }\n\
 \n\
    // print modify date/time if requested\n\
    if (flags & LS_DATE) {\n\
       root.printFatDate(p.lastWriteDate);\n\
       client.print(\' \');\n\
       root.printFatTime(p.lastWriteTime);\n\
    }\n\
    // print size if requested\n\
    if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {\n\
      client.print(\' \');\n\
      client.print(p.fileSize);\n\
    }\n\
    client.println("</li>");\n\
  }\n\
  client.println("</ul>");\n\
}
\n\ \n\

\n\ OK upload the sketch already!\n\

\n\ \n\

\n\ Now you'll see that the file names have turned into links (we also added the file size in bytes)\n\

\n\ \n\

\n\ \"\"\n\

\n\ \n\

\n\ Click on a filename to view it\n\

\n\ \n\

\n\ \"\"\n\

\n\ \n\

\n\ If you try to view a file that is not on the card, you'll get a 404 error (file not found)\n\

\n\ \n\

\n\ \"\"\n\

\n\ \n\
\n\ ";document.write(zoomy);document.write("

This page was autogenerated from http://www.ladyada.net/wiki//tutorials/learn/arduino/ethfiles.html
Please edit the wiki to contribute any updates or corrections.
")