Go Down

Topic: Counting seconds (Read 694 times) previous topic - next topic

Skywolf

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...

Code: [Select]

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!

Nick_Pyner

#1
Jan 21, 2013, 04:09 am Last Edit: Jan 21, 2013, 04:40 am by Nick_Pyner Reason: 1



Code: [Select]

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...

Quick5pnt0

I think you need to change
Code: [Select]
int count = count + 1;

To
Code: [Select]
count = count + 1;

el_supremo

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.
Code: [Select]

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

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

Pete

Delta_G

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
Code: [Select]
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.

Skywolf


michinyon

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 ?

Go Up