Counter not working...?

Hey, I've been trying to get a simple counter set up, but for some reason it doesn't really do anything.

void loop() {
  char cmd;			                          // Command input by user
  int humidVal;			                      // Humidity value read from SHT1x
  int tempVal;		 	                      // Temperature value from SHT1x
  int sensorNum;                          // Sensor number
  float fHumidity;		                    // Working value for humidity calculation
  float fTemperature;		                  // Working value for temperature calculation
  unsigned char error;		                // Return value for routine calls
  unsigned int port;
  int counter;

  while (Serial.available () > 0) {   		// When a serial connection exists
      cmd = Serial.read ();	              // Read user comand
      error = 0;
      if (cmd == TIME_HEADER) {           // If the command starts with "T"
          processSyncMessage();           // Set the time
         }

      if (timeStatus() != timeNotSet) {   // If the time is set
         digitalClockDisplay();           // Display the new time
         }
      else {
         setTime(1420070400);
         }

      if (cmd == SENSOR_CALL) {         // if the command starts with "S"
         sensorNum = Serial.parseInt(); // Set sensorNum as input  
         port = sensorNum;
	       
	       if (port < 2) {                  // If port 2 was called
	          Serial.println ("Unable to access serial communication port!\n");
	          break;                        // Exit this statement
	          }
	       if (port == CLOCK) {             // If the clock port was called
	          Serial.println ("Unable to access SHT10 CLOCK port!\n");
	          break;                        // Exit this statement
	          }
	                                        // Read request - read in temperature and humidity
	       Serial.print ("Accessing port ");
	       Serial.println (port);          // Print the port being accessed
	       error +=                        // Increment the error value
	       sMeasure ((unsigned char *) &humidVal, MEASURE_HUMI, 0, port);
	       error +=
	       sMeasure ((unsigned char *) &tempVal, MEASURE_TEMP, 0, port);
	       if (error)
            sConnectionReset (port);
	       else {
          digitalClockDisplay();
            fHumidity = float (humidVal);
            fTemperature = float (tempVal);
            calcTempHumid (&fHumidity, &fTemperature);
            printReading ("Reading: ", &fTemperature, "*C");
           // String test1 = printReading ("Reading: ", &fTemperature, "*C");
            printReading (" at ", &fHumidity, "% Humidity");

            //dataFileA = SD.open("data_A.txt");
           //if (dataFileA) {                                                         //if the file is open
            //  dataFileA.println(printReading("Reading: ", &fTemperature, "*C"));    //write the output string for T/C1 to the card
             // dataFileA.println(printReading(" at ", &fHumidity, "% Humidity"));    //write the output string for T/C2 to the card
             // dataFileA.close();                                                       //close the dataFile
              //Serial.print(output1String);                                            // print to the serial port too
              }
            
            Serial.println();
	          }
	      Serial.println ();
	      break;
	      }
  
      if (second() == 40 || second() == 10) {    // Auto reading every 30 seconds
         counter++;   //COUNTER DOESN"T WORK!
         if (timeStatus() != timeNotSet) {       // If the time is set
         digitalClockDisplay();                  // Display the new time
         }
         
         Serial.println(counter);
         for (int xy = 5; xy < 7; xy++){        // For loop to go through all the sensor ports.  Change this upper value for increased number of sensors
         port = xy;                              // Set the port to the current value of the For loop
                                                 
         Serial.print ("Port ");
         Serial.println (port);                  // Print the port being accessed     
         error +=                                // Increment the error value
         sMeasure ((unsigned char *) &humidVal, MEASURE_HUMI, 0, port);
         error +=
         sMeasure ((unsigned char *) &tempVal, MEASURE_TEMP, 0, port);
         if (error) {
            Serial.println();
            sConnectionReset (port);
            break;
            }  
            
         else {
            fHumidity = float (humidVal);
            fTemperature = float (tempVal);
            calcTempHumid (&fHumidity, &fTemperature);
            printReading ("Reading: ", &fTemperature, "*C");
            printReading (" at ", &fHumidity, "% Humidity");
            Serial.println();

            delay(200);
            }
        Serial.println();
        }
       
     }
}

Roughly 2/3s of the way down is where I have it currently, and it'll count to 1, but keep spitting out 1 every time. I want it to count every time the 40 or 10 second if statement is run.
I tried having it at the end of the code, after the for loop but still inside the if statement, but it just returns a 0 every time. Any ideas of what's going on? I mean, something like this shouldn't be so complicated, but I cannot seem to figure it out for some reason.

For openers, you declare a char variable command, but try an if statement where you check for equality of cmd with a whole string, TIME_HEADER. I don't see how the compiler accepts that, but if it does, it probably doesn't generate the code that does what you want. Better study up on the difference between characters and strings, and also study up on how to properly compare strings.

Perhaps you should have posted all of your code and not just the loop().

