Problem with nested if/else

Last two days I have been struggling to find out why a particular statement inside a If clause executes when it actuallyis not supposed to. But for this issue rest of the code is fully functional. Just so that not to waste your time I am just posting the function with this issue.

In this if you look , the following is the sequence :

  1. The loop() calls this startLogging() function once every 100ms.
  2. If the user has flipped the swithc to start logging , first we give him the option to choose from creating a new file / Using the existiing file / Send already logged data to PC via Serial.
  3. User chooses either the New File or Old File ultimately he reaches the doLoggingGate. This boolean allows the actual logging to SD card happen. Every second it updates the display with the latest Analog value and once the set interval elapses, it logs the value to the SD card.

All working as expected upto this pont.

The bug hits only after this point : I expect the code execution to return to the doLoggingGate after the next 100ms period. But instead it reaches the "Serial.write(dataFile.read) " statement , sends the logged data to Serial and THEN gets back to doLoggingGate.

I have done extensive debugging and observe that none of the booleans which permit the Serial.Write( dataFile.read) statement to execute are ON . Yet the read happens.

The function is as below. If this one does not give any clue, then I can post the full zipped code which is a bit large :

//@@@@@@@@@@@@@@@@@@@@@@@

// The Main logging function

void startLogging ()
{
  bool logSwVal = digitalRead(LogOnSw);   // User has chosen to start logging to SDC

  if (logSwVal == false )                                // Active low...
  {
    homeDispGate = false;
    if (beginLogGate )                                     // Inform user the choices ....
    {
      beginLogGate = false;
      homeDispGate = false;
      lcd.clear();
      lcd.print(( "Erase/Start/Read"));             // Choices : Erase and start a new file / Append to existing file / Send logged file to PC app. 
      lcd.setCursor(0, 1);
      lcd.print(( "NEW  /APPEN/SEND"));
      fileChooseGate = true;
    }

    //############################

    if (fileChooseGate)                                    // Wait for user response
    {
      if ( validDIN == 'N') {
        newFileGate = true;                               //ersae old file and dtart new file..
      }
      else if ( validDIN == 'D') {
        oldFileGate = true;                                //continue logging to old file
      }
      else if ( validDIN == 'S') {
        dumpDataGate = true;                         // initiate a read from the SDC 
      }
    }

    //#########

    if ( newFileGate )                                        //  [ HANDLE NEW FILE CASE ]
    {
      fileChooseGate = false;
      newFileGate = false;
      validDIN = NO_KEY;
      lcd.clear();
      lcd.print(( "Erase SDC/Cancel"));            // Give one more warning 
      lcd.setCursor(0, 1);
      lcd.print(( "NEW FILE /APPEND "));
      delay(2000);
      eraseConfGate = true;
    }

    //#########

    if ( eraseConfGate )
    {
      if ( validDIN == 'N')                                  // User is hell bent on erasing...
      {
        validDIN = NO_KEY;
        if (SD.exists("TEMPLOG.CSV"))         
        {
          if (!SD.remove("TEMPLOG.CSV"))
          {
            lcd.setCursor(0, 0);
            lcd.print(( "Error Erasing SD"));
            lcd.setCursor(0, 1);
            lcd.print(( "Check SD Card !!"));
            while (1);                                           // Something went wrong... wait for reset
          }
        }
        lcd.setCursor(0, 0);
        lcd.print(( "SD Card Erased!!"));           // Inform user the old file is gone
        lcd.setCursor(0, 1);
        lcd.print(( "New File opened."));
        delay( 2000);
        doLoggingGate = true;                          // Start logging ...now.
        eraseConfGate = false;
      }

      else if ( validDIN == 'D')                          // User changed his mind not to erase 
      {
        beginLogGate = true;
        validDIN = NO_KEY;
      }
    }

    //#########

    if ( oldFileGate)                                        // [ HANDLE APPEND FILE CASE ]
    {
      fileChooseGate = false;
      oldFileGate = false;
      doLoggingGate = true;                           // Jump to do logging...
      validDIN = NO_KEY;
    }

    //#######

    if ( doLoggingGate )                                // Actual logging operation to SDC  happens here 
    {
      if (  second() != prevSecond )  {
        prevSecond = second();
        dtostrf(tempDegC, 5, 2, bufferT);       // Update the temperature
        lcd.setCursor(0, 0);
        lcd.print(( "Logging Started."));
        lcd.setCursor(0, 1);
        sprintf(clockStringNow, "  Deg C = %s ", bufferT);
        lcd.print(clockStringNow);
        Serial.println("Started Logging !");
        digitalWrite(13, LOW);
      }

      if ( millis() - logMs > loggingInterval * 1000 )    {              // Time to write to SD card
        logMs = millis();
        logFile = SD.open("TEMPLOG.CSV", FILE_WRITE);   // Open the file to write

        if (logFile)                                                                  
        {
          sprintf( dataToLog, "%02d/%02d/%02d-%02d:%02d:%02d %s", year(), day(), month(), hour(), minute(), second(), bufferT);
          logFile.println(dataToLog);
          logFile.close();
          digitalWrite(logging_LED, HIGH);                                   
        }
        else
        {
          lcd.setCursor(0, 0);
          lcd.print(( "SD Card Error !!"));                                      // Inform user that logging has failed...
          lcd.setCursor(0, 1);
          lcd.print(( "Check SD Card..."));
          digitalWrite(logging_LED, LOW);
          while (1);                                                                    
        }
      }
    }

    //#########

    if (dumpDataGate  )                                                            // [ HANDLE SEND FILE CASE ]
    {
      fileChooseGate  = false;                                                   
      validDIN = NO_KEY;
      dumpDataGate = false;
      homeDispGate = false;
      prepareTransfer = true;
    }

    //########

    if ( prepareTransfer)                                                               
    {
      lcd.setCursor(0, 0);
      lcd.print(( "Ready to Send..."));                                        // Inform user that you are waiting for acknowledgement
      lcd.setCursor(0, 1);
      lcd.print(( "Waiting for R   "));
      prepareTransfer = false;
      waitOnSerGate = true;
    }

    //########

    if (waitOnSerGate )                                                         // Serial read is now active waiting for user response..
    {
      if (readyToReceiveDump )                                           // User has acknowledged the request..
      {
        slTransmittGate = true;
        waitOnSerGate   = false;
        lcd.clear();
      }
    }

    //#######

    if (slTransmittGate  )
    {
      File dataFile = SD.open("TEMPLOG.CSV", FILE_READ);
      if (!dataFile) {                                                                // Problem opening data file..quit!
        lcd.clear();
        lcd.print(("File Open Error!"));
        while (1);                                                                      // Hang on here ...for reset
      }
      else
      {
        lcd.print(( "Sending Data..  "));
        while (dataFile.available())                                           // PROBLEM : When actual logging  is ON, code reaches this point direct after writing to SDC one record.
        {                                                                      
          Serial.write(dataFile.read());                                     // Data file exists ..read it.
        }

        dataFile.close();
        Serial.println("OK");
        lcd.clear();
        lcd.print(( "SDC Data Oprn..."));
        lcd.setCursor(0, 1);
        lcd.print("    >>>>>>>>    ");
        slTransmittGate = false;
        beginLogGate = true;
        readyToReceiveDump = false;
      }
      delay(1000);
      lcd.clear();
    }
  }                                                                                      // ( END of logSwVal = false)

  else
  {
    doLoggingGate = false;                                                // Stop logging and reset the variable
    beginLogGate = true;
    homeDispGate = true;
    digitalWrite(logging_LED, LOW);
  }
}

