Carl
all lessons
The 6502, by doing Lesson 7 of 9

Timing with the VIA Timer

A delay loop wastes the CPU and times nothing accurately. The 6522 VIA has a real hardware timer (T1) ticking on its own crystal. Arm it, then poll its flag — the count now advances on a precise beat while you learn how peripheral registers work.

6502 assembly via timer hardware

The delay loop was honest but crude — it burns the CPU and its timing drifts with clock speed. Real hardware has a timer. The 6522 VIA’s Timer 1 counts down on the chip’s own 1 MHz crystal, independent of the CPU, and raises a flag when it hits zero.

Three register groups (the assembler names them): ViaACR picks the timer’s mode ($40 = free-running — reload and keep going), ViaT1C_* sets the count (writing the high byte arms it), and ViaIFR is the interrupt flag register — bit 6 (ViaT1Bit) goes high on underflow. BIT is the trick for reading it: BIT ViaIFR copies that bit straight into the V flag without disturbing A, so BVC can spin on it.

CodeLab — Count, paced by Timer 1
6502 source — stores to VIA Port B ($B000 = 8 LEDs)
loading…
assembler
VIA Port B — 8 LEDs (bit 7 … 0)
CPU
disassembly

Assemble, then Run: the same counter, but each step now lands on the timer’s beat instead of a guessed loop count. Open the disassembly and CPU panels — the count advances exactly when T1 fires. Reading ViaT1C_L would also clear the flag (the classic 65C22 “ack” trick); here we write ViaIFR explicitly so the mechanism is visible.

Try this: change the ViaT1C_H value ($40$10) and watch the beat speed up — you’re reprogramming a hardware timer in flight.

Next: instead of polling that flag, let the timer interrupt the CPU — and write your first interrupt handler.