1

I'm working on a project to read "current" in "data.txt" from SDcard. Goal is to read it line by line and input to my int "TargetCur".

Code structure:
1. Open "data.txt" from SDcard
2. Read first line data
3. Input read data into int "TargetCur"
4. Arduino perform action
5. Once action above completed, read second line data from "data.txt"
6. Repeat step 3 to 5 above

"data.txt" look like this:
Current
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//
}
kin
  • 67
  • 4
  • 12

1 Answers1

1

You can always create your own function that suits you needs. If you know the max line size than a statically declared char[] will work best like so.

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;
    }
}

If you don't know the max line size that this becomes a bit harder and you need to use malloc() to dynamically grow the size of the buffer.

Stefan Bossbaly
  • 6,682
  • 9
  • 53
  • 82
  • incompatible types in assignment of 'int' to 'char [1]' (i declared `next` outside the while statement as an array with 1 position). – tony gil Jun 03 '19 at 17:29
  • 1
    myFile.read() returns an `int` since. Once you ensure the return is not -1 then you can cast to to a char. I have updated the code. – Stefan Bossbaly Jun 03 '19 at 17:40