Yesterday’s code has a nasty side-effect of getting into a corner out of which it almost can’t recover at times. Here’s a somewhat longer run, edited for brevity (note the indented lines):
On one occasion, it took 238 retries (12 minutes) to get back into sync!
Note how the code is sailing slightly too close to the edge, by always being at 0 or 1 ms from the expected time, just because this watchdog timer “happens” to run at a particular rate.
One fix is to gradually widen the window again when too many receptions in a row fail:
The other step is to always leave a bit more time when calculating a new estimate – it’s better to err on the side of receiving too early than to miss the start of the packet:
Whoops, looks like this doesn’t get it right – but it illustrates the widening:
This change works a lot better (i.e. plus 2, instead of minus 2):
Here’s the sample output:
The syncRecv code on GitHub has been updated with this tweak. More to come!