1 | /*
|
---|
2 | SD card basic file example
|
---|
3 |
|
---|
4 | This example shows how to create and destroy 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 | #include <SPI.h>
|
---|
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, 14 on the Leonardo) must be left as an output
|
---|
38 | // or the SD library functions will not work.
|
---|
39 |
|
---|
40 | if (!SD.begin(4)) {
|
---|
41 | Serial.println("initialization failed!");
|
---|
42 | return;
|
---|
43 | }
|
---|
44 | Serial.println("initialization done.");
|
---|
45 |
|
---|
46 | if (SD.exists("example.txt")) {
|
---|
47 | Serial.println("example.txt exists.");
|
---|
48 | }
|
---|
49 | else {
|
---|
50 | Serial.println("example.txt doesn't exist.");
|
---|
51 | }
|
---|
52 |
|
---|
53 | // open a new file and immediately close it:
|
---|
54 | Serial.println("Creating example.txt...");
|
---|
55 | myFile = SD.open("example.txt", FILE_WRITE);
|
---|
56 | myFile.close();
|
---|
57 |
|
---|
58 | // Check to see if the file exists:
|
---|
59 | if (SD.exists("example.txt")) {
|
---|
60 | Serial.println("example.txt exists.");
|
---|
61 | }
|
---|
62 | else {
|
---|
63 | Serial.println("example.txt doesn't exist.");
|
---|
64 | }
|
---|
65 |
|
---|
66 | // delete the file:
|
---|
67 | Serial.println("Removing example.txt...");
|
---|
68 | SD.remove("example.txt");
|
---|
69 |
|
---|
70 | if (SD.exists("example.txt")) {
|
---|
71 | Serial.println("example.txt exists.");
|
---|
72 | }
|
---|
73 | else {
|
---|
74 | Serial.println("example.txt doesn't exist.");
|
---|
75 | }
|
---|
76 | }
|
---|
77 |
|
---|
78 | void loop()
|
---|
79 | {
|
---|
80 | // nothing happens after setup finishes.
|
---|
81 | }
|
---|
82 |
|
---|
83 |
|
---|
84 |
|
---|