Adding an unrelated simple IF condition stops the SD from working

Hi there,

I’ve been working on a people counter. I am using (all generic Arduino compatible devices from Banggood) an Arduino Nano, a couple of IR receiver and a micro SD module. The involved library is SD.h v1.2.2 The section I would like to focus is this one (I deleted code that is not useful to see what the issue I ran into):

void loop() {
   for (int i = 0; i < RECEIVERS; i++)
    statusPin[i] = digitalRead(2+i);
    if (statusPin[i]==0) 
     if ((millis()-previousMillis[i]>150)&&(millis()-previousMillis[(i+1) % 2]>150)) 
          if (i==0)

void LogToSD(){
    DateTime now =;   
[b]    File dataFile ="dwvisit.csv", FILE_WRITE);
[/b]  if (dataFile) {
    Serial.println("error opening dwvisits.csv");

Everything was working like charm, but I had room for improvement in terms of accuracy, so that I added a third condition in an IF:

if ((millis()-previousMillis[i]>150)&&(millis()-previousMillis[(i+1) % 2]>150)[b]&&(previousMillis[i]<previousMillis[(i+1) % 2])[/b])

and voila! Most of the time, it cannot initialize the micro SD card, when it does, it cannot create the file or creates it but then cannot write on it. If I delete the third condition or add a dummy condition, like 2<3, it works again. I did it a several times with the same result: without the 3rd condition, it works, with the 3rd condition, this part in LogToSD() doesn’t work:

    File dataFile ="dwvisit.csv", FILE_WRITE);

I cannot make sense of it. The micro SD worked fine in the computer and with my camera.

Now it becomes weirder. After a week switching between codes, the one that worked started to stop working just after re-loading it, I had to upload it twice in order for the SD to work (after that, it kept working). Today, after giving up searching solutions and trying lots of tweaks, I decided to come back to the original code, but it no longer worked (not even with a good brand micro SD I borrowed from my camera). I decided then to try formatting the SD with the Formatter utility recommended in this forum (Note: the SD was working, I could open and edit the files in it), but after starting the formatting (BTW, I didn’t find any single format option in the software, while here, several are mentioned), error message, and that was it. I tried again, nothing. I tried to format it with the Windows utility, nothing, error. I ended up with no counter and a broken SD.

I already ordered a new SD and different SD Module from different manufacturer. Do you think it can be related to defective hardware? I read that generic SD module from Banggood is problematic, but that doesn’t explain why a logic condition in an IF affects the SD and why Formatter killed my micro SD.



I cannot make sense of it.

Well, I can not make sense of your snippets. Trying to bold text in a code window does not work.

So, you have two choices. 1) Post all of your code. 2) Fix the problem yourself.

Your choice.