Arduino逐行读取SD文件C++

Arduino reading SD file line by line C++

我正在尝试从连接到我的 Arduino MEGA 的 SD 卡中逐行读取文本文件 "Print1.txt"。到目前为止,我有以下代码:

#include <SD.h>
#include <SPI.h>
int linenumber = 0;
const int buffer_size = 54;
int bufferposition;
File printFile;
char character;
char Buffer[buffer_size];
boolean SDfound;


void setup()
{
  Serial.begin(9600);
  bufferposition = 0;
}

void loop() 
{
  if (SDfound == 0)
  {
    if (!SD.begin(53)) 
    {
      Serial.print("The SD card cannot be found");
      while(1);
    }
  }
  SDfound = 1;
  printFile = SD.open("Part1.txt");


  if (!printFile)
  {
    Serial.print("The text file cannot be opened");
    while(1);
  }

  while (printFile.available() > 0)
  {
    character = printFile.read();
    if (bufferposition < buffer_size - 1)
    {
      Buffer[bufferposition++] = character;
      if ((character == '\n'))
      {
        //new line function recognises a new line and moves on 
        Buffer[bufferposition] = 0;
        //do some action here
        bufferposition = 0;
      }
    }

  }
  Serial.println(Buffer);
  delay(1000);
}

函数returns只重复文本文件的第一行。

我的问题

如何更改函数以读取一行文本(希望在该行上执行操作,如“//do some action”所示),然后移至后续的下一行循环,重复这个直到到达文件末尾?

希望这是有道理的。

实际上,您的代码 returns 只是文本文件的 最后 行,因为它仅在读取整个数据后才打印缓冲区。代码重复打印,因为文件是在循环函数内打开的。通常,读取文件应该在只执行一次的 setup 函数中完成。

您可以读取直到找到定界符并将其分配给 String 缓冲区,而不是逐个字符地读取数据到缓冲区中。这种方法使您的代码简单。我的修复代码的建议就在下面:

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

File printFile;
String buffer;
boolean SDfound;


void setup() {
  Serial.begin(9600);

  if (SDfound == 0) {
    if (!SD.begin(53)) {
      Serial.print("The SD card cannot be found");
      while(1);
    }
  }
  SDfound = 1;
  printFile = SD.open("Part1.txt");

  if (!printFile) {
    Serial.print("The text file cannot be opened");
    while(1);
  }

  while (printFile.available()) {
    buffer = printFile.readStringUntil('\n');
    Serial.println(buffer); //Printing for debugging purpose         
    //do some action here
  }

  printFile.close();
}

void loop() {
   //empty
}