Arduino逐行读取SD文件

Jul*_*Das 6 c++ arduino sd-card readfile line-by-line

我试图从连接到我的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);
}
Run Code Online (Sandbox Code Playgroud)

该函数仅重复返回文本文件的第一行.

我的问题

如何更改函数以读取一行文本(希望在这样的行上执行操作,显示为"//执行某些操作")然后移动到后续循环中的下一行,重复此操作直到文件的结尾已经到了?

希望这是有道理的.

Art*_*les 10

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

您可以读取而不是通过char将数据char读入缓冲区,直到找到分隔符并将其分配给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
}
Run Code Online (Sandbox Code Playgroud)