I am trying to read a text file "Print1.txt", line by line, from an SD card attached to my Arduino MEGA. So far I have the following code:
#include <SD.h>
#include <SPI.h>
int linenumber = 0;
const int buffer_size = 54;
int bufferposition;
File printFile;
char character;
char Buffer[buffer_size];
boolean SDfound;
void setup()
{
Serial.begin(9600);
bufferposition = 0;
}
void loop()
{
if (SDfound == 0)
{
if (!SD.begin(53))
{
Serial.print("The SD card cannot be found");
while(1);
}
}
SDfound = 1;
printFile = SD.open("Part1.txt");
if (!printFile)
{
Serial.print("The text file cannot be opened");
while(1);
}
while (printFile.available() > 0)
{
character = printFile.read();
if (bufferposition < buffer_size - 1)
{
Buffer[bufferposition++] = character;
if ((character == '\n'))
{
//new line function recognises a new line and moves on
Buffer[bufferposition] = 0;
//do some action here
bufferposition = 0;
}
}
}
Serial.println(Buffer);
delay(1000);
}
The function returns only the first line of the text file repeatedly.
My Question
How do I change the function to read a line of text, (with the hope to perform an action on such line, shown by "//do some action") and then move onto the next line in the subsequent loop, repeating this until the end of file has been reached?
Hopefully this makes sense.
Buffer
before this lineBuffer[bufferposition] = 0
? – IntratelluricBuffer
before terminating the string is a good idea. – NyasalandBuffer[bufferposition] = 0
. At this point you have a valid string in your buffer that you can use to trigger any action. However, note that you is including a\n
character as last character. This can be an issue when processing the line. In order to remove it, just replaceBuffer[bufferposition] = 0;
byBuffer[bufferposition-1] = 0;
. There is nothing wrong in keeping the file open while processing the commands. You can close it after reading the whole data. – Intratelluric//do some action here
. The while loop will read one line each time and the content of the line will be stored in the variablebuffer
. – Intratelluric