You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.0KB

  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. ** CS - pin 4
  10. created Nov 2010
  11. by David A. Mellis
  12. modified 9 Apr 2012
  13. by Tom Igoe
  14. This example code is in the public domain.
  15. */
  16. #define SD_CS_PIN SS
  17. #include <SPI.h>
  18. //#include <SD.h>
  19. #include <SdFat.h>
  20. SdFat SD;
  21. File myFile;
  22. void setup()
  23. {
  24. // Open serial communications and wait for port to open:
  25. Serial.begin(9600);
  26. while (!Serial) {
  27. ; // wait for serial port to connect. Needed for Leonardo only
  28. }
  29. Serial.print("Initializing SD card...");
  30. // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  31. // Note that even if it's not used as the CS pin, the hardware SS pin
  32. // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  33. // or the SD library functions will not work.
  34. pinMode(10, OUTPUT);
  35. if (!SD.begin(SD_CS_PIN)) {
  36. Serial.println("initialization failed!");
  37. return;
  38. }
  39. Serial.println("initialization done.");
  40. // open the file. note that only one file can be open at a time,
  41. // so you have to close this one before opening another.
  42. myFile = SD.open("test.txt", FILE_WRITE);
  43. // if the file opened okay, write to it:
  44. if (myFile) {
  45. Serial.print("Writing to test.txt...");
  46. myFile.println("testing 1, 2, 3.");
  47. // close the file:
  48. myFile.close();
  49. Serial.println("done.");
  50. } else {
  51. // if the file didn't open, print an error:
  52. Serial.println("error opening test.txt");
  53. }
  54. // re-open the file for reading:
  55. myFile = SD.open("test.txt");
  56. if (myFile) {
  57. Serial.println("test.txt:");
  58. // read from the file until there's nothing else in it:
  59. while (myFile.available()) {
  60. Serial.write(myFile.read());
  61. }
  62. // close the file:
  63. myFile.close();
  64. } else {
  65. // if the file didn't open, print an error:
  66. Serial.println("error opening test.txt");
  67. }
  68. }
  69. void loop()
  70. {
  71. // nothing happens after setup
  72. }