Arduino:如何逐行读取SD卡文本文件

时间:2018-06-18 09:24:57

标签: arduino android-sdcard sd-card line-by-line

我正在开展一个项目,以阅读"当前" in" data.txt"来自SDcard。目标是逐行阅读并输入我的int" TargetCur"。

代码结构:
1.打开" data.txt"来自SDcard
2.读取第一行数据
3.将读取数据输入到int" TargetCur"
4. Arduino执行行动
5.完成上述操作后,从" data.txt"中读取第二行数据。
6.重复上面的步骤3到5

"的 data.txt中"看起来像这样:
目前的 2.179
3.179
2.659
2.859

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

File Data;

// Declare the pins used:
int TargetCur = 0;

void setup() {    
    Serial.begin(9600);     // initialize serial communications at 9600 bps:
    TCCR1B = TCCR1B & B11111000 | B00000001;

    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
    }
    myFile = SD.open ("data.txt", FILE_WRITE);
}

void loop() {
    TargetCur = Serial.write(myFile.read());
    //perform action//
}

2 个答案:

答案 0 :(得分:0)

要逐行读取,请创建一个 String readLine()函数,该函数按char读取char,直到该行结束。

答案 1 :(得分:0)

您始终可以创建适合自己需要的功能。如果您知道最大行大小,则比静态声明的char[]效果最好。

int index = 0;
char stringArray[MAX_LINE_LEN];

while ((char next = myFile.read()) != -1)
{
    if (next == '\n')
    {
        stringArray[index] = '\0';
        /* Do something with char array */
        index = 0;
    }
    else
    {
        stringArray[index] = next;
        index += 1;
    }
}

如果您不知道最大行大小,这会变得有些困难,您需要使用malloc()动态增加缓冲区的大小。