ecalifornica

reddit question 003 arduino

Oct 20th, 2012
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.90 KB | None | 0 0
  1.  
  2. /*
  3.  * This sketch uses the microSD card slot on the Arduino Ethernet shield
  4.  * to serve up files over a very minimal browsing interface
  5.  *
  6.  * Some code is from Bill Greiman's SdFatLib examples, some is from the
  7.  * Arduino Ethernet WebServer example and the rest is from Limor Fried
  8.  * (Adafruit) so its probably under GPL
  9.  *
  10.  * Tutorial is at http://www.ladyada.net/learn/arduino/ethfiles.html
  11.  * Pull requests should go to http://github.com/adafruit/SDWebBrowse
  12.  */
  13.  
  14. #include <SdFat.h>
  15. #include <SdFatUtil.h>
  16. #include <Ethernet.h>
  17. #include <SPI.h>
  18.  
  19. /************ ETHERNET STUFF ************/
  20. byte mac[] = {
  21.   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  22. byte ip[] = {
  23.   192, 168, 1, 8 };
  24. EthernetServer server(80);
  25.  
  26. /************ SDCARD STUFF ************/
  27. Sd2Card card;
  28. SdVolume volume;
  29. SdFile root;
  30. SdFile file;
  31.  
  32. //SdFat sd;
  33.  
  34.  
  35. // TMP102
  36. #include <Wire.h>
  37. int TMP102Address = 0x48;
  38.  
  39. // RTC
  40. #include "RTClib.h"
  41. RTC_DS1307 RTC;
  42.  
  43. // haven't figured out how to use the RTC as intervalometer
  44. long previousMillis;
  45. long interval = 15000;
  46.  
  47. // store error strings in flash to save RAM
  48. #define error(s) error_P(PSTR(s))
  49.  
  50. //// //// error print? //// ////
  51. void error_P(const char* str) {
  52.   PgmPrint("error: ");
  53.   SerialPrintln_P(str);
  54.   if (card.errorCode()) {
  55.     PgmPrint("SD error: ");
  56.     Serial.print(card.errorCode(), HEX);
  57.     Serial.print(',');
  58.     Serial.println(card.errorData(), HEX);
  59.   }
  60.   while(1);
  61. }
  62.  
  63.  
  64. //// //// SETUP //// ////
  65.  
  66. void setup() {
  67.   Serial.begin(9600);
  68.   Serial.println();
  69.   //Serial.println();
  70.   PgmPrint("20121020 0000");
  71.   Serial.println();
  72.   Wire.begin();
  73.   RTC.begin();
  74.   PgmPrint("Free RAM: ");
  75.   Serial.println(FreeRam());  
  76.  
  77.   // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  78.   // breadboards.  use SPI_FULL_SPEED for better performance.
  79.   pinMode(10, OUTPUT);                       // set the SS pin as an output (necessary!)
  80.   digitalWrite(10, HIGH);                    // but turn off the W5100 chip!
  81.   // pin 4?
  82.   if (!card.init(SPI_FULL_SPEED, 4)) error("card.init failed!");
  83.  
  84.   // initialize a FAT volume
  85.   if (!volume.init(&card)) error("vol.init failed!");
  86.  
  87.   PgmPrint("Volume is FAT");
  88.   Serial.println(volume.fatType(),DEC);
  89.   Serial.println();
  90.  
  91.   if (!root.openRoot(&volume)) error("openRoot failed");
  92.  
  93.   // list file in root with date and size
  94.   PgmPrintln("Files found in root:");
  95.   root.ls(LS_DATE | LS_SIZE);
  96.   Serial.println();
  97.  
  98.   // Recursive list of all directories
  99.   PgmPrintln("Files found in all dirs:");
  100.   root.ls(LS_R);
  101.  
  102.   Serial.println();
  103.   PgmPrintln("Done");
  104.  
  105.  
  106.   // Debugging complete, we start the server!
  107.   Ethernet.begin(mac, ip);
  108.   server.begin();
  109. }
  110.  
  111. //// //// //// ////
  112. void ListFiles(EthernetClient client, uint8_t flags) {
  113.   // This code is just copied from SdFile.cpp in the SDFat library
  114.   // and tweaked to print to the client output in html!
  115.   dir_t p;
  116.   root.rewind();
  117.   //client.println("<ul>");
  118.   while (root.readDir(p) > 0) {
  119.     // done if past last used entry
  120.     if (p.name[0] == DIR_NAME_FREE) break;
  121.     // skip deleted entry and entries for . and  ..
  122.     if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue;
  123.     // only list subdirectories and files
  124.     if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;
  125.     // print any indent spaces
  126.     //client.print("<li><a href=\"");
  127.     for (uint8_t i = 0; i < 11; i++) {
  128.       if (p.name[i] == ' ') continue;
  129.       if (i == 8) {
  130.         client.print('.');
  131.       }
  132.       client.print((char)p.name[i]);
  133.     }
  134.     //client.print("\">");
  135.     // print file name with possible blank fill
  136.     /*
  137.     for (uint8_t i = 0; i < 11; i++) {
  138.       if (p.name[i] == ' ') continue;
  139.       if (i == 8) {
  140.         client.print('.');
  141.       }
  142.       client.print((char)p.name[i]);
  143.     }
  144.     */
  145.     //client.print("</a>");
  146.     if (DIR_IS_SUBDIR(&p)) {
  147.       client.print('/');
  148.     }
  149.     // print modify date/time if requested
  150.     if (flags & LS_DATE) {
  151.       root.printFatDate(p.lastWriteDate);
  152.       client.print(' ');
  153.       root.printFatTime(p.lastWriteTime);
  154.     }
  155.     // print size if requested
  156.     if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {
  157.       client.print(' ');
  158.       client.print(p.fileSize);
  159.       client.println("<br>");
  160.     }
  161.    // client.println("</li>");
  162.   }
  163.   //client.println("</ul>");
  164. }
  165.  
  166. //// //// TMP102 //// ////
  167. float readTMP102_C() {
  168.   Wire.requestFrom(TMP102Address, 2);
  169.   byte MSB = Wire.read();
  170.   byte LSB = Wire.read();
  171.  
  172.   // don't understand this yet
  173.   int TemperatureSum = ((MSB << 8) | LSB) >> 4;
  174.   float TMP102_C = TemperatureSum*0.0625;
  175.   return TMP102_C;
  176. }
  177.  
  178. // How big our line buffer should be. 100 is plenty!
  179. // don t fully understand this. 100 bytes? i ve tried making this 200
  180. #define BUFSIZ 100
  181.  
  182. //// //// LOOP //// ////
  183.  
  184. void loop()
  185. {
  186.   //
  187.  
  188.   unsigned long currentMillis = millis();
  189.   // IF
  190.   if (currentMillis - previousMillis > interval) { //replace with RTC
  191.     previousMillis = currentMillis;
  192.     // TMP102
  193.     float TMP102_C = readTMP102_C();
  194.     //////////////////////////////////////////////HIH4030
  195.     float HIH4030 = analogRead(0);
  196.     HIH4030 = (HIH4030/1023)/(1.0546 - 0.00216*TMP102_C);
  197.     //////////////////////////////////////MOISTURE SENSOR
  198.     /*
  199.     digitalWrite(moistureSensorVcc, HIGH);
  200.      delay(500);
  201.      moistureValue = analogRead(moistureSensor);
  202.      digitalWrite(moistureSensorVcc, LOW);
  203.      moistureValue = map(moistureValue, 0, 1023, 0, 100);
  204.      */
  205.      
  206.     //debug delete files
  207.     //char deleteFile[] = "DATA118.CSV";
  208.     //if(!file.open(root, deleteFile, O_WRITE)) ("Opening delete file failed");
  209.     //if (!file.remove()) error("Deletion of 106 failed");
  210.     //Serial.print(deleteFile);
  211.     //PgmPrintln(" deleted.");
  212.     ////
  213.     char name[] = "DATA119.CSV";
  214.     //PgmPrint("Appending to: ");
  215.     //Serial.println(name);
  216.     if (!file.open(root, name, O_CREAT | O_APPEND | O_WRITE)) error("open failed");
  217.     DateTime now = RTC.now();
  218.     file.print(now.year(), DEC);
  219.     file.print(now.month(), DEC);
  220.     file.print(now.day(), DEC);
  221.     file.print("_");
  222.     if (int(now.hour()) < 10) {
  223.       file.print("0");
  224.       file.print(now.hour(), DEC);
  225.     }
  226.     else {
  227.       file.print(now.hour(), DEC);
  228.     }
  229.     file.print(":");
  230.     if (int(now.minute()) < 10) {
  231.       file.print("0");
  232.       file.print(now.minute(), DEC);
  233.     }
  234.     else {
  235.       file.print(now.minute(), DEC);
  236.     }
  237.     file.print(":");
  238.     if (int(now.second()) < 10) {
  239.       file.print("0");
  240.       file.print(now.second(), DEC);
  241.     }
  242.     else {
  243.       file.print(now.second(), DEC);
  244.     }      
  245.     file.print(", ");
  246.     file.print(now.unixtime());
  247.     //Serial.print(now.unixtime());
  248.     file.print(", ");
  249.     //Serial.print(", ");
  250.     file.print(TMP102_C);
  251.     //Serial.println(TMP102_C);
  252.     file.print(", ");
  253.     file.print(HIH4030);
  254.     file.println("");
  255.     if (file.writeError) error("write failed");
  256.     if (!file.close()) error("close failed");    
  257.     //Serial.println("Done");
  258.     Serial.println();
  259.   }
  260.  
  261.   ////
  262.   char clientline[BUFSIZ];
  263.   int index = 0;
  264.  
  265.   EthernetClient client = server.available();
  266.   if (client) {
  267.     // an http request ends with a blank line
  268.     boolean current_line_is_blank = true;
  269.  
  270.     // reset the input buffer
  271.     index = 0;
  272.  
  273.     while (client.connected()) {
  274.       if (client.available()) {
  275.         char c = client.read();
  276.  
  277.         // If it isn't a new line, add the character to the buffer
  278.         if (c != '\n' && c != '\r') {
  279.           clientline[index] = c;
  280.           index++;
  281.           // are we too big for the buffer? start tossing out data
  282.           if (index >= BUFSIZ)
  283.             index = BUFSIZ -1;
  284.  
  285.           // continue to read more data!
  286.           continue;
  287.         }
  288.  
  289.         // got a \n or \r new line, which means the string is done
  290.         clientline[index] = 0;
  291.  
  292.         // Print it out for debugging
  293.         Serial.print("clientline: ");
  294.         Serial.println(clientline);
  295.  
  296.         // Look for substring such as a request to get the root file
  297.         if (strstr(clientline, "GET / ") != 0) {
  298.           // send a standard http response header
  299.           client.println("HTTP/1.1 200 OK");
  300.           client.println("Content-Type: text/html");
  301.           client.println();
  302.  
  303.           // print all the files, use a helper to keep it clean
  304.           //client.println("<h2>Files:</h2>");
  305.           ListFiles(client, LS_SIZE);
  306.         }
  307.         else if (strstr(clientline, "GET /") != 0) {
  308.           // this time no space after the /, so a sub-file!
  309.           char *filename;
  310.  
  311.           filename = clientline + 5; // look after the "GET /" (5 chars)
  312.           // a little trick, look for the " HTTP/1.1" string and
  313.           // turn the first character of the substring into a 0 to clear it out.
  314.           (strstr(clientline, " HTTP"))[0] = 0;
  315.  
  316.           // print the file we want
  317.           Serial.println(filename);
  318.  
  319.           if (! file.open(&root, filename, O_READ)) {
  320.             client.println("HTTP/1.1 404 Not Found");
  321.             client.println("Content-Type: text/html");
  322.             client.println();
  323.             client.println("<h2>File Not Found!</h2>");
  324.             break;
  325.           }
  326.  
  327.           Serial.println("Opened!");
  328.  
  329.           client.println("HTTP/1.1 200 OK");
  330.           client.println("Content-Type: text/plain");
  331.           client.println();
  332.  
  333.           int16_t c;
  334.           while ((c = file.read()) > 0) {
  335.             // uncomment the serial to debug (slow!)
  336.             //Serial.print((char)c);
  337.             client.print((char)c);
  338.           }
  339.           file.close();
  340.         }
  341.         else {
  342.           // everything else is a 404
  343.           client.println("HTTP/1.1 404 Not Found");
  344.           client.println("Content-Type: text/html");
  345.           client.println();
  346.           client.println("<h2>File Not Found!</h2>");
  347.         }
  348.         break;
  349.       }
  350.     }
  351.     // give the web browser time to receive the data
  352.     delay(1);
  353.     client.stop();
  354.   }
  355. }
Add Comment
Please, Sign In to add comment