Timed Triggers and modulos

#1

I’m working on a bit of code to make something happen every couple of seconds.
The idea was something like this:

if (ofGetElapsedTimef() % 8) {
printf(“ok, it’s working”);
}

But this throws an error about floats - maybe having something to do with floating-point resolution in C++. So, I end up trying:

if (fmod(ofGetElapsedTimef(), 8)){
printf(“ok, it’s working”);
}

And this does not work like expected.

Any thoughts on how to do this and why this approach isn’t working?

#2

Hi @JDeut,

ofGetElapsedTimef returns a float, so you must do somehting like this ( cast into int) :

 if((int)(ofGetElapsedTimef() % 8){
// do somehting
}

Hope this helps,

++

P

1 Like
#3

Hi Pierre -

Thanks for the solution - however, what I’m noticing is that if I have a Printf function inside those brackets, it prints the message many, many times when triggered. Do you happen to know why this happens?

#4

If you are doing % 8 you will get a true for the whole second. Maybe you want something more like this.

In you ofApp.h file
float startTime;

in setup
startTime = ofGetElapsedTimef();

in main loop - trigger every 3 seconds

if (ofGetElapsedTimef() - startTime > 3.0) {
    startTime = ofGetElapsedTimef();
    printf("trigger\n");
}
1 Like
#5

I usually do a timer like tod’s way but I’ve also done this in a pinch:

// assuming the app runs at 60 fps
if (ofGetFrameNum() % (60*8) == 0){
}
1 Like