Making a simple counter/timer

I am trying to do something very simple and can’t figure out how. I want to implement a counter that counts from 0 to 12, printing out 1 number per second (so on run it will immediately print “0”, followed by “1” 1 second later, etc.). My code works but the problem is that it prints out many instances of the same number per second. When I reduce the frame rate to 1, it does the trick, but doesn’t print out the first “0”. Here is my code:

int x = 0;
int timer = 1000;
int nextTime = 0;

void setup() {
  size(100, 100);
}

void draw() {
  if (millis() > timer) {
    x += 1;
    timer += 1000;
  }
  println(x);
}

Thanks for your help!

Hi @AverageBiped,

Welcome to the community! :slight_smile:

Is this what you are looking for?

In my opinion you can either:

    • try to calculate the elapsed time using the millis() function:
int x = 0;
int ellapsedMillis = 1000;
int nextTime = 0;
int previousTime = 0;
void setup() {
  size(100, 100);
}

void draw() {
  if (millis()-previousTime>= ellapsedMillis) {
    previousTime = millis();
    println(x);
    x += 1;
  }
}

or you can use the internal clock from the computer using seconds()

int x = 0;
int nextTime = 0;
int previousTime = 0;
void setup() {
  size(100, 100);
}

void draw() {
  if (second()-previousTime>= 1) {
    previousTime = second();
    println(x);
    x += 1;
  }
}

I hope it helps!
Best regards

Since the default frameRate is 60 per second, did you try putting in setup:

frameRate(1);

EDIT:
Oh sorry, I see you DID try that…

:nerd_face:

Thank you Miguel! Both of these examples are extremely helpful. I think the first one is better suited to what I’m trying to do, and basically solves the problem. My only other question would be if there’s a way you know of to output the first “0” immediately upon running the program, rather than after 1000 ms have elapsed. Thank you again - I’m excited to be a part of this community and have access to such great knowledge from such helpful people. :slight_smile:

You can set “previousTime” to -1000 instead of 0 when you set it up.

Ha, that’s brilliant jb4x. Thank you !!

1 Like

Okay, another question: if I wanted to make this into a function that returns an int, how could I do that? The problem I’m running into is that by changing “println(x)” to “return x”, I make it so that I can’t include the following line “x += 1” because the code becomes unreachable. Do I have to change the architecture of the whole program?

int count() {
    if (millis() - previousTime >=  ellapsedMs) {
      previousTime = millis();
      x = x % max;
      return x;
      x += 1;  
    }

Hi @AverageBiped

What about using a temporary variable? So that you can modify tempX and return the x value afterward

int x = 0;
int tempX = 0;

int count() {
    if (millis() - previousTime >=  ellapsedMs) {
      previousTime = millis();
      x = tempX % max;
      tempX += 1; 
      return x;
    }
}

Best regards