Microcontroller Core Simulation Strategies


There are several reasons why you might want to write a simulator for a micro controller: education, debugging, legacy/preservation, or just fun.

Over the years I have felt the need for a bit of all of the above and I have published some of the results of such investigations. For example, in the category fun but also definitely legacy, I have written a simulator for the glorious Z80 microprocessor and the entire ZX Spectrum home computer (to run old “original” video games on a brand new PIC32 Mikromedia).

A simulator like that can be quite complex to “read”, the Z80 was not exactly a RISC machine with its 750+ individual instructions. For educational purposes I developed instead a PIC16 (baseline) simulator. Now that is RISC and it is quite simple code to follow, once more it is all C language for a PIC32. Several interesting things came out of that project: I discovered that although not optimised for speed the simulator could run two PIC16 in parallel (@4MHz) on a single PIC32 (@80MHz) proving once and for all that PIC16+PIC16 = PIC32!

But both the Z80 and the PIC16 simulator where written so to simulate code execution with the granularity of the instruction cycle (Tcy), without any regard for the actual way the microcontroller/processor instruction decoding and inner workings were actually implemented in silicon. More recent investigations of the Core Independent Peripherals design methodology (see the new Rocket Science book) drew my attention to the need to obtain a more accurate type of simulator. One that is capable of reproducing the behaviour of a (PIC16) microcontroller on a  cycle by cycle basis, reproducing each of the four Q cycles used by the core to execute each instruction.

So I set off to write a new simulator but this time I chose Python as the host language to add a little challenge to the project and to achieve a bit more portability across desktop platforms. Using solely the device data sheet as a source for hints of the internal architecture and silicon implementation details, the new cycle by cycle PIC16 (baseline) simulator turned out to be surprisingly compact and efficient.

Python is known to be quite expressive, but at the same time it is certainly not famous for its ability to describe the low level detail of a micro controller core.

By mimicking (or at least trying to stay closer to) the device internal architecture, the resulting application got reduced to half the number of lines of code while at the same time gaining in accuracy. With this new design it should be possible to add peripherals (core independent ones of course) and simulate very accurately the timing of the CLC macro blocks, the HLT and SMT timers and many more…


This entry was posted in PIC16, Python and tagged , , , . Bookmark the permalink.