Hi guys, I’d be grateful for your guidance. I would like to have a Timer that triggers an event every 20ms. with good accuracy. Every 20ms it will read a value from an arrayList and it will send it through Serial.
I have so far tested quite a few ways as found in the forums, including the Java Timer class, the TimedEvents library, etc.
They all seem to be a bit out, similar amount as in this basic bit of code enclosed below that uses delay(). So instead of 20ms between events, I am getting something like 20,23,21, 24, 20ms…and so on.
My question is, is it possible to get closer to the 20ms that I need with an even spacing , or am I being totally unrealistic? I’m on a Mac, in case it’s relevant. In any case, I am more after precision than accuracy i.e. , I rather get 23, 23, 23ms between delays than 20,21,19,23, etc…
The other problem is that the incremental counter (on which I rely to get the array element number) sometimes skips at these high frequencies, so for instance on a run of 250 counts, it may skip a couple counts, no good:). Although to be fair this skipping is shown in the println(),which is slow, so maybe in reality it doesn’t skip, I still have to check that.
Many thanks in advance.
int frequency = 20; // 20 milliseconds between events
int counter=0;
int startMillis;
void setup() {
}
void draw() {
}
void keyPressed() {
for (int i = 1; i > 0; i = i++) {
int millisDiff = millis() - startMillis;
startMillis = millisDiff + startMillis;
counter++;
println(“Counter: " + counter +” millis: " + millis() + "ms " + “frequency: " + millisDiff + " ms” );
delay(frequency);
if (counter>=250) {
counter=0;
break;
}
}
}