Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <SPI.h>
  2. #include <SD.h>
  3.  
  4.  
  5. #define SD_CS 4
  6.  
  7.  
  8. File myFile;
  9.  
  10. void setup() {
  11.   // Open serial communications and wait for port to open:
  12.   Serial.begin(9600);
  13.   while (!Serial) {
  14.     ; // wait for serial port to connect. Needed for native USB port only
  15.   }
  16.  
  17.  
  18.   Serial.print("Initializing SD card...");
  19.  
  20.   if (!SD.begin(SD_CS)) {
  21.     Serial.println("initialization failed!");
  22.     return;
  23.   }
  24.   Serial.println("initialization done.");
  25.  
  26.   // open the file. note that only one file can be open at a time,
  27.   // so you have to close this one before opening another.
  28.   myFile = SD.open("test.txt", FILE_WRITE);
  29.  
  30.   // if the file opened okay, write to it:
  31.   if (myFile) {
  32.     Serial.print("Writing to test.txt...");
  33.     myFile.println("testing 1, 2, 3.");
  34.     // close the file:
  35.     myFile.close();
  36.     Serial.println("done.");
  37.   } else {
  38.     // if the file didn't open, print an error:
  39.     Serial.println("error opening test.txt");
  40.   }
  41.  
  42.   // re-open the file for reading:
  43.   myFile = SD.open("test.txt");
  44.   if (myFile) {
  45.     Serial.println("test.txt:");
  46.  
  47.     // read from the file until there's nothing else in it:
  48.     while (myFile.available()) {
  49.       Serial.write(myFile.read());
  50.     }
  51.     // close the file:
  52.     myFile.close();
  53.   } else {
  54.     // if the file didn't open, print an error:
  55.     Serial.println("error opening test.txt");
  56.   }
  57. }
  58.  
  59. void loop() {
  60.   // nothing happens after setup
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement