|
| 1 | +#include <SD.h> |
| 2 | +const int chipSelect = 10; |
| 3 | +File myFile; |
| 4 | + |
| 5 | +void setup() { |
| 6 | + |
| 7 | + // Open serial communications and wait for port to open: |
| 8 | + Serial.begin(9600); |
| 9 | + |
| 10 | + // wait for Serial Monitor to connect. Needed for native USB port boards only: |
| 11 | + while (!Serial); |
| 12 | + |
| 13 | + |
| 14 | + check_and_create_file(); |
| 15 | + write_text(); |
| 16 | +} |
| 17 | + |
| 18 | +void loop() { |
| 19 | + |
| 20 | + // nothing happens after setup finishes. |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +void check_and_create_file() |
| 25 | +{ |
| 26 | + Serial.print("Initializing SD card..."); |
| 27 | + |
| 28 | + /*Check if the SD card exist or not*/ |
| 29 | + if (!SD.begin(chipSelect)) { |
| 30 | + Serial.println("initialization failed!"); |
| 31 | + while (1); |
| 32 | + } |
| 33 | + |
| 34 | + Serial.println("initialization done."); |
| 35 | + |
| 36 | + if (SD.exists("data_log.txt")) |
| 37 | + Serial.println("data_log.txt exists."); |
| 38 | + |
| 39 | + else |
| 40 | + { |
| 41 | + Serial.println("data_log.txt doesn't exist."); |
| 42 | + |
| 43 | + |
| 44 | + /* open a new file and immediately close it: |
| 45 | + this will create a new file */ |
| 46 | + |
| 47 | + Serial.println("Creating data_log.txt..."); |
| 48 | + |
| 49 | + myFile = SD.open("data_log.txt", FILE_WRITE); |
| 50 | + |
| 51 | + myFile.close(); |
| 52 | + |
| 53 | + /* Now Chec agin if the file exists in |
| 54 | + the SD card or not */ |
| 55 | + |
| 56 | + if (SD.exists("data_log.txt")) |
| 57 | + Serial.println("data_log.txt exists."); |
| 58 | + |
| 59 | + else |
| 60 | + Serial.println("data_log.txt doesn't exist."); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | + |
| 65 | +void write_text() |
| 66 | +{ |
| 67 | + myFile = SD.open("data_log.txt", FILE_WRITE); |
| 68 | + |
| 69 | + // if the file opened okay, write to it: |
| 70 | + if (myFile) { |
| 71 | + Serial.print("Writing to data_log.txt..."); |
| 72 | + myFile.println("testing 1, 2, 3."); |
| 73 | + // close the file: |
| 74 | + myFile.close(); |
| 75 | + Serial.println("done."); |
| 76 | + } else { |
| 77 | + // if the file didn't open, print an error: |
| 78 | + Serial.println("error opening data_log.txt"); |
| 79 | + } |
| 80 | + |
| 81 | + // re-open the file for reading: |
| 82 | + myFile = SD.open("data_log.txt"); |
| 83 | + if (myFile) { |
| 84 | + Serial.println("data_log.txt:"); |
| 85 | + |
| 86 | + // read from the file until there's nothing else in it: |
| 87 | + while (myFile.available()) { |
| 88 | + Serial.write(myFile.read()); |
| 89 | + } |
| 90 | + // close the file: |
| 91 | + myFile.close(); |
| 92 | + } else { |
| 93 | + // if the file didn't open, print an error: |
| 94 | + Serial.println("error opening data_log.txt"); |
| 95 | + } |
| 96 | +} |
0 commit comments