【问题标题】:From .txt file in sd card to string variable in Arduino从 sd 卡中的 .txt 文件到 Arduino 中的字符串变量
【发布时间】:2023-03-16 13:34:01
【问题描述】:

我正在尝试在 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()返回一个整数数组,但我不知道如何分别访问它们。

【问题讨论】:

    标签: string arduino sd-card


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      相关资源
      最近更新 更多