What is an Interrupt?
An interrupt is an external signal from a hardware device (like a timer or keyboard controller) that tells the CPU to immediately stop what it’s doing and execute a specific routine to handle the event. This is how the system maintains responsiveness.
The Two Key Commands:
Instruction | Action | Purpose |
---|---|---|
EI |
Enable Interrupts | Allows the CPU to listen for and respond to external interrupt requests. |
DI |
Disable Interrupts | Prevents the CPU from responding to external requests (used for critical code sections). |
The routine that handles the interrupt must end with RETI
(Return from Interrupt) or RETN
(Return from Non-Maskable Interrupt) instead of a simple RET
.
Z80’s Three Interrupt Modes
The Z80 supports three distinct ways to handle interrupt signals, configured using the IM
(Interrupt Mode) instruction.
1. Mode 0 (IM 0): External Instruction
The interrupting hardware must send an instruction byte (usually a RST
call) to the CPU, which the CPU then executes. This mode is system-dependent and rarely used in modern Z80 systems.
2. Mode 1 (IM 1): Fixed Restart
This is the simplest mode. When an interrupt is received, the CPU automatically performs a RST 38H
(a jump to address 0038H
).
IM 1 ; Set Interrupt Mode 1
EI ; Enable interrupts
; ... CPU waits for an interrupt ...
ORG 0038H ; The start of the interrupt handler
MY_HANDLER:
PUSH AF ; Always save registers immediately!
; ... interrupt service code ...
POP AF
RETI ; Return from Interrupt
3. Mode 2 (IM 2): Vector Table (Advanced) This is the most flexible mode. The CPU uses the I register (Interrupt Vector Register) and the byte supplied by the hardware to look up a 16-bit address in a vector table, allowing many different devices to share the same interrupt line.
Setup Commands:
LD I, Base_Address
IM 2
EI