|
| 1 | +/* |
| 2 | + SD card read/write |
| 3 | + |
| 4 | + This example shows how to read and write data to and from an SD card file |
| 5 | + The circuit: |
| 6 | + * SD card attached to SPI bus as follows: |
| 7 | + ** MOSI - pin 11 |
| 8 | + ** MISO - pin 12 |
| 9 | + ** CLK - pin 13 |
| 10 | + ** CS - pin 4 |
| 11 | + |
| 12 | + created Nov 2010 |
| 13 | + by David A. Mellis |
| 14 | + modified 9 Apr 2012 |
| 15 | + by Tom Igoe |
| 16 | + |
| 17 | + This example code is in the public domain. |
| 18 | + |
| 19 | + */ |
| 20 | + |
| 21 | +#include <SD.h> |
| 22 | + |
| 23 | +File myFile; |
| 24 | + |
| 25 | +void setup() |
| 26 | +{ |
| 27 | + // Open serial communications and wait for port to open: |
| 28 | + Serial.begin(9600); |
| 29 | + while (!Serial) { |
| 30 | + ; // wait for serial port to connect. Needed for Leonardo only |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | + Serial.print("Initializing SD card..."); |
| 35 | + // On the Ethernet Shield, CS is pin 4. It's set as an output by default. |
| 36 | + // Note that even if it's not used as the CS pin, the hardware SS pin |
| 37 | + // (10 on most Arduino boards, 53 on the Mega) must be left as an output |
| 38 | + // or the SD library functions will not work. |
| 39 | + pinMode(10, OUTPUT); |
| 40 | + |
| 41 | + if (!SD.begin(10)) { |
| 42 | + Serial.println("initialization failed!"); |
| 43 | + return; |
| 44 | + } |
| 45 | + Serial.println("initialization done."); |
| 46 | + |
| 47 | + // open the file. note that only one file can be open at a time, |
| 48 | + // so you have to close this one before opening another. |
| 49 | + |
| 50 | + |
| 51 | + // re-open the file for reading: |
| 52 | + myFile = SD.open("datalog1.txt"); |
| 53 | + if (myFile) { |
| 54 | + Serial.println("datalog1.txt:"); |
| 55 | + |
| 56 | + // read from the file until there's nothing else in it: |
| 57 | + while (myFile.available()) { |
| 58 | + Serial.write(myFile.read()); |
| 59 | + } |
| 60 | + // close the file: |
| 61 | + myFile.close(); |
| 62 | + } else { |
| 63 | + // if the file didn't open, print an error: |
| 64 | + Serial.println("error opening test.txt"); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +void loop() |
| 69 | +{ |
| 70 | + // nothing happens after setup |
| 71 | +} |
| 72 | + |
| 73 | + |
0 commit comments