Search code examples
iosnstimertimingsampling

"Precise" sample timing in cycles in ios


I'm periodically sending data to an RC helicopter, at the moment I am using NSTimer with a time interval of 30 ms to do this. Now due to the imprecision of NSTimer and the non-real timedness of ios I'm getting quite big discrepancies with the sample times. (5 packets of data in the first 30 ms then nothing for 4 cycles and such). Is there a more precise way to handle data sampling and timing of functions in ios?


Solution

  • You could do something like you usually do in games to finely tune fps (and also keep logic and painting separate to make it work fine in any fps). Something like this, and call it in a background thread:

    - (void)updateLoop
    {
        NSTimeInterval last = CFAbsoluteTimeGetCurrent();
        NSTimeInterval elapsed = 0;
        while (self.running) {
            NSTimeInterval now = CFAbsoluteTimeGetCurrent();
            NSTimeInterval dt = now - last;
    
            elapsed += dt;
    
            if (elapsed >= YOUR_INTERVAL) {
                //Do stuff
                elapsed = 0;
            }
    
            last = now;
    
            [NSThread sleepForTimeInterval:0.001]; //There is not NSThread yield
        }
    }