3

I'm fairly new to arduino programming and C/C++. I would like to read a .csv file element wise, and send each element via. a nRF24L01 tranceiver to a raspberry pi. Right now I'm able to read the .csv file with Serial.write(<file>.read()). I was wondering if there's a way to read each element one at a time, if so how would i do that?

My thoughts (Pseudo code-ish):

loop through every element in .csv file {
    save the current element to X.
    send X to raspberry pi (I already have a function for sending)
}

I hope someone can help. Thanks in advance.

  • Take a look at this post. Since the file is csv, you can construct a similar approach using a sscanf on each line you read. – brtiberio Jun 9 '16 at 8:54
  • Are all your CSV values all numeric, or do you have textual data in there as well? – Majenko Jun 9 '16 at 11:24
4

The read() method works character-wise, not element-wise. Then you have to rethink your algorithm to loop over characters:

  • store each character in a buffer
  • send the whole buffer (i.e. a single element) when you see a delimiter

Example:

const size_t BUFFER_SZ = ...;
char buffer[BUFFER_SZ];
size_t pos = 0;    // current write position in buffer
int c;

// While we can read a character:
while ((c = <file>.read()) != -1) {

    // If we get a delimiter, then we have a complete element.
    if (c == ',' || c == '\n') {
        buffer[pos] = '\0';         // terminate the string
        raspberry.println(buffer);  // send to the RPi
        pos = 0;                    // ready for next element
    }

    // Otherwise, store the character in the buffer.
    else if (pos < BUFFER_SZ-1) {
        buffer[pos++] = c;
    }
}

Here the buffer is sent as a string. If you want to parse it into a number, you can use sscanf.

This code assumes Unix text-file conventions, i.e. each line of the file (including the last one) being terminated by an LF character. You may have to adapt if your file is different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.