NES Emulator: Instruction Cycle

Building off my last post detailing the various addressing modes the 6502 CPU uses for loading operands to assembly instructions, I would like to devote this post to the CPU instruction cycle as it relates to the NES Emulator. The instruction cycle has 3 core components: fetch, decode, execute. Each time the CPU wants to complete a new instruction, it will follow these 3 basic steps.

Fetch

  • The CPU has a register called the program counter (PC) that holds the 16 bit address of the next instruction to be executed. Once the address in the PC is fetched, the PC is incremented by 1 and now holds the next address to be fetched. It is important to immediately increment the PC after fetching the address, otherwise subsequent instructions could be incorrectly fetched. The data located at the first byte of the address in the PC is called the operation code, or simply opcode.

Decode

  • The 6502 CPU supports 151 opcodes that are grouped into 56 different assembly operations. The hexadecimal value of the opcode will range from 0x00 to 0xFF as represented by this table. However, not all 256 opcodes in this range are officially supported and most games can be played only implementing the 151 official opcodes. The table linked earlier has 8 rows and 32 columns, i.e. 256 entries. To decode which instruction goes with an opcode, read the hexadecimal opcode and find that entry in the table. For example, 0x00 is BRK. To implement this idea in code, one could use a long switch statement that matches the hex value with the assembly instruction. A lookup table or other data structure could be used as well. As mentioned in my previous post, the opcode can have a varied number of operands, so it is important in the decode stage to determine those operands so that they assembly instructions can be executed correctly.

Execute

  • Once the assembly instruction has been decoded from the opcode, it is now the CPU’s job to execute the instruction. Different instructions require a different number of CPU clock cycles to complete. The CPU clock ticks for every simple instruction, such as addition, and some opcodes require multiple simple instructions and can take up to 7 cycles. A detailed look what each opcode does and their clock cycles can be found here.

Once the CPU has executed the opcode, the next instruction is read from the PC and the whole instruction cycle begins again. Interestingly, the Picture Processing Unit that controls the game display completes 3 cycles for every 1 CPU cycle. The correct timing of the CPU and PPU is a difficult feat to achieve, and a future blog post will detail our group’s strategy.

*Sources:

  • https://wiki.nesdev.org/w/index.php/CPU_unofficial_opcodes
  • http://users.telenet.be/kim1-6502/6502/proman.html

Print Friendly, PDF & Email

Leave a comment

Your email address will not be published.