You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.3KB

  1. /*
  2. SD card datalogger
  3. This example shows how to log data from three analog sensors
  4. to an SD card using the SD library.
  5. The circuit:
  6. * analog sensors on analog ins 0, 1, and 2
  7. * SD card attached to SPI bus as follows:
  8. ** MOSI - pin 11
  9. ** MISO - pin 12
  10. ** CLK - pin 13
  11. ** CS - pin 4
  12. created 24 Nov 2010
  13. modified 9 Apr 2012
  14. by Tom Igoe
  15. This example code is in the public domain.
  16. */
  17. #include <SD.h>
  18. #include <SPI.h>
  19. // On the Ethernet Shield, CS is pin 4. Note that even if it's not
  20. // used as the CS pin, the hardware CS pin (10 on most Arduino boards,
  21. // 53 on the Mega) must be left as an output or the SD library
  22. // functions will not work.
  23. // change this to match your SD shield or module;
  24. // Arduino Ethernet shield: pin 4
  25. // Adafruit SD shields and modules: pin 10
  26. // Sparkfun SD shield: pin 8
  27. // Teensy 2.0: pin 0
  28. // Teensy++ 2.0: pin 20
  29. const int chipSelect = 4;
  30. void setup()
  31. {
  32. // Open serial communications and wait for port to open:
  33. Serial.begin(9600);
  34. while (!Serial) {
  35. ; // wait for serial port to connect. Needed for Leonardo only
  36. }
  37. Serial.print("Initializing SD card...");
  38. // make sure that the default chip select pin is set to
  39. // output, even if you don't use it:
  40. pinMode(10, OUTPUT);
  41. // see if the card is present and can be initialized:
  42. if (!SD.begin(chipSelect)) {
  43. Serial.println("Card failed, or not present");
  44. // don't do anything more:
  45. return;
  46. }
  47. Serial.println("card initialized.");
  48. }
  49. void loop()
  50. {
  51. // make a string for assembling the data to log:
  52. String dataString = "";
  53. // read three sensors and append to the string:
  54. for (int analogPin = 0; analogPin < 3; analogPin++) {
  55. int sensor = analogRead(analogPin);
  56. dataString += String(sensor);
  57. if (analogPin < 2) {
  58. dataString += ",";
  59. }
  60. }
  61. // open the file. note that only one file can be open at a time,
  62. // so you have to close this one before opening another.
  63. File dataFile = SD.open("datalog.txt", FILE_WRITE);
  64. // if the file is available, write to it:
  65. if (dataFile) {
  66. dataFile.println(dataString);
  67. dataFile.close();
  68. // print to the serial port too:
  69. Serial.println(dataString);
  70. }
  71. // if the file isn't open, pop up an error:
  72. else {
  73. Serial.println("error opening datalog.txt");
  74. }
  75. }