NonBlockingWrite.ino 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. Non-blocking Write
  3. This example demonstrates how to perform non-blocking writes
  4. to a file on a SD card. The file will contain the current millis()
  5. value every 10ms. If the SD card is busy, the data will be buffered
  6. in order to not block the sketch.
  7. NOTE: myFile.availableForWrite() will automatically sync the
  8. file contents as needed. You may lose some unsynced data
  9. still if myFile.sync() or myFile.close() is not called.
  10. The circuit:
  11. - Arduino MKR Zero board
  12. - micro SD card attached
  13. This example code is in the public domain.
  14. */
  15. #include <SD.h>
  16. // file name to use for writing
  17. const char filename[] = "demo.txt";
  18. // File object to represent file
  19. File txtFile;
  20. // string to buffer output
  21. String buffer;
  22. unsigned long lastMillis = 0;
  23. void setup() {
  24. Serial.begin(9600);
  25. while (!Serial);
  26. // reserve 1kB for String used as a buffer
  27. buffer.reserve(1024);
  28. // set LED pin to output, used to blink when writing
  29. pinMode(LED_BUILTIN, OUTPUT);
  30. // init the SD card
  31. if (!SD.begin()) {
  32. Serial.println("Card failed, or not present");
  33. // don't do anything more:
  34. while (1);
  35. }
  36. // If you want to start from an empty file,
  37. // uncomment the next line:
  38. // SD.remove(filename);
  39. // try to open the file for writing
  40. txtFile = SD.open(filename, FILE_WRITE);
  41. if (!txtFile) {
  42. Serial.print("error opening ");
  43. Serial.println(filename);
  44. while (1);
  45. }
  46. // add some new lines to start
  47. txtFile.println();
  48. txtFile.println("Hello World!");
  49. }
  50. void loop() {
  51. // check if it's been over 10 ms since the last line added
  52. unsigned long now = millis();
  53. if ((now - lastMillis) >= 10) {
  54. // add a new line to the buffer
  55. buffer += "Hello ";
  56. buffer += now;
  57. buffer += "\r\n";
  58. lastMillis = now;
  59. }
  60. // check if the SD card is available to write data without blocking
  61. // and if the buffered data is enough for the full chunk size
  62. unsigned int chunkSize = txtFile.availableForWrite();
  63. if (chunkSize && buffer.length() >= chunkSize) {
  64. // write to file and blink LED
  65. digitalWrite(LED_BUILTIN, HIGH);
  66. txtFile.write(buffer.c_str(), chunkSize);
  67. digitalWrite(LED_BUILTIN, LOW);
  68. // remove written data from buffer
  69. buffer.remove(0, chunkSize);
  70. }
  71. }