1

我正在做一个从 SD 卡读取“data.txt”中的“当前”的项目。目标是逐行阅读并输入到我的int“TargetCur”。

代码结构:
1. 从 SDcard 打开“data.txt”
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//
}
4

2 回答 2

0

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

int index = 0;
char stringArray[MAX_LINE_LEN];

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

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

于 2018-06-19T19:01:56.783 回答
0

To read line by line, create a String readLine () function that reads char by char until the end of the line.

于 2018-06-18T18:12:44.897 回答