Having said that, I don't see 'second' being modified anywhere in your code. No reference to it anywhere, except in the comparison line.
Perhaps this has something to do with it?

jrdoner:
For openers, you declare a char variable command, but try an if statement where you check for equality of cmd with a whole string, TIME_HEADER. I don't see how the compiler accepts that, but if it does, it probably doesn't generate the code that does what you want. Better study up on the difference between characters and strings, and also study up on how to properly compare strings.

I don't see quotation marks around TIME_HEADER. Isn't it just a constant, no doubt defined as 'T'? (Or am I missing something?)

Another good reason to have posted all of the code and not just the loop.

Delta_G - I missed that one.

Delta_G:

int counter;

This creates the counter variable, but it does so INSIDE the loop function. That means this variable is local to the loop function. So it gets destroyed and recreated every time loop exits and is called again. You can either make it static (add static keyword) or global (move variable definition up above setup) to make it live on between calls to loop.

Google "C++ Scope" for more information.

Something so simple like that, thank you for the help and the added explanation!
This actually resolved the issue I was having. I'll definitely be checking out the C++ Scope like you mentioned.

So 'second' never changes?

OldSteve:
So 'second' never changes?

I have other code that functions properly, but it's too large to post to the forum (over 9000 characters).
Besides, I knew it was a simple problem, which was why I only posted the loop() section. But if you want to look over my whole code:

'second' is set from my internal clock (Time.h). I'm still waiting on an RTC module to come in, so right now I'm using a code-based clock.

haetr01:
I have other code that functions properly, but it's too large to post to the forum (over 9000 characters).
Besides, I knew it was a simple problem, which was why I only posted the loop() section. But if you want to look over my whole code:

#include "ctype.h"#include "Time.h"#include "SD.h"#include "SPI.h"#def - Pastebin.com

'second' is set from my internal clock (Time.h). I'm still waiting on an RTC module to come in, so right now I'm using a code-based clock.

No worries. I suspected that might have been the case, but thought I'd better mention it since in the code you posted 'second' was never modified.

On an aside, you can do away with some of the curly brackets, too.
Where only one statement follows an 'if()' statement, there's no need for curly brackets around it.
ie This:-

if (cmd == TIME_HEADER) {           // If the command starts with "T"
    processSyncMessage();           // Set the time
}

can be:-

if (cmd == TIME_HEADER)             // If the command starts with "T"
    processSyncMessage();           // Set the time

It makes things a little more concise and easier to read.

And we don't need to see all of your code now that the problem has been quickly solved by Delta_G.

OldSteve:
On an aside, you can do away with some of the curly brackets, too.
Where only one statement follows an 'if()' statement, there's no need for curly brackets around it.

I know, but it's just a habit of mine. I find it easier to follow when the if statement's contents are in curly brackets regardless of how many lines are in it.

haetr01:
I know, but it's just a habit of mine. I find it easier to follow when the if statement's contents are in curly brackets regardless of how many lines are in it.

Yep, no problem. Just thought I'd mention it in case you didn't know.

I have peculiar habits anyway, and always put the opening curly bracket on a new line, too, to improve readability, but no one else seems to do that any more.
(Just some of the things I was taught years ago when I started, and fell into the habit of doing. :slight_smile: )

OldSteve:
Yep, no problem. Just thought I'd mention it in case you didn't know.

I have peculiar habits anyway, and always put the opening curly bracket on a new line, too, to improve readability, but no one else seems to do that any more.
(Just some of the things I was taught years ago when I started, and fell into the habit of doing. :slight_smile: )

You mean, like this?

if (condition)    // that's one line
{                 // two lines so far
  doSomething();  // yup, three lines
}                 // four whole lines just for that?!

I used to do that as well, until I started using Visual Basic for work. Now I kind of look at the curly brackets as "Then" and "End If" equivalents.

odometer:
You mean, like this?

if (condition)    // that's one line

{                // two lines so far
  doSomething();  // yup, three lines
}                // four whole lines just for that?!

Yep, but never for just one line after the 'if()' statement.
It only adds one line, and for me makes the code more readable. It's much easier to see the opening bracket.

if(x==y)
{
    //do something...
    // do something else...
    // do yet another thing....
    // and another....
}

I didn't say others should do that - it's just how I like doing it, and not really worthy of your special post just to ridicule it.

haetr01:
I used to do that as well, until I started using Visual Basic for work. Now I kind of look at the curly brackets as "Then" and "End If" equivalents.

I've used PICBasic for years, and there are no brackets to contend with, but in C++ I like that clearly-seen opening bracket. I even modified the 'formatter.conf'file so that it's done automatically by 'Auto Format' when I copy other people's code into the Arduino editor.

Horses for courses, I say. It does no harm, and doesn't alter execution in any way - it just makes the code slightly more readable, for me at least, like your preference for the use of curly brackets around single statements after an 'if()'.

Some people think that everything has to be done their way - not so.