从SD卡中的.txt文件到Arduino中的字符串变量

3

我尝试在Arduino SD卡读卡器中读取文本文件,并将其文本复制到一个字符串变量中,但是函数.read始终返回-1。我该如何解决这个问题?

以下是代码:

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

File mappa;
String text;

void setup() {
Serial.begin(9600);
while (!Serial) {
  ;
}
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
  Serial.println("initialization failed!");
  return;
}
Serial.println("initialization done.");

// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
mappa = SD.open("map.txt");

// if the file opened okay, write to it:
if (mappa) {
  Serial.println("File aperto");
} else {
  // if the file didn't open, print an error:
  Serial.println("error opening map.txt");
}
Serial.println("map.txt:");

// read from the file until there's nothing else in it:
while (mappa.available()) {
  Serial.write(mappa.read());
 // text = parseInt(mappa.read());
}
Serial.println(text);
  // close the file:
  mappa.close();  
}
void loop() {
  // nothing happens after setup
}

我知道.read()返回一个整数数组,但我不知道如何单独访问它们。
1个回答

8
经过进一步研究,我了解到 .read 的工作原理:它读取光标所指的字符,并将光标向前移动。
因此,为了读取整个文件,您需要删除 Serial.write 部分并将字符转换为 char
String finalString = "";
while (mappa.available())
{
  finalString += (char)mappa.read();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接