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

时间:2018-07-12 15:43:03

标签: string arduino sd-card

我正在尝试在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 个答案:

答案 0 :(得分:1)

经过进一步研究,我了解了.read的工作原理:它在前进光标时读取光标指向的字符。

因此,为了读取整个文件,您必须删除Serial.write部分并将字符转换为char

string finalString="";
while (mappa.available())
{
finalString+=(char)mappa.read();
}