Pages: [1]   Go Down
Author Topic: Counting seconds  (Read 531 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 14
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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!
Logged

Dee Why NSW
Offline Offline
Edison Member
*
Karma: 47
Posts: 2169
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset



Code:
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...
« Last Edit: January 20, 2013, 10:40:37 pm by Nick_Pyner » Logged

NE PA
Offline Offline
Full Member
***
Karma: 5
Posts: 156
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

To
Code:
count = count + 1;
Logged


Offline Offline
Edison Member
*
Karma: 43
Posts: 1550
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
void setup() {
    Serial.begin(9600);
    int count=0;
}

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

Pete
Logged

Where are the Nick Gammons of yesteryear?

Offline Offline
God Member
*****
Karma: 17
Posts: 721
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Offline Offline
Newbie
*
Karma: 0
Posts: 14
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It works. Thanks!
Logged

Offline Offline
Faraday Member
**
Karma: 57
Posts: 2764
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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 ?
Logged

Pages: [1]   Go Up
Jump to: