Mar*_*min 2 string arduino sd-card
I'm trying to read a text file in an Arduino SD card reader and copy its text into a string variable, but the function .read always returns -1. How can I solve this problem?
Here's the code:
#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
}
Run Code Online (Sandbox Code Playgroud)
我知道它.read()
返回一个整数数组,但我不知道如何分别访问它们。
经过进一步研究,我了解了.read
工作原理:它在推进光标时读取其光标指向的字符。
因此,为了读取整个文件,您必须删除该Serial.write
部分并将字符转换为char
:
String finalString = "";
while (mappa.available())
{
finalString += (char)mappa.read();
}
Run Code Online (Sandbox Code Playgroud)