Writing to a file on an SD card

I have successfully written a program which can open a file on an SD card and write "hello world" to the file. However I am encountering a problem when transferring this code to a more complicated program. The program counts the number of times something passes through a two light-gate system this integer variable is given the name lemnum. Lemnum is what I am trying to write to the file on the SD card, however the file doesn't open. Every time that the file should open, i.e. when 1 is added to lemnum, instead the error message is printed to the serial port. Below is the relevant section of the code.

else if ((array[0] == 0) && (array[1] == 0))//lemur has entered the box
{
lemnum = lemnum++;//add one to the lemnum
state = 1;//return to state 1

Serial.println(lemnum);//print the number of lemurs to the serial port
//open the file
dataFile = SD.open("lemur.txt", FILE_WRITE);
//if the file is available write to it
if (dataFile)
{
//write lemnum to the file
dataFile.println(lemnum);
//close file
dataFile.close();
}
//if the file doesn't open, pop up an error
else
{
Serial.println("error opening lemur.txt");
}
break;

Any help, is greatly appreciated! :slight_smile:

Edit: removed

Do you mean that I should get rid of the if statement to give:

Serial.println(lemnum);//print the number of lemurs to the serial port
//open the file
dataFile = SD.open("lemur.txt", FILE_WRITE);
//write lemnum to the file
dataFile.println(lemnum);
//close file
dataFile.close();

This still doesn't open the file. And when I do a Serial print of dataFile it gives 0.

I take back my previous post, and ask to see your full code.

Also try the example again, and break it down.

        lemnum = lemnum++;//add one to the lemnum

n++ is equivalent to n = n + 1. So, your statement is equivalent to

lemnum = lemnum = lemnum + 1;

Looks a little silly that way, doesn't it.

Of course, the comment stating the obvious does, too.

Below is the relevant section of the code.

Clearly that isn't the source of the problem, since incrementing lemnum and setting state should have no impact on the ability to open the file.