TFCard.ino 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. *******************************************************************************
  3. * Copyright (c) 2022 by M5Stack
  4. * Equipped with M5Core sample source code
  5. * 配套 M5Core 示例源代码
  6. * Visit for more information: https://docs.m5stack.com/en/core/gray
  7. * 获取更多资料请访问: https://docs.m5stack.com/zh_CN/core/gray
  8. *
  9. * Describe: TF Card. TF卡
  10. * Date: 2022/3/25
  11. *******************************************************************************
  12. In this example, we will detect the existence of a file and perform read and
  13. write operations on it
  14. 在这个示例中,我们将会检测某文件是否存在,并进行读写文件操作
  15. */
  16. #include <M5Stack.h>
  17. void setup() {
  18. M5.begin();
  19. if (!SD.begin()) { // Initialize the SD card. 初始化SD卡
  20. M5.Lcd.println(
  21. "Card failed, or not present"); // Print a message if the SD card
  22. // initialization fails or if the
  23. // SD card does not exist
  24. // 如果SD卡初始化失败或者SD卡不存在,则打印消息
  25. while (1)
  26. ;
  27. }
  28. M5.Lcd.println("TF card initialized.");
  29. if (SD.exists("/hello.txt")) { // Check if the "/hello.txt" file
  30. // exists.查看是否存在"/hello.txt"文件
  31. M5.Lcd.println("hello.txt exists.");
  32. } else {
  33. M5.Lcd.println("hello.txt doesn't exist.");
  34. }
  35. M5.Lcd.println("Creating hello.txt");
  36. File myFile = SD.open("/hello.txt",
  37. FILE_WRITE); // Create a new file "/hello.txt".
  38. // 创建一个新文件"/hello.txt"
  39. if (myFile) { // If the file is open, then write to it.
  40. // 如果文件打开,则进行写入操作
  41. M5.Lcd.println("Writing to test.txt...");
  42. myFile.println("SD test.");
  43. myFile.close(); // Close the file. 关闭文件
  44. M5.Lcd.println("done.");
  45. } else {
  46. M5.Lcd.println("error opening test.txt");
  47. }
  48. delay(500);
  49. myFile = SD.open("/hello.txt",
  50. FILE_READ); // Open the file "/hello.txt" in read mode.
  51. // 以读取模式打开文件"/hello.txt"
  52. if (myFile) {
  53. M5.Lcd.println("/hello.txt Content:");
  54. // Read the data from the file and print it until the reading is
  55. // complete. 从文件里读取数据并打印到串口,直到读取完成.
  56. while (myFile.available()) {
  57. M5.Lcd.write(myFile.read());
  58. }
  59. myFile.close();
  60. } else {
  61. M5.Lcd.println("error opening /hello.txt"); // If the file is not open.
  62. // 如果文件没有打开
  63. }
  64. }
  65. void loop() {}