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.

fgets.ino 2.2KB

10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
8 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Demo of fgets function to read lines from a file.
  2. #include <SPI.h>
  3. #include "SdFat.h"
  4. #include "sdios.h"
  5. // SD chip select pin
  6. const uint8_t chipSelect = SS;
  7. SdFat sd;
  8. // print stream
  9. ArduinoOutStream cout(Serial);
  10. //------------------------------------------------------------------------------
  11. // store error strings in flash memory
  12. #define error(s) sd.errorHalt(F(s))
  13. //------------------------------------------------------------------------------
  14. void demoFgets() {
  15. char line[25];
  16. int n;
  17. // open test file
  18. SdFile rdfile("fgets.txt", O_RDONLY);
  19. // check for open error
  20. if (!rdfile.isOpen()) {
  21. error("demoFgets");
  22. }
  23. cout << endl << F(
  24. "Lines with '>' end with a '\\n' character\n"
  25. "Lines with '#' do not end with a '\\n' character\n"
  26. "\n");
  27. // read lines from the file
  28. while ((n = rdfile.fgets(line, sizeof(line))) > 0) {
  29. if (line[n - 1] == '\n') {
  30. cout << '>' << line;
  31. } else {
  32. cout << '#' << line << endl;
  33. }
  34. }
  35. }
  36. //------------------------------------------------------------------------------
  37. void makeTestFile() {
  38. // create or open test file
  39. SdFile wrfile("fgets.txt", O_WRONLY | O_CREAT | O_TRUNC);
  40. // check for open error
  41. if (!wrfile.isOpen()) {
  42. error("MakeTestFile");
  43. }
  44. // write test file
  45. wrfile.print(F(
  46. "Line with CRLF\r\n"
  47. "Line with only LF\n"
  48. "Long line that will require an extra read\n"
  49. "\n" // empty line
  50. "Line at EOF without NL"
  51. ));
  52. wrfile.close();
  53. }
  54. //------------------------------------------------------------------------------
  55. void setup(void) {
  56. Serial.begin(9600);
  57. // Wait for USB Serial
  58. while (!Serial) {
  59. SysCall::yield();
  60. }
  61. cout << F("Type any character to start\n");
  62. while (!Serial.available()) {
  63. SysCall::yield();
  64. }
  65. delay(400); // catch Due reset problem
  66. // Initialize at the highest speed supported by the board that is
  67. // not over 50 MHz. Try a lower speed if SPI errors occur.
  68. if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
  69. sd.initErrorHalt();
  70. }
  71. makeTestFile();
  72. demoFgets();
  73. cout << F("\nDone\n");
  74. }
  75. void loop(void) {}