If you want a framerate control (do a certain amount of thing every X time apart), do this:
unsigned long lastFrameStart;
unsigned long nextFrameStart;
bool justRendered;
uint8_t lastFrameDurationMs;
uint16_t frameCount;
uint16_t frameDiff;
bool setFrameDiff
(uint16_t rate)
{
frameDiff = rate;
return 0;
}
bool nextFrame
(void)
{
unsigned long now = millis();
bool tooSoonForNextFrame = now < nextFrameStart;
if (justRendered) {
lastFrameDurationMs = now - lastFrameStart;
justRendered = false;
return false;
}
else if (tooSoonForNextFrame) {
if ((uint8_t)(nextFrameStart - now) > 1)
sleep(1);//delay(1) when the processor does not support "sleep" function
return false;
}
// pre-render
justRendered = true;
lastFrameStart = now;
nextFrameStart = now + frameDiff;
frameCount++;
//if (frameCount > 20000)
//frameCount = frameCount - 20000;
return true;
The code is part of my library that display graphics on a screen at 50Hz. or 10Hz.
I then used "frameCount" to poll data from a temperature sensor (and/or PM sensor) every 25/5 frames (every half a second) to make sure I don't miss out anything, since the sensors will respond with "NACK" when the data is not ready.