0

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

这是我的代码:

#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打印语句。其余的都是一样的。我显然已经安装了 SD 卡。

有人知道吗?

4

1 回答 1

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");

它奏效了。

于 2017-08-02T09:47:47.227 回答