magenet

Monday, November 14, 2016

The MOS 6502, Part 2

Another important aspect we need to care of is the speed that the CPU reads the instructions at. The real hardware is ruled by a signal that pulses. This is called Clock. This signal is very important because in the majority of the systems all components are synchronized and can work together.

In an emulated system this signal doesn't exist really, but it's simulated by a repeated task that executes all the components of the system for a time unit. Something like:

1) Execute CPU.
2) Draw graphics.
3) Check the keyboard.
...
n) Other task.

Now, the program that emulates the CPU is called every n time units and executes a specific number of instructions. 

The instructions usually take a certain amount of time, measured in clock pulses. So for example a CPU can take 2 clock pulses to perform an addition. Or maybe 5 clock pulses to access the RAM and save a value. Every instruction take a certain amount of cycles. It's very important to count these cycles in order to keep the correct speed of the system that is emulated.

The Apple-1 was "Clocked" at 1,023 MHz, this means that in a second the system receives 1,023,000. So one pulse every 977 micro seconds. If we want to emulate this kind of speed we can't pretend that a micro controller executes the virtual CPU at this speed, we would need a very fast micro controller. What we need is to reduce the number of times the virtual CPU is executed, and let it execute more instructions at once.

So for example we can setup a repeated cycle that runs at 102,300 Hz, 1/10th of the original frequency:

Every 102,300
1) Execute 10 cycles of CPU.
2) ...
n) Other task.

We can keep track of the cycles executes with a simple global counter, and update it after each instruction executed.

Every 102,300
1) Execute 10 cycles of CPU:
     - Instruction 1: -2 clocks, still 8 to execute.
     - Instruction 2: -5 clocks, still 3 to execute.
     - Instruction 3: -5 clocks, Overflow, the counter goes negative -2 cycles

n) Other task.


In the previous call the virtual CPU has executed 2 clocks more than needed, so for the next call the two clocks are subtracted from the number of cycles to execute.

Every 102,300
1) Execute 10-2 cycles of CPU:
   ...

n) Other task.


It's very important to read the documentation of the system, and then the documentation of all the components that the system uses.