Skip to content →

opcode cycles and timings

So, to make our timer (and a lot of other stuff work), we need to be accurate with our cycles. Each opcode, takes a different amount of CPU-cycles to be executed (because of different actions it internally has to process).

Looking at izik’s GBops table again, we can see additional information, that we already stumbled upon, while implementing our opcodes. Each opcode has the timing information in the lower right corner. For example, the OR A, H instruction takes 1 M-Cycle. The CALL NZ, u16 instruction though, has a conditional timing value (if the condition is met, or not), of either 3 M-Cycles or 6 M-Cycles.

So, we have to alter our CPU.cpp once more, and let it return each timing value, once an opcode is executed. This would result in a CPU.cpp similar to this:

int processOpcode(uint16_t& pc, uint16_t& sp, Registers& registers, Flags& flags, int& interrupts_enabled) {
...

And an int main() similar to this structure by now:

//	start CPU
while (1) {
	if (unpaused) {
		//	step cpu if not halted
		if (!flags.HALT)
			cyc = processOpcode(pc, sp, registers, flags, interrupts_enabled);
		//	if system is halted just idle, but still commence timers and condition for while loop
		else
			cyc = 1;

		//	handle timer
		handleTimer(cyc);

		//	handle interrupts
		handleInterrupts();

	}
}
Note: The 'unpaused' variable is only, to be able to HALT the CPU, with the according opcode. Plus, later, we can make use of it, to just pause our emulation.

This way, we execute our opcodes, one after another, count our cycles, and handle our timer and interrupts accordingly. So far this is good progress, our CPU is almost done!

With these implementations, you should already be able to pass most (or all) of blargg’s test ROMs. To verify the correct cycle count and timing, I tuned and fixed my CPU until I was able to pass instr_timing.gb – a test ROM that is crucial to being able to emulate most of the commercial games.

Now, that we have an (ideally fully working) CPU, we finally want to see some output, something more appealing to the eye. So, now it is time for the first implementation of the PPU.

Comments

Leave a Reply