Keeping Time: RTCLOK, System Timers and POKEY Hardware Timers

The Atari is unusually good at real-time work, because the whole machine is slaved to the television signal and the CPU clock was chosen so that instruction timing lines up with the electron beam. The OS builds on that with a frame counter and five countdown timers, and POKEY adds four hardware timers that can interrupt the CPU thousands of times a second. This guide shows how to use each one, from BASIC where possible.

You need: Atari BASIC for most examples, an assembler for the POKEY timer section. Everything applies to all 400/800/XL/XE models, with the PAL/NTSC caveats noted.

1. Jiffies: the unit of Atari time

A jiffy is one TV frame: 1/60 second on NTSC machines and 1/50 on PAL. De Re Atari's clock program divides by 59.923334 to be exact, because an NTSC Atari produces slightly fewer than 60 frames per second. All the OS software timers count in jiffies, because they are updated by the vertical blank interrupt. If the VBI is disabled or replaced, they stop.

2. RTCLOK: the frame counter

Locations 18, 19, 20 ($12–$14) hold a three-byte counter that the OS increments in stage 1 of every vertical blank. Location 18 is the most significant byte:

Location Rolls over Meaning
20 ($14) every 256 frames Jiffies (low byte)
19 ($13) every 4.27 s on NTSC Middle byte
18 ($12) every 18.2 min on NTSC (65,536 frames) High byte

After 16,777,216 frames (about 77 hours) the counter wraps to zero. RTCLOK is updated in every vertical blank, even during time-critical code, so it keeps counting during disk I/O as well.

Reading it safely

The bytes can change between your PEEKs. If location 20 rolls from 255 to 0 just after you read location 19, your total is off by 256 jiffies. De Re Atari's clock routine fixes this by reading all three bytes and repeating until two reads agree. The same idea in BASIC:

900 T1=PEEK(18):T2=PEEK(19):T3=PEEK(20)
910 IF T1<>PEEK(18) OR T2<>PEEK(19) THEN 900
920 J=T1*65536+T2*256+T3:RETURN

Benchmarking BASIC code

This is the most practical use of the clock. Wrap whatever you want to time:

10 GOSUB 900:S=J
20 FOR I=1 TO 1000:A=A+1:NEXT I
30 GOSUB 900
40 PRINT "TOOK ";J-S;" JIFFIES"
50 PRINT "= ";(J-S)/60;" SECONDS (NTSC)"
60 END
900 T1=PEEK(18):T2=PEEK(19):T3=PEEK(20)
910 IF T1<>PEEK(18) OR T2<>PEEK(19) THEN 900
920 J=T1*65536+T2*256+T3:RETURN

Try it with POKE 559,0 before line 20 and POKE 559,34 after it. Turning off ANTIC's screen DMA visibly speeds BASIC up, by about 30%. 34 is the normal value for a standard playfield in GRAPHICS 0; it's good practice to PEEK and save the original value before you clear it.

A time-of-day clock

Set a starting time once, then compute the elapsed time from RTCLOK:

10 PRINT "HOUR, MINUTE";:INPUT H0,M0
20 GOSUB 900:S=J
30 GOSUB 900:T=INT((J-S)/60)+H0*3600+M0*60
40 H=INT(T/3600):M=INT((T-H*3600)/60):SC=T-H*3600-M*60
50 H=H-INT(H/24)*24
60 POSITION 10,10:PRINT H;":";M;":";SC;"   "
70 GOTO 30
900 T1=PEEK(18):T2=PEEK(19):T3=PEEK(20)
910 IF T1<>PEEK(18) OR T2<>PEEK(19) THEN 900
920 J=T1*65536+T2*256+T3:RETURN

On NTSC, dividing by 60 drifts by about 0.13% (the true NTSC rate is 59.923334). For a clock that stays accurate over hours, use that constant, or 50 on PAL.

3. PAL or NTSC?

Every duration measured in jiffies depends on the video standard. The GTIA's PAL register at 53268 ($D014, read-only) tells you which one you have. Its low four bits read 0001 on PAL and 1111 on NTSC, but only bits 1–3 are guaranteed by the original specification. Atari BASIC has no AND operator, so extract bits 1–3 arithmetically:

10 V=PEEK(53268):B=INT(V/2)-INT(V/16)*8
20 IF B=0 THEN HZ=50:PRINT "PAL"
30 IF B=7 THEN HZ=60:PRINT "NTSC"