// ( END of startLogging())

If I read your coded correctly (which is I found very painful btw!) 'readyToReceiveDump' is what sets 'slTransmittGate'

so question is "how is 'readyToReceiveDump' set?"... can't find that one in the code you posted....

Ok i told that what i posted is NOT The complete code. I am now posting the full code. If reading what i posted was painful, this could be no less !!

Teensy3.5_DataLogger_V1.3.zip (7.42 KB)

My guess is a buffer overflow.

In your main file:

char dataToLog[20];
char bufferT[20];

in Functions.ino:

  ..........

  dtostrf(tempDegC, 5, 2, bufferT);       // Update the temperature

  ...........

  sprintf( dataToLog, "%02d/%02d/%02d-%02d:%02d:%02d %s", year(), day(), month(), hour(), minute(), second(), bufferT);

"%02d/%02d/%02d-%02d:%02d:%02d " <-- that's 18 characters, before adding the contents of bufferT

Try increasing the size of dataToLog. If memory is an issue, decrease the size of bufferT proportionally.

darrob:
My guess is a buffer overflow.

In your main file:

char dataToLog[20];

char bufferT[20];




in Functions.ino:


..........

dtostrf(tempDegC, 5, 2, bufferT);      // Update the temperature

...........

sprintf( dataToLog, "%02d/%02d/%02d-%02d:%02d:%02d %s", year(), day(), month(), hour(), minute(), second(), bufferT);





"%02d/%02d/%02d-%02d:%02d:%02d " <-- that's 18 characters, before adding the contents of bufferT


Try increasing the size of dataToLog. If memory is an issue, decrease the size of bufferT proportionally.

Great ... that s a valid point. Possibly I will just increase the size of dataToLog[] to about 40 . SRAM is not an issue as I am using the Teensy3.5.

Will check out once the unit gets back to me from the field where its data logging the last three days with no issues ( at least no issues to the user !!)