Rev Author Line No. Line
2195 kaklik 1 /*
2241 kaklik 2 SD card datalogger
2195 kaklik 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:
2201 kaklik 8 * analog sensors on analog ins PC0, PC1, and PC2
2195 kaklik 9 * SD card attached to SPI bus as follows:
2241 kaklik 10 ** MOSI/CMD - PB3
11 ** MISO/DAT0 - PB4
2201 kaklik 12 ** CLK - PB5
2241 kaklik 13 ** CD/DAT3 - PD4
2195 kaklik 14  
15 */
16  
17 #include <SD.h>
2241 kaklik 18 #define chipSelect 4
2195 kaklik 19  
20 void setup()
21 {
22 Serial.begin(9600);
23 Serial.print("Initializing SD card...");
24 // make sure that the default chip select pin is set to
25 // output, even if you don't use it:
26 pinMode(10, OUTPUT);
27  
28 // see if the card is present and can be initialized:
29 if (!SD.begin(chipSelect)) {
30 Serial.println("Card failed, or not present");
31 // don't do anything more:
32 return;
33 }
34 Serial.println("card initialized.");
35 }
36  
2201 kaklik 37 int count;
38  
2195 kaklik 39 void loop()
40 {
2201 kaklik 41  
2195 kaklik 42 // make a string for assembling the data to log:
2241 kaklik 43 String dataString = "$LOG";
2201 kaklik 44 delay(100);
45 dataString += String(count); // print number of measurement
46 dataString += ",";
2195 kaklik 47  
2201 kaklik 48  
2195 kaklik 49 // read three sensors and append to the string:
50 for (int analogPin = 0; analogPin < 3; analogPin++) {
51 int sensor = analogRead(analogPin);
52 dataString += String(sensor);
53 if (analogPin < 2) {
54 dataString += ",";
55 }
56 }
57  
58 // open the file. note that only one file can be open at a time,
59 // so you have to close this one before opening another.
60 File dataFile = SD.open("datalog.txt", FILE_WRITE);
61  
62 // if the file is available, write to it:
63 if (dataFile) {
64 dataFile.println(dataString);
65 dataFile.close();
66 // print to the serial port too:
67 Serial.println(dataString);
2201 kaklik 68 count++;
2195 kaklik 69 }
70 // if the file isn't open, pop up an error:
71 else {
72 Serial.println("error opening datalog.txt");
73 }
2201 kaklik 74 }