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 <SPI.h>
|
---|
22 | #include <SD.h>
|
---|
23 |
|
---|
24 | File myFile;
|
---|
25 |
|
---|
26 | void setup()
|
---|
27 | {
|
---|
28 | // Open serial communications and wait for port to open:
|
---|
29 | Serial.begin(9600);
|
---|
30 | while (!Serial) {
|
---|
31 | ; // wait for serial port to connect. Needed for Leonardo only
|
---|
32 | }
|
---|
33 |
|
---|
34 |
|
---|
35 | Serial.print("Initializing SD card...");
|
---|
36 | // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
|
---|
37 | // Note that even if it's not used as the CS pin, the hardware SS pin
|
---|
38 | // (10 on most Arduino boards, 53 on the Mega, 14 on the Leonardo) must be left as an output
|
---|
39 | // or the SD library functions will not work.
|
---|
40 |
|
---|
41 | if (!SD.begin(4)) {
|
---|
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 | myFile = SD.open("test.txt", FILE_WRITE);
|
---|
50 |
|
---|
51 | // if the file opened okay, write to it:
|
---|
52 | if (myFile) {
|
---|
53 | Serial.print("Writing to test.txt...");
|
---|
54 | myFile.println("testing 1, 2, 3.");
|
---|
55 | // close the file:
|
---|
56 | myFile.close();
|
---|
57 | Serial.println("done.");
|
---|
58 | } else {
|
---|
59 | // if the file didn't open, print an error:
|
---|
60 | Serial.println("error opening test.txt");
|
---|
61 | }
|
---|
62 |
|
---|
63 | // re-open the file for reading:
|
---|
64 | myFile = SD.open("test.txt");
|
---|
65 | if (myFile) {
|
---|
66 | Serial.println("test.txt:");
|
---|
67 |
|
---|
68 | // read from the file until there's nothing else in it:
|
---|
69 | while (myFile.available()) {
|
---|
70 | Serial.write(myFile.read());
|
---|
71 | }
|
---|
72 | // close the file:
|
---|
73 | myFile.close();
|
---|
74 | } else {
|
---|
75 | // if the file didn't open, print an error:
|
---|
76 | Serial.println("error opening test.txt");
|
---|
77 | }
|
---|
78 | }
|
---|
79 |
|
---|
80 | void loop()
|
---|
81 | {
|
---|
82 | // nothing happens after setup
|
---|
83 | }
|
---|
84 |
|
---|
85 |
|
---|