Counting seconds

Hello!

I'm fairly new to the Arduino/C++ programming language. I wanted to make an integer counter that counted seconds. This is what I have...

void setup() { 
    Serial.begin(9600);
    int count=0;
}

void loop() {
  int count = count + 1;
  Serial.println(count);
  delay(1000);
}

Except whenever I launch the code, it prints "1" over and over again. How can I set this so that it will count 1, 2, 3, 4, etc.?

Thanks!

Skywolf:

void setup() { 

Serial.begin(9600);
 
}

void loop() {
Serial.println(millis()/1000);
delay(1000);

}

The above rough and ready one-line modification is lifted from the Hello World LCD sketch in the examples. Try that...

I think you need to change

int count = count + 1;

To

count = count + 1;

You have declared to be local to the loop function so every time you enter loop() the count variable is created anew and initialized to one. You should declare it to be global (outside loop) so that it won't be regenerated all the time.

void setup() { 
    Serial.begin(9600);
    int count=0;
}

int count = 0;
void loop() {
  count = count + 1;
  Serial.println(count);
  delay(1000);
}

Pete

You are declaring an int called count twice. You are declaring it once inside the setup function, it goes away forever as soon as setup exits. Then you declare a new one in loop, it goes away every time loop returns and then a new one is created when loop starts again.

Instead, do the

int count = 0;

part up above the setup function so it will be at global scope. Then just call the variable by it's name and drop the int part ever after that.

It works. Thanks!

Well that solves your problem with the repeated 1's.

How accurate do these seconds need to be, and how long do they need to go on for ?