IRQ Programming

From F256 Foenix
Revision as of 08:25, 2 July 2025 by Minstrel Dragon (talk | contribs) (Basic IRQ handling (with the help of ChatGPT, some details may need additional reviewing))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Basic IRQ handling on the 6502

The 65C02 processor (or 65816 in compatibility mode) contains an interrupt system which allows for code to be executed outside the normal program flow on the occurrence of an external event. Such event can be the start of a new frame, the expiration of a VIA timer, reception of data on a serial input line etc.

Here is a short explanation of how an interrupt is handled:

1. IRQ Line Goes Low

  • The IRQ pin on the 6502 is active low.
  • When the IRQ pin is pulled low by a device and interrupts are enabled, the CPU will respond.

2. IRQ Timing

  • The CPU checks for IRQ at the end of each instruction cycle.
  • If IRQ is active and not masked, the CPU starts the interrupt sequence.

3. Interrupt Sequence

When an IRQ is accepted:

  1. Complete the current instruction.
  2. Push the Program Counter (PC) to the stack (2 bytes, high byte first).
  3. Push the Processor Status Register (P) to the stack.
  4. Set the Interrupt Disable (I) flag in the status register (to prevent nested IRQs).
  5. Read the IRQ vector from memory address $FFFE (low byte) and $FFFF (high byte).
  6. Jump to the address fetched from the IRQ vector.

4. Returning from Interrupt

  • The interrupt handler ends with the RTI (Return from Interrupt) instruction.
  • RTI does the reverse:
    • Pulls the status register from the stack.
    • Pulls the program counter (2 bytes) from the stack.
    • Resumes execution where it left off.