Advertisement
Guest User

Untitled

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