Use HZ wherever you convert jiffies to seconds. On XL/XE machines the OS also keeps a PAL/NTSC flag, PALNTS at $62 (cc65's atari.inc: 0 means NTSC), but the GTIA test works on every model.

4. The five system countdown timers

The OS provides five 16-bit timers that count down once per frame:

Timer Locations When it reaches zero Notes
1 536–537 ($218) JSR through CDTMA1, 550–551 ($226) Used by SIO for serial bus timeouts: avoid
2 538–539 ($21A) JSR through CDTMA2, 552–553 ($228) Free for you; the vector starts at zero, so set it first
3 540–541 ($21C) Clears flag CDTMF3, 554 ($22A) Used by the cassette handler; also a DOS timeout flag
4 542–543 ($21E) Clears flag CDTMF4, 556 ($22C) Free
5 544–545 ($220) Clears flag CDTMF5, 558 ($22E) Free

Timer 1 is decremented in stage 1 of the VBI. Timers 2–5 are decremented in stage 2, so they pause during time-critical I/O.

Using a timer from BASIC

The simplest method, popular in Antic music listings, is to POKE a value into the low byte and wait until it reads zero:

100 POKE 543,0:POKE 542,90:REM TIMER 4 = 1.5 S (NTSC)
110 IF PEEK(542) THEN 110

Two details matter. First, clear the high byte as well. Second, keep values under 256: a VBI can arrive between the two byte writes of a 16-bit value. The flags offer a non-blocking alternative. Set the flag non-zero yourself, start the timer, and carry on with other work, checking the flag now and then:

100 POKE 556,255:POKE 543,0:POKE 542,120
110 REM ... GAME LOOP CONTINUES HERE ...
120 IF PEEK(556)=0 THEN PRINT "TWO SECONDS ARE UP"

Using a timer from assembly

From machine code, always set timers through SETVBV ($E45C). Put the timer number (1–5) in A, the high byte of the count in X and the low byte in Y. De Re Atari's example sets timer 1 to $200 frames:

        LDA #1          ; timer number
        LDY #0          ; low byte
        LDX #2          ; high byte: $200 frames
        JSR SETVBV

For timers 1 and 2, the OS "simulates a JSR" through the vector when the count expires, so your routine ends with RTS. To repeat, it must restart the timer itself. De Re Atari's metronome example does exactly this: the timer-2 routine clicks the speaker and calls SETVBV again with the rate from a page-zero variable. Because these routines run inside the VBI, keep them short.

5. POKEY hardware timers

When a jiffy is too coarse, for sample playback, serial bit-banging or a high-resolution stopwatch, use POKEY. Its four audio dividers double as countdown timers, and timers 1, 2 and 4 can raise IRQs with vectors VTIMR1 ($210), VTIMR2 ($212) and VTIMR4 ($214). The original OS never vectors through VTIMR4 because of a bug; Rev. B fixed it. The setup steps:

  1. Choose the clock in AUDCTL ($D208).
  2. Set the channel's volume to 0 in AUDC.
  3. Put the count in AUDF. The period is (AUDF+1)×28 cycles on the 64 kHz clock or (AUDF+1)×114 on the 15 kHz clock.
  4. Write your handler and point the timer vector at it.
  5. Set the timer's bit in both IRQEN ($D20E) and its shadow POKMSK ($10). Bit 0 enables timer 1, bit 1 timer 2, bit 2 timer 4.
  6. Write any value to STIMER ($D209) to load and start the timers.

A roughly 1 kHz tick counter (64 × 28 = 1,792 cycles per tick, about 998.7 Hz on NTSC):

AUDF1  = $D200
AUDC1  = $D201
AUDCTL = $D208
STIMER = $D209
IRQEN  = $D20E
POKMSK = $10
VTIMR1 = $0210

        *= $3000
INIT    SEI             ; no IRQs while we change the vector
        LDA #<TICK
        STA VTIMR1
        LDA #>TICK
        STA VTIMR1+1
        LDA #0
        STA AUDCTL      ; 64 kHz base clock
        STA AUDC1       ; channel 1 silent
        LDA #63
        STA AUDF1       ; (63+1)*28 cycles
        LDA POKMSK
        ORA #$01        ; enable timer 1 IRQ
        STA POKMSK
        STA IRQEN
        STA STIMER      ; any write starts the timers
        CLI
        RTS
TICK    INC TICKS       ; 16-bit tick counter
        BNE DONE
        INC TICKS+1
DONE    PLA             ; OS dispatcher pushed A
        RTI
TICKS   .WORD 0

The default timer vectors point to a PLA, RTI sequence. The OS IRQ dispatcher leaves A on the stack, so your handler must finish the same way. Save and restore X or Y yourself if you use them. Two more cautions: timer interrupts can be pre-empted by ANTIC's DMA, a DLI or the vertical blank process, and SIO reprograms POKEY during disk and cassette I/O, so reinstall your AUDCTL/AUDF settings afterwards.

6. Sub-frame timing with VCOUNT

ANTIC's VCOUNT register at 54283 ($D40B) returns the current scan line divided by two: 0–130 on NTSC and up to 155 on PAL. It is handy for waiting until the beam reaches a certain part of the screen, or for measuring how many lines a routine takes:

WAIT    LDA $D40B       ; VCOUNT
        CMP #100        ; wait for scan line 200
        BNE WAIT

Troubleshooting

  • My timer never expires. You used timer 1 or 3 while the OS was doing I/O, or the VBI is disabled (NMIEN cleared), so nothing decrements it.
  • Clock readings occasionally jump by 256. You read RTCLOK without the double-read check.
  • Durations are wrong in Europe. PAL machines run 50 frames per second. Detect it and scale.
  • The POKEY timer stops after loading a file. SIO changed AUDCTL and the AUDF registers. Re-run your setup.
  • Crash when the timer IRQ fires. Make sure the handler ends with PLA/RTI and preserves X/Y, and that you set the vector while IRQs were masked.

Further reading

  • De Re Atari (Atari, Inc., 1982), Chapter 8 "Real Time Programming", including the realtime clock and metronome listings.
  • Mapping the Atari by Ian Chadwick (Small System Services, 1983), locations 18–20 and 536–558.
  • Altirra Hardware Reference Manual (Avery Lee), Chapter 5: exact POKEY timer periods and IRQ behaviour.
  • On this site: POKEY sound basics and Vertical blank interrupts.

Credits