gpt4 book ai didi

c++ - Arduino逐行读取SD文件C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:00 26 4
gpt4 key购买 nike

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

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

我的问题

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

希望这是有道理的。

最佳答案

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

关于c++ - Arduino逐行读取SD文件C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com