Advertisement
RuiViana

SD_RW

Jun 27th, 2016
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  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.   // Open serial communications and wait for port to open:
  27.   Serial.begin(9600);
  28.   while (!Serial) {
  29.     ; // wait for serial port to connect. Needed for native USB port only
  30.   }
  31.  
  32.  
  33.   Serial.print("Initializing SD card...");
  34.  
  35.   if (!SD.begin(4)) {
  36.     Serial.println("initialization failed!");
  37.     return;
  38.   }
  39.   Serial.println("initialization done.");
  40.  
  41.   // open the file. note that only one file can be open at a time,
  42.   // so you have to close this one before opening another.
  43.   myFile = SD.open("test.txt", FILE_WRITE);
  44.  
  45.   // if the file opened okay, write to it:
  46.   if (myFile) {
  47.     Serial.print("Writing to test.txt...");
  48.     myFile.println("testing 1, 2, 3.");
  49.     // close the file:
  50.     myFile.close();
  51.     Serial.println("done.");
  52.   } else {
  53.     // if the file didn't open, print an error:
  54.     Serial.println("error opening test.txt");
  55.   }
  56.  
  57.   // re-open the file for reading:
  58.   myFile = SD.open("test.txt");
  59.   if (myFile) {
  60.     Serial.println("test.txt:");
  61.  
  62.     // read from the file until there's nothing else in it:
  63.     while (myFile.available()) {
  64.       Serial.write(myFile.read());
  65.     }
  66.     // close the file:
  67.     myFile.close();
  68.   } else {
  69.     // if the file didn't open, print an error:
  70.     Serial.println("error opening test.txt");
  71.   }
  72. }
  73.  
  74. void loop() {
  75.   // nothing happens after setup
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement