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);
}
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.
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;
}