The Role of the Z80 CTC
The Z80 CTC (Counter/Timer Circuit) is a dedicated peripheral chip that provides four independent channels (Channel 0 to 3), each capable of acting as a counter or a timer. This chip is crucial for relieving the Z80 CPU of the burden of running software timing loops (Part 15).
Advantage: The CTC allows for precise, hardware-based timing that operates in the background, freeing the CPU to run main program logic.
CTC Communication Ports
The CTC typically occupies four consecutive I/O ports, one for each channel’s control and data:
Port | Channel | Function |
---|---|---|
0 | Channel 0 | Transfers data (time constant) and control words. |
1 | Channel 1 | Transfers data and control words. |
2 | Channel 2 | Transfers data and control words. |
3 | Channel 3 | Transfers data and control words. |
Initialization: Setting the Time Constant
To use a CTC channel as a timer, you write a Time Constant (a 1-to-256 value) to the channel’s port.
Timer Principle: The channel counts clock pulses from the Z80 (divided by a programmable factor, e.g., 16 or 256). When the count equals the Time Constant, the timer expires, an interrupt is generated, and the cycle repeats.
Example: Setting Channel 0 for a Timer
CTC_CHAN_0_PORT EQU 40H
INIT_TIMER:
; 1. Send Control Word (Mode/Interrupt Setup)
LD A, 93H ; Example control word for: Interrupt, Timer Mode, Prescale 16
OUT (CTC_CHAN_0_PORT), A
; 2. Send Time Constant (Determines the delay)
LD A, 100 ; Constant 100 (The timer will count down from 100)
OUT (CTC_CHAN_0_PORT), A
RET
Generating Interrupts
The CTC is often the primary source of time-based interrupts (e.g., 50 Hz VSync interrupts).
The Process:
- The timer expires, and the channel automatically generates an Interrupt Request (INT) signal to the Z80.
- In IM 2 mode, the CTC provides the specific Interrupt Vector Byte (Part 60) for that channel.
- The Z80 jumps to the dedicated Channel 0 ISR (Interrupt Service Routine).
Counter Mode
The CTC can also be configured to act as a Counter. Instead of counting the Z80’s clock pulses, the channel counts pulses arriving from an external hardware pin. This is used for measuring external events, such as the speed of a motor or the frequency of an incoming signal. The programming is identical to Timer Mode, but the control word selects the external clock input.