【问题标题】:Arduino reading SD file line by line C++Arduino逐行读取SD文件C++
【发布时间】:2016-05-30 21:20:37
【问题描述】:

我正在尝试从连接到我的 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);
}

该函数只重复返回文本文件的第一行。

我的问题

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

希望这是有道理的。

【问题讨论】:

  • 为什么不在Buffer[bufferposition] = 0这一行之前使用Buffer的内容执行操作?
  • @ArtonDorneles 您认为这种变化的优点是什么?我认为在终止字符串之前对Buffer 执行一些操作不是一个好主意。
  • 我不认为打开文件而不关闭它是好的。
  • 抱歉,我想说之后 Buffer[bufferposition] = 0。此时,您的缓冲区中有一个有效的字符串,您可以使用它来触发任何操作。但是,请注意您将 \n 字符作为最后一个字符。在处理线路时,这可能是一个问题。要删除它,只需将Buffer[bufferposition] = 0; 替换为Buffer[bufferposition-1] = 0;。在处理命令时保持文件打开没有任何问题。读取全部数据后可以关闭它。
  • @ArtonDorneles 感谢您对“\n”字符的帮助。但是我的问题不是在行上执行操作,而是读取文本文件的下一行以进行进一步操作的方法。例如:第 1 行:G1 X19.500 Y9.000 第 2 行:G1 X-19.500 Y-9.000 第 3 行:等等....如何读取下一行,然后是连续行,直到 EOF。有任何想法吗?提前谢谢你。

标签: c++ arduino sd-card readfile line-by-line


【解决方案1】:

实际上,您的代码仅返回文本文件的 last 行,因为它仅在读取整个数据后才打印缓冲区。代码重复打印,因为文件是在循环函数中打开的。通常,读取文件应该在只执行一次的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
}

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 2012-06-13
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多