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;

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.