Help: odd but consistent output from micros()

Hi folks, first post here, so please bear with me if this is any sort of FAQ. I’ve Googled for a day or two but can’t find an answer. Maybe I just don’t know enough to find what I’m looking for.

I’m basically hacking Alastair Parker’s Pong code into something else, so ideally need very accurate timing in order to produce video output from two Arduino digital pins operating through a resistor DAC. So far so good.

I’m trying to produce a wait loop at the bottom of my code which waits for a certain amount of time to have elapsed since a point further up the code. This will be for the frame timing, and so ideally needs to be every 20ms for PAL video frames, and pretty much accurate to the microsecond.

The basic code so far looks like this:

void loop()
{
// iterate over the lines on the tv

then = micros();

for ( line =0;line< DISPLAY_LINES;++line)
{
    ... Draw 240 video lines @ 64us each ...
}

//vsync
PORTB = _SYNC;

while (micros()-then < wait)
  ;
}

…where ‘wait’ has been previously set to 1023 as this gives a stable picture on my test TV. Interrupts are disabled while this code runs, and I’m using Arduino 0017.

Drawing 240 lines at 64us each should take 15360us, but the difference between the before and after values returned by micros() is consistently 320 (or occasionally 316), in other words, vastly too small.

Any ideas why? And is there a better way to make sure a piece of code is called consistently every 20ms (or better, 19.9ms for faked progressive PAL video)?

Many thanks,

Dr. Matt…

Full code is at http://dl.dropbox.com/u/1279811/SuperPong.txt, with apologies for the mess.

Interrupts are disabled while this code runs,

The functions "micros", "delay" and "millis" all depend on interrupts being enabled.

You could try delayMicroseconds (with interrupts disabled).