ReadWrite.ino 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. SD card read/write
  3. This example shows how to read and write data to and from an SD card file
  4. The circuit:
  5. * SD card attached to SPI bus as follows:
  6. ** MOSI - pin 11
  7. ** MISO - pin 12
  8. ** CLK - pin 13
  9. created Nov 2010
  10. by David A. Mellis
  11. modified 9 Apr 2012
  12. by Tom Igoe
  13. This example code is in the public domain.
  14. */
  15. #include <SPI.h>
  16. //#include <SD.h>
  17. #include "SdFat.h"
  18. SdFat SD;
  19. #define SD_CS_PIN SS
  20. File myFile;
  21. void setup() {
  22. // Open serial communications and wait for port to open:
  23. Serial.begin(9600);
  24. while (!Serial) {
  25. ; // wait for serial port to connect. Needed for native USB port only
  26. }
  27. Serial.print("Initializing SD card...");
  28. if (!SD.begin(SD_CS_PIN)) {
  29. Serial.println("initialization failed!");
  30. return;
  31. }
  32. Serial.println("initialization done.");
  33. // open the file. note that only one file can be open at a time,
  34. // so you have to close this one before opening another.
  35. myFile = SD.open("test.txt", FILE_WRITE);
  36. // if the file opened okay, write to it:
  37. if (myFile) {
  38. Serial.print("Writing to test.txt...");
  39. myFile.println("testing 1, 2, 3.");
  40. // close the file:
  41. myFile.close();
  42. Serial.println("done.");
  43. } else {
  44. // if the file didn't open, print an error:
  45. Serial.println("error opening test.txt");
  46. }
  47. // re-open the file for reading:
  48. myFile = SD.open("test.txt");
  49. if (myFile) {
  50. Serial.println("test.txt:");
  51. // read from the file until there's nothing else in it:
  52. while (myFile.available()) {
  53. Serial.write(myFile.read());
  54. }
  55. // close the file:
  56. myFile.close();
  57. } else {
  58. // if the file didn't open, print an error:
  59. Serial.println("error opening test.txt");
  60. }
  61. }
  62. void loop() {
  63. // nothing happens after setup
  64. }