如何在安装在Arduino Yun上的SD卡上创建文本文件?

时间:2017-07-26 17:11:32

标签: arduino text-files sd-card arduino-yun

就像标题所说,我正在尝试从我的Arduino草图创建一个文本文件。我的Arduino通过以太网线连接到我的电脑,但SD卡安装在Arduino上,所以我假设与计算机(USB或以太网)的连接无关紧要。我在official Arduino documentation上找到的内容似乎很简单,但我无法创建该文件。

这是我的代码:

#include <Bridge.h>
#include <Console.h>
#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Start using the Bridge.
  Bridge.begin();
  // To output on the Serial Monitor
  Console.begin();
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  if (!SD.begin(4)) {
    Console.println("initialization failed!");
    //return;
  }
  Console.println("initialization done.");
  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    Console.print("Writing to test.txt...\n");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Console.print("done.\n");
  } else {
    // if the file didn't open, print an error:
    Console.print("error opening test.txt\n");
  }
  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Console.print("test.txt: ");
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Console.print(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Console.print("error opening test.txt\n");
  }
}

void loop() {
  Console.print("Loop\n");
  delay(1000);
}

这是输出:

initialization failed!
initialization done.
error opening test.txterror opening test.txt
Loop
[...]
Loop

与我上面提供的链接相反,我使用Console而不是Serial作为print语句。其余的都是一样的。我显然已安装了SD卡。

任何人都知道吗?

1 个答案:

答案 0 :(得分:0)

正如gre_gor在评论中所建议的那样,我特意为Arduino Yun提供了本教程:https://www.arduino.cc/en/Tutorial/YunDatalogger。我不得不改变SD卡上文件的路径(我的是'/mnt/sda1/myFile.txt'),我不得不在设置功能中删除这两行:

// Delete these two lines:
while (!SerialUSB); // wait for Serial port to connect.
SerialUSB.println("Filesystem datalogger\n");

它有效。