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– brtiberio2016年06月09日 08:54:46 +00:00Commented Jun 9, 2016 at 8:54
-
Are all your CSV values all numeric, or do you have textual data in there as well?Majenko– Majenko2016年06月09日 11:24:33 +00:00Commented Jun 9, 2016 at 11:24
1 Answer 1
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.