Advertisement
Guest User

Untitled

a guest
Jul 20th, 2015
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1.  
  2. /*
  3. SD card datalogger
  4.  
  5. This example shows how to log data from three analog sensors
  6. to an SD card using the SD library.
  7.  
  8. The circuit:
  9. * analog sensors on analog ins 0, 1, and 2
  10. * SD card attached to SPI bus as follows:
  11. ** MOSI - pin 11
  12. ** MISO - pin 12
  13. ** CLK - pin 13
  14. ** CS - pin 4
  15.  
  16. created 24 Nov 2010
  17. modified 9 Apr 2012
  18. by Tom Igoe
  19.  
  20. This example code is in the public domain.
  21.  
  22. */
  23.  
  24. #include <SPI.h>
  25. #include <SD.h>
  26.  
  27. const int chipSelect = 4;
  28.  
  29. void setup() {
  30. // Open serial communications and wait for port to open:
  31. Serial.begin(9600);
  32. while (!Serial) {
  33. ; // wait for serial port to connect. Needed for Leonardo only
  34. }
  35.  
  36.  
  37. Serial.print("Initializing SD card...");
  38.  
  39. // see if the card is present and can be initialized:
  40. if (!SD.begin(chipSelect)) {
  41. Serial.println("Card failed, or not present");
  42. // don't do anything more:
  43. return;
  44. }
  45. Serial.println("card initialized.");
  46. }
  47.  
  48. void loop() {
  49. // make a string for assembling the data to log:
  50. String dataString = "";
  51.  
  52. // read three sensors and append to the string:
  53. for (int analogPin = 0; analogPin < 3; analogPin++) {
  54. int sensor = analogRead(analogPin);
  55. dataString += String(sensor);
  56. if (analogPin < 2) {
  57. dataString += ",";
  58. }
  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.  
  65. // if the file is available, write to it:
  66. if (dataFile) {
  67. dataFile.println(dataString);
  68. dataFile.close();
  69. // print to the serial port too:
  70. Serial.println(dataString);
  71. }
  72. // if the file isn't open, pop up an error:
  73. else {
  74. Serial.println("error opening datalog.txt");
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement