ReadWrite.ino 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 (for MKRZero SD: SDCARD_SS_PIN)
  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. #include <SPI.h>
  17. #include <SD.h>
  18. File myFile;
  19. void setup() {
  20. // Open serial communications and wait for port to open:
  21. Serial.begin(9600);
  22. while (!Serial) {
  23. ; // wait for serial port to connect. Needed for native USB port only
  24. }
  25. Serial.print("Initializing SD card...");
  26. if (!SD.begin(4)) {
  27. Serial.println("initialization failed!");
  28. while (1);
  29. }
  30. Serial.println("initialization done.");
  31. // open the file. note that only one file can be open at a time,
  32. // so you have to close this one before opening another.
  33. myFile = SD.open("test.txt", FILE_WRITE);
  34. // if the file opened okay, write to it:
  35. if (myFile) {
  36. Serial.print("Writing to test.txt...");
  37. myFile.println("testing 1, 2, 3.");
  38. // close the file:
  39. myFile.close();
  40. Serial.println("done.");
  41. } else {
  42. // if the file didn't open, print an error:
  43. Serial.println("error opening test.txt");
  44. }
  45. // re-open the file for reading:
  46. myFile = SD.open("test.txt");
  47. if (myFile) {
  48. Serial.println("test.txt:");
  49. // read from the file until there's nothing else in it:
  50. while (myFile.available()) {
  51. Serial.write(myFile.read());
  52. }
  53. // close the file:
  54. myFile.close();
  55. } else {
  56. // if the file didn't open, print an error:
  57. Serial.println("error opening test.txt");
  58. }
  59. }
  60. void loop() {
  61. // nothing happens after setup
  62. }