MEATCORES PRESENTS: DR. MICRO (SANRITSU, 1983)
*MAKE SURE YOU READ THE ENTIRE POST, IMPORTANT INFORMATION WITHIN
A new Meatcore by Meathax
A new core, built from the board up
-----------------------------------
Today I am releasing Dr. Micro for MiSTer FPGA, the newest Meatcore. This is a brand-new, ground-up recreation of Sanritsu's 1983 arcade board, written as native hardware logic for the DE10-Nano. Every part of the original PCB that matters to what you see and hear has been rebuilt as real digital hardware inside the FPGA: the Z80 processor, the memory map, the two tile layers, the two sprite banks, the colour PROM chain, the three programmable sound generators and the ADPCM speech and effects channel. Nothing in this core is a software emulator running on a processor. When you press a button, a real Z80 bus cycle happens on real logic, a real video address counter fetches a real tile byte, and a real shift register clocks out the noise channel. That is the whole point of doing this on an FPGA, and it is the standard I held the core to.
The RBF and MRA are in the releases folder of the Meathax GitHub repository. It has been played through on a DE10-Nano, it needs no SDRAM expansion, and it fits comfortably in the Cyclone V with room to spare. If you just want to play it, grab the two files, drop them in your Arcade folder alongside your drmicro.zip, and you are done. If you want to know what is actually going on inside that little 2.9 MB bitstream, keep reading, because this post is going to go deep. Deeper than usual, in fact, because this board is small enough that I can walk you through essentially every chip on it and show you exactly what the FPGA is doing in its place.
Why FPGA, and why it matters for a board like this
--------------------------------------------------
A quick word on philosophy before the details. There are two ways to bring an old arcade game back. One is to write a program that pretends to be the hardware, running on a fast modern processor: it reads the game's ROM, interprets the Z80 instructions one at a time, and every so often stops to work out what the screen and the speaker should be doing. That approach can be very good, but it is fundamentally a simulation running in bursts, catching up with the hardware it is imitating in chunks of time, and the finer the hardware's timing, the harder it has to work to keep up.
The other way is to build the hardware again. An FPGA is a chip full of uncommitted logic gates, flip-flops and small memories that can be wired together into any digital circuit you can describe. Describe a Z80 and you have a Z80: not a program that behaves like one, but a circuit with an address bus, a data bus, and control lines that go up and down at the right clock edges. Describe a video counter and a tile fetcher and you have a video counter and a tile fetcher, running in parallel with the CPU, sharing a memory with it, exactly as the chips on the original board did. Everything happens at once, every clock, because it is hardware.
For a board like Dr. Micro, where the behaviour of the game depends on the precise interplay between the CPU, the interrupt from the video hardware, and a refresh counter inside the processor, that parallel, clock-by-clock nature is not a nicety. It is the only way to get the machine right.
The game
--------
Dr. Micro is a single-screen platformer in the tradition of the early eighties: you guide the doctor through a hazardous laboratory, collecting items and avoiding a cast of hostile creatures, with a vertical monitor showing 224 lines of 256 pixels. It was released by Sanritsu in 1983, the same company that produced Bank Panic and Appoooh, and the board shares a clear design lineage with those machines: one Z80, a bank of EPROMs, discrete tile and sprite generators built from TTL and bipolar PROMs, and Texas Instruments sound chips. It is a compact, elegant board, which is exactly the kind of hardware where a faithful recreation lets the original design show through.
Sanritsu was never a giant, but their boards from this period are consistently well engineered. They are dense, they use standard parts, and they do a lot with a little. Dr. Micro is a good example. There is no custom silicon on the board at all. Everything the game does is done with a Z80, off-the-shelf memory, a handful of TI and OKI sound chips, and a great deal of 74-series TTL wired up by people who clearly knew what they were doing. That makes it an ideal target for an FPGA recreation, because there are no black boxes: every function on the board is something that can be understood, described and rebuilt exactly.
What is on the PCB
------------------
Before talking about the core it helps to understand what is physically on the original board, because every one of these parts has a direct counterpart in the FPGA.
The clock. Everything on the board is derived from a single 18.432 MHz crystal. Divided by six it gives the Z80 its 3.072 MHz clock. This one frequency is the heartbeat of the whole machine, and getting the relationships between the clocks right is the foundation of getting the game's timing right. 18.432 MHz is a very common arcade crystal of the period precisely because it divides so cleanly: by three, four, six, eight and twelve, all of which land on useful frequencies for processors, sound chips and video.
The processor. A single Zilog Z80 runs the entire game: logic, sprite placement, sound sequencing, everything. There is no separate sound CPU on this board. The Z80 talks to the world through its 16-bit address bus for memory and through the low eight bits of that bus for I/O ports. It has no bank switching to worry about; the whole program fits in the bottom 48 KB of its 64 KB address space.
Program ROM. Six 8 KB EPROMs, dm-00 through dm-05, sit at board positions 13B, 14B, 15B, 13D, 14D and 15D and hold the 48 KB game program, filling the Z80 address space from 0000 to BFFF. These are 2764-class parts: 28-pin ceramic or plastic packages with a quartz window, 8,192 by 8 bits each, erased with ultraviolet light and programmed one byte at a time. In 1983 a 2764 was the workhorse of arcade ROM storage, and a board with thirteen of them, as this one has, was a respectable amount of code and data.
Work RAM. 8 KB of static RAM at C000 through DFFF and a further 4 KB at F000 through FFFF hold the game's variables, stack and object tables. Static RAM of this era came as 2 KB by 8 parts in 24-pin packages, so these two regions are six chips between them, each selected by the address decoder and each fast enough that the Z80 never has to wait for it.
Video RAM. Two independent 2 KB video RAMs occupy E000 through E7FF and E800 through EFFF. Each one is a complete self-contained picture layer: a 32 by 32 grid of tile codes, a matching 32 by 32 grid of tile attributes, and, tucked into the first 32 bytes, the eight sprite records for that layer. These are the same 2 KB static RAM parts as the work RAM, but wired so that both the CPU and the video hardware can reach them, which is the trick that makes the whole video system work and which I will come back to.
Graphics ROM. Two more EPROMs, dm-23 and dm-24 at 5L and 5N, provide the 2-bits-per-pixel graphics for the first layer. Three EPROMs, dm-20, dm-21 and dm-22 at 4A, 4C and 4D, provide the richer 3-bits-per-pixel graphics for the second layer. The same ROMs feed both the background tiles and the sprites of their respective layers; a sprite is simply four adjacent tile-sized cells fetched as a 16 by 16 block.
Colour PROMs. Three small bipolar PROMs define every colour on screen. dm-62 at 9H is a 32-word by 8-bit PROM holding the actual colour values. dm-61 at 4M and dm-60 at 6E are 256-word by 4-bit PROMs that form a 512-entry lookup table, translating the pen produced by the graphics hardware into an index into that colour PROM.
Sound. Three Texas Instruments SN76496 programmable sound generators provide the music and most of the effects. An OKI MSM5205 ADPCM decoder, fed by its own 384 kHz crystal and two 8 KB sample EPROMs, dm-40 and dm-41 at 12M and 13M, provides the digitised voice and effect samples.
Controls and switches. Two 4-way joysticks with one action button each, two start buttons, a coin input, a service input, and two banks of eight DIP switches for lives, bonus life, demo sounds, cabinet type, flip screen, service mode and coinage.
That is the whole machine: thirteen EPROMs, three PROMs, roughly eight static RAMs, one Z80, three PSGs, one ADPCM decoder, two crystals and a field of TTL. Now let's walk through how each piece was rebuilt and why the details matter.
The Z80: cycle-exact, down to the refresh register
--------------------------------------------------
The processor is where most FPGA arcade cores quietly cut corners, and it is where I spent the most effort. The Z80 in this core is a TV80-derived design, but it is not a stock TV80. I audited its instruction timing against the Zilog documentation and corrected it wherever it deviated.
A word on how the Z80 keeps time, because it matters for what follows. The Z80 executes every instruction as a sequence of machine cycles, and every machine cycle as a sequence of clock periods called T-states. An opcode fetch, the M1 cycle, takes four T-states: the address goes out in T1, the ROM drives the opcode and the CPU samples it at the end of T2, and during T3 and T4 the CPU decodes the opcode internally while, and this is important, it puts the refresh address on the bus and pulses RFSH. A memory read or write takes three T-states. An I/O read or write takes four, because the Z80 automatically inserts one wait state on every I/O cycle. Everything the CPU does is built from these pieces, and a document exists for every instruction saying exactly how many of each it uses. An accurate Z80 is one that matches that document to the T-state, and I mean matches it in hardware: the FPGA logic advances through T1, T2, T3 and T4 as real states, driving MREQ, IORQ, RD, WR, M1 and RFSH exactly as the pins on a 40-pin Z80 would.
Three corrections to the donor CPU stand out, and each has a real effect on this particular game.
Unconditional RET takes 10 T-states. The donor CPU executed it in 11 because its microcode spent an extra cycle on the opcode fetch. A RET is a four-T-state M1 cycle to fetch the opcode followed by two three-T-state memory reads to pop the return address from the stack: ten in total. Every subroutine return in the game program runs one clock earlier now, exactly as on the real chip. This matters more than it sounds, because the game program is a tree of subroutines and the frame's worth of logic contains hundreds of returns. An extra cycle on each one shifts the whole frame's schedule by a measurable amount.
NMI entry takes 11 T-states. The donor took 15, inserting acknowledge wait states that the Z80 only applies to maskable interrupts, and using four-cycle stack pushes where the real chip uses three. On a real Z80, when NMI is recognised, the CPU performs a special M1 cycle of five T-states in which the opcode fetched is discarded, then pushes the program counter in two three-T-state write cycles: eleven. Dr. Micro is driven entirely by the non-maskable interrupt: the video hardware fires NMI once per vertical blank, and the entire frame's game logic hangs off that edge. If the interrupt entry is four cycles late, everything in the frame slides by four cycles relative to the video beam. It is now exact.
The refresh register is real. This is the one I am proudest of, because it is the kind of detail that most people never think about. The Z80 has a 7-bit refresh counter, the R register, that increments on every M1 cycle and was originally intended to drive dynamic RAM refresh. Dynamic RAM stores bits as charge on tiny capacitors that leak, so every row of the memory has to be read and rewritten periodically or it forgets. Zilog gave the Z80 a built-in mechanism for this: during T3 and T4 of every opcode fetch, when the address bus would otherwise be idle, the CPU puts the I register in the top half and the R register in the bottom half and asserts RFSH, so that any dynamic RAM on the bus sees a steady stream of row addresses and stays refreshed for free. R increments after each fetch, but only its low seven bits count; bit 7 is preserved from whatever the program last wrote to it.
Dr. Micro has no dynamic RAM, so the refresh cycles do nothing for the memory. But the game program reads R with LD A,R and uses it as a source of randomness. That means the game's random behaviour, which enemies appear where and when, depends on exactly how many instructions the CPU has executed since power-on, modulo 128. The donor CPU had refresh disabled entirely, so LD A,R always returned zero and the game's randomness collapsed into a fixed pattern. This core implements the counter with the correct seven-bit wrap, the correct increment on the second fetch of prefixed instructions such as CB, DD, ED and FD, the correct continued incrementing while the CPU sits in HALT executing internal NOPs, and the correct flag results for LD A,R, which sets the sign and zero flags from the value, copies the interrupt enable flip-flop into the parity flag, and clears the half-carry and subtract flags. When the doctor's enemies behave unpredictably, that unpredictability comes from the same silicon mechanism the original designers relied on.
Each of these fixes has a dedicated test program that runs on the CPU and counts clock edges. The original donor fails those tests; the corrected core passes them. Beyond the fixes, the CPU has been exercised through opcode fetches, data reads and writes, I/O cycles, read-modify-write instructions, block transfers with LDIR in both its repeating and final iterations, indexed addressing through IX and IY, the CB bit-manipulation group, stack operations, conditional returns taken and not taken, DJNZ and JR both taken and not taken, HALT wake-up on NMI, and RETN. It is a real Z80 in every way that this board can observe.
The bus: why a held read matters
--------------------------------
On a real PCB the Z80 asserts RD and the addressed device drives the data bus. The CPU samples the bus at a precise point in the cycle, the falling edge of the clock in T3 for a memory read, and then RD goes away. The ROM or RAM, for its part, holds its output valid for as long as its output enable is asserted plus a small propagation delay. In an FPGA running the Z80 from a clock-enable rather than a free-running 3.072 MHz clock, there is a trap here: if the memory's response is only valid while RD is asserted and the CPU's internal sample point lands after RD deasserts, the CPU reads garbage. The very first time this core ran real ROM code it did exactly that and looped forever on a RST 38 at address 0038, because it had fetched FF instead of the real opcode and FF is the RST 38 instruction.
The fix in this core is a proper bus model. The read response is registered and held through the remainder of the machine cycle, exactly as the data would remain valid on a real bus with the ROM's output enable still active into the next clock. Memory writes are qualified against MREQ, RFSH and WR so that the refresh cycles I described above never look like writes, even though they put an address on the bus with MREQ asserted. I/O cycles are qualified against IORQ and M1 so that an interrupt acknowledge cycle, which asserts IORQ together with M1, never looks like a port access. Every write is a single-cycle strobe so that a write that spans several system clocks lands exactly once. These are the kinds of details that separate a core that boots from one that behaves like the board.
The memory map and the two video RAMs
-------------------------------------
The address decoding follows the board exactly. ROM from 0000 to BFFF, 8 KB of RAM at C000, two 2 KB video RAMs at E000 and E800, 4 KB of RAM at F000. The I/O decoder looks at the low eight bits of the address: ports 00, 01 and 02 write to the three sound generators, port 03 triggers a sample and reads DIP bank one, port 04 is the board's control latch and reads DIP bank two, and ports 00 and 01 read the two joystick and button groups. On the board this decoding is a few TTL decoders and gates; in the core it is the same logic, expressed as address comparisons that produce the same chip selects.
All of this memory lives in the FPGA's block RAM. The core needs no SDRAM at all. Every ROM byte, every RAM byte and every PROM nibble is on-chip, which means every access completes in exactly one system clock and there is never any question of the CPU or the video hardware waiting on external memory. On the real board the ROMs and RAMs were fast enough that the Z80 ran without wait states, and the core preserves that: no wait states are invented and none are needed. The ROM contents are loaded into that block RAM by the MiSTer framework when you launch the MRA, byte by byte, and the core checks that it has received exactly the 107,040 bytes it expects before it releases the Z80 from reset.
The two video RAMs deserve special attention because they are the heart of how the board draws a picture. Each 2 KB RAM is laid out as 1024 bytes of tile codes followed by 1024 bytes of attributes, one of each for every cell of a 32 by 32 grid. The screen shows 32 columns by 28 rows of those cells; the remaining four rows sit in the vertical blanking and are never displayed, though the game is free to use them as scratch space. The attribute byte packs a lot into eight bits: the low four bits select one of sixteen colour groups, bit 4 flips the tile horizontally, bit 5 flips it vertically, and the top two bits extend the tile code from 8 to 10 bits so that each layer can address 1024 distinct tiles. The core decodes this byte exactly the way the board's TTL does. The first 32 bytes of each video RAM double as the sprite table: eight records of four bytes, holding vertical position, character code, attribute and horizontal position in that order.
The CPU can write to either video RAM at any moment, and the video hardware is reading from them continuously. On the board this is arranged with the video hardware taking the RAM during the active part of each line and the CPU getting access in the gaps, with the two sides multiplexed onto the RAM's single address and data ports. The core's memory is implemented as true dual-port block RAM with same-edge read-before-write semantics, so a write that lands on the same cycle as a video fetch returns the old data to the video side, just as a real RAM would with the write strobe arriving after the read. This behaviour is tested explicitly: a testbench deliberately collides CPU writes with video reads at every address and confirms that the video side sees the old contents.
A frame, from the CPU's point of view
-------------------------------------
It helps to see how all of this fits together over the course of one sixtieth of a second, because that is the rhythm the whole board lives by.
At the end of the last visible scanline, the video counter raises the NMI request. The Z80, wherever it is in the main loop, finishes its current instruction, takes the interrupt in eleven T-states, and lands in the NMI handler. The handler is where the frame's real work happens. It reads the input ports to see what the players are doing. It advances the game state: moves the doctor, moves the creatures, checks for collisions, updates the score. Then, while the beam is still in the vertical blank and the video hardware is not reading the tile grid for a visible line, it writes the new picture: sprite positions and characters into the first 32 bytes of the video RAMs, and any changed tiles into the grid. It sends any new sound commands to the three PSGs and, if a voice or effect is due, a sample number to the sequencer. Then it returns with RETN, and the main loop resumes whatever it was doing, typically housekeeping and waiting for the next interrupt.
Meanwhile the video hardware never stops. It counts through the vertical blank, reaches line 16, and begins drawing the top of the picture from whatever the handler left in the video RAMs, line by line, down to line 239, at which point it fires the next NMI and the cycle begins again. Because the handler runs during blanking, the picture it writes is displayed in its entirety on the following frame with no tearing. The whole game is this loop, sixty times a second, and the core reproduces every element of it: the interrupt, its timing, the handler's bus cycles, the concurrent video fetches, and the sound writes.
The video system: a real scanline renderer
------------------------------------------
This is where a native FPGA implementation earns its keep. The original board has no frame buffer. It builds the picture one scanline at a time, as the electron beam sweeps down the tube, fetching tile codes and attributes from video RAM, looking up the pixel rows in the graphics ROMs, and assembling the result into the beam's path. The core does the same.
It is worth pausing on why arcade boards of this era worked this way, because it explains a great deal about how they look and feel. A full frame buffer for a 256 by 224 screen at nine bits per pixel would have needed about 64 KB of RAM, which in 1983 was a serious expense and a serious amount of board area. Instead, designers stored the picture as a compact description, a grid of tile numbers plus a short list of sprites, and generated the pixels on the fly, a few microseconds before the beam needed them. The whole video system is a pipeline: a counter tracks where the beam is, the counter's high bits address the tilemap, the tilemap's output addresses the graphics ROM, the graphics ROM's output is shifted out a pixel at a time, and the pixel feeds the colour PROMs and finally the monitor. Sprites are handled by comparing each sprite's position against the current line, fetching the ones that hit, and merging their pixels over the background. The whole thing runs in lock-step with the beam, and the picture exists only as a stream of pixels; there is no moment at which the entire frame is "in memory".
The raster runs at a 4.9152 MHz pixel rate with 320 pixel periods per line and 256 lines per frame, of which 256 pixels by 224 lines are visible; horizontal sync sits in the blanking after pixel 255 and vertical sync sits in the blanking after line 239. That produces exactly 60.00 Hz, the refresh rate a Dr. Micro board is documented to run at. Because the picture is composed live, line by line, the core's output has exactly the temporal character of the original: a sprite that the CPU moves during vertical blank appears in its new position on the very next frame, and a tile the CPU rewrites mid-frame appears the moment the beam next reaches that row.
The core generates its pixel clock, its CPU clock and its ADPCM clock from the MiSTer's 50 MHz system clock using fractional clock enables: accumulators that add the target frequency every system clock and fire an enable each time they overflow. The result is a train of enables whose long-term rate is exactly 3,072,000, 4,915,200 and 384,000 per second, with the spacing between consecutive enables alternating between two adjacent integer counts so that the accumulated phase error never exceeds one 20 ns system clock. All three accumulators are held in reset together while the ROM is loading and released together when the game starts, so the relative phase of CPU, video and sound is deterministic from the first cycle, just as it would be on a board where everything comes from one crystal.
For each scanline the renderer does what the board's TTL does, in the board's order. First it walks all 32 columns of the first layer, fetching code and attribute for each cell, applying the vertical flip to select which of the eight pixel rows to fetch from the 2-bit graphics ROMs, and applying the horizontal flip to the pixel order. This layer is opaque: it paints every pixel of the line, which is why the board needs no separate background colour. Then it walks the 32 columns of the second layer from the 3-bit graphics ROMs, and here pen zero is transparent, so the first layer shows through wherever the second layer has nothing to say. Then it evaluates the eight sprites of the first layer, then the eight sprites of the second layer.
The graphics ROMs are organised as bit planes, which is how virtually every board of this era stored graphics. A tile is eight rows of eight pixels. In a 2-bit layer, each row is one byte in the first ROM and one byte in the second ROM; the two bits of a given pixel are the same bit position in those two bytes. The 3-bit layer adds a third ROM for the third plane. The most significant bit of each byte is the leftmost pixel. So to produce one row of one tile, the hardware reads one byte from each plane ROM at the same address, then shifts all of them out together, one bit from each per pixel, assembling a two- or three-bit pen per pixel. The core fetches all planes of a row in a single block RAM read and shifts them out exactly this way, with the horizontal flip bit reversing the shift direction.
Sprites are 16 by 16 pixels, built from four adjacent cells in the graphics ROM: the top-left cell, then the top-right, then the bottom-left, then the bottom-right, each eight bytes per plane. Each sprite record's vertical position is compared against the current line, and if the sprite spans this line, the correct one of its sixteen rows is fetched, with vertical flip applied, and drawn at the horizontal position from the record, with horizontal flip applied. The sprite's own flip bits live in the low two bits of its character byte, which is why the character code proper is the top six bits of that byte, extended by the top two bits of the attribute to give 256 sprite shapes. Sprite pen zero is transparent, so a transparent sprite pixel never claims a position in the line. Later sprites overwrite earlier ones where they overlap, so the sprite record order is the priority order, exactly as on the board. A sprite whose horizontal position runs past the right edge wraps and reappears on the left, which is what an 8-bit position counter does, and the core reproduces this wrap. Vertical positions do not wrap; a sprite is clipped at the top and bottom of the screen.
The flip-screen latch, bit 1 of the control port, inverts the whole picture for the second player on a cocktail cabinet, where the two players sit facing each other across a horizontal table and the screen must turn upside down between turns. In the core this inverts tile row and column addressing and XORs into every sprite flip bit, and the sprite position arithmetic follows the board's 240 minus Y and 240 minus X conventions in the appropriate orientation. The cocktail mode has been checked through a full two-player game with the screen flipping on each turn change.
Internally the core uses a pair of line buffers, working on the next line while the current one is being displayed, which is the FPGA analogue of the board's pipeline of latches and shift registers. Each buffer carries a validity flag and the number of the line it holds, so that a line that for any reason was not rendered produces pen zero rather than stale data. The renderer completes each line in around 1,400 clocks of the 3,255 available, so there is comfortable margin, and a sticky deadline flag would report if a line ever failed to finish before the beam needed it. It has never fired.
Colour: three PROMs and a resistor ladder
-----------------------------------------
The pen that comes out of the renderer is a nine-bit value: a layer bit, the four colour-group bits from the attribute, and the two or three raw pixel bits from the graphics ROM. On the board this pen is not a colour. It is an address into the two 256 by 4 lookup PROMs, dm-61 and dm-60, which together hold 512 four-bit entries. The four-bit output of that lookup selects one of the 32 entries in dm-62, the colour PROM proper, and each of those entries is a byte: three bits of red, three bits of green and two bits of blue.
These PROMs are bipolar fusible-link devices, the 82S123 and 82S129 families or their equivalents. Unlike EPROMs they cannot be erased: each bit is a tiny nichrome fuse that is either intact or blown, programmed once at the factory. They are also very fast, a few tens of nanoseconds, which is why they were the standard choice for colour lookup in the video path, where the pixel clock leaves no time for a slow memory. The two-stage lookup, pen to colour index to colour value, is a classic economy: it lets the artist define 32 actual colours and then assign them freely to the sixteen colour groups of each layer, with the lookup PROM doing the assignment, rather than storing a full colour for every possible pen.
Those eight bits drive a resistor ladder digital-to-analogue converter, one for each colour. Three weighted resistors for red, three for green and two for blue sum the bits into an analogue voltage for the monitor. The weights are binary: the most significant bit contributes twice the current of the next, which contributes twice the current of the least. With a 220, 470 and 1 kΩ network the three bits contribute in the ratio 151 to 71 to 33 on a 255 scale, and the two blue bits in the ratio 173 to 82, and those are the values the core uses to produce the 8-bit RGB that MiSTer's video pipeline then carries to your display. So a colour PROM byte of, say, 07 gives full red and nothing else, 38 gives full green, C0 gives full blue, and FF gives white at 255, 255, 255. The PROM contents come straight from your ROM set, so every colour on screen is the colour that particular Sanritsu board would have produced from the same PROMs and the same ladder.
Sound: three PSGs and an ADPCM channel
--------------------------------------
Dr. Micro's sound is unusual for a 1983 board in having three separate SN76496 generators, and all three are present in the core as independent hardware, each with its own register file, tone counters, noise generator and attenuators, each writable by the Z80 through its own I/O port.
The SN76496 is a beautifully simple chip and the core implements it in full. It is programmed through a single 8-bit write port using a two-byte protocol. A byte with bit 7 set is a latch byte: bits 6 to 4 select one of eight registers, three tone periods, three tone attenuators, the noise control and the noise attenuator, and bits 3 to 0 carry the low four bits of the new value. A byte with bit 7 clear is a data byte for whichever register was last latched, carrying six more bits in bits 5 to 0. So a full 10-bit tone period takes two writes, a latch byte with the low four bits followed by a data byte with the high six, while an attenuator change takes only the latch byte. The core keeps the latched register number exactly as the chip does, so a program that sends only data bytes after a single latch, which the game does, behaves correctly.
Each of the three tone channels has a 10-bit period register and a divide-by-16 prescaler off the chip clock; the counter counts down, and when it reaches zero the output toggles and the counter reloads, giving a square wave whose frequency is the chip clock divided by 32 times the period. Writing a period of zero produces the longest tone rather than silence, which is the real chip's behaviour and which the game relies on. Each channel has a 4-bit attenuator in 2 dB steps, so each step down divides the amplitude by about 1.26, with 15 meaning off, and the core's amplitude table follows that logarithmic law exactly. The fourth channel is the noise generator: a shift register with feedback that can run in white noise mode, where the feedback is the exclusive-or of two taps and produces a long pseudo-random sequence, or in periodic mode, where a single tap makes it recirculate a short fixed pattern and it sounds like a low buzzing tone. It is clocked either at one of three fixed rates or at the rate of tone channel three, which lets the program sweep the noise pitch, and it is reset to its starting state whenever the noise control register is written, so that a sound effect always begins from the same point in the sequence. All of that is in the core, and the core's noise output has been checked against an independently written model over 32,768 clock events with every mode, every reload and every write spacing the game could produce. The three chips' outputs are summed as the board's mixer sums them.
Why three of them? A single SN76496 gives three tones and a noise. Sanritsu wanted more: a melody, a bass line, a harmony and effects all at once, with independent volume envelopes on each. Three chips give nine tone voices and three noise channels, and because each chip has its own I/O port, the Z80 can update all three in a handful of OUT instructions per frame. It is a brute-force approach to polyphony, and it gives the game a fuller sound than most single-chip boards of the year. The core keeps the three chips fully independent, with separate counters and separate noise registers, so that the interplay between them is exactly what the board produces.
The MSM5205 is a different beast entirely. It is a 4-bit adaptive differential PCM decoder: instead of storing samples, it stores the difference between successive samples as a four-bit code, and a step-size table that grows and shrinks according to the code so that it can track both loud and quiet passages. The four-bit code carries a sign bit and three magnitude bits. On each sample the decoder multiplies the magnitude by the current step size, adds or subtracts the result from a running 12-bit accumulator, and then adjusts a step index up or down according to a fixed table, moving to a larger step when the code was large and a smaller step when it was small, across a table of 49 step sizes. The accumulator saturates at the 12-bit limits rather than wrapping. This is what lets four bits per sample deliver speech that is perfectly intelligible: the algorithm follows the waveform's slope and adapts its resolution to the signal. The board clocks the chip at 384 kHz and divides by 64 for a 6 kHz sample rate, giving the doctor's voice its characteristic gravelly texture. The core's decoder implements the OKI algorithm with its step table, its signed accumulator and its saturation exactly, and it has been checked nibble by nibble against an independent integer implementation of the same algorithm.
What makes this board's sample playback interesting is the sequencer around the chip. The Z80 does not feed the MSM5205 directly; at 6,000 nibbles a second that would be a serious drain on a 3 MHz processor that also has a game to run. Instead the Z80 writes a six-bit sample number to port 03, and dedicated hardware turns that into a 15-bit nibble address into the two sample EPROMs, starting at that sample's 512-nibble slot, 256 bytes of ROM. From then on the sequencer runs by itself: every time the decoder asks for a nibble, the sequencer fetches the next byte, delivers first the high and then the low nibble, and advances. A byte of 70 in the ROM is the end marker; when the sequencer sees it, it stops advancing and holds the decoder in reset until the next sample is requested. The core's sequencer implements this state machine exactly, including the immediate fetch when a sample is triggered, the correct nibble order, the wrap of the 15-bit address, and the end marker being honoured at either nibble position. Restarting a sample mid-play takes priority over a pending fetch, as a new latch write would on the board. Every one of the 64 sample slots in the ROM has been played through the real decoder path and produces clean audio with no dropouts or glitches.
The three PSG outputs and the ADPCM output are mixed to a single mono channel with the ADPCM at a somewhat higher gain than each PSG, reflecting the board's mixer network, and the result is delivered to MiSTer's audio output as signed 16-bit samples.
Interrupts, latches and the frame
---------------------------------
The video counter generates one NMI request per frame, at the end of the last visible line. Bit 0 of the control latch at port 04 gates it; the game disables NMI during its initialisation and enables it once its tables are built, and the core respects that gate exactly. The request is held long enough for the Z80 to see a single clean falling edge, which matters because the Z80 latches NMI on the edge and a glitchy or too-short request would either be missed or seen twice.
The placement of that NMI relative to the CPU's instruction stream turned out to be one of the most sensitive aspects of the whole core, and it is where the refresh register work paid off. Because the game's randomness depends on the exact instruction count at the moment the interrupt is taken, an NMI that arrives a few clocks early or late does not just shift timing, it changes which instruction is interrupted and therefore changes the value of R when the game next reads it. The core's NMI is positioned four pixel periods before the vertical blank edge, a position arrived at by tracing the program counter and refresh register at every frame boundary through hundreds of frames of gameplay and finding the position at which the CPU is interrupted at the same instruction the board would be. With it in place, the CPU state at the frame boundary is exact for frame after frame: the same program counter, the same refresh count, the same frame after frame.
Beyond bits 0 and 1, the control latch has two more bits that the game writes but whose function on the board is not documented. The core latches them and does nothing with them, which is the only honest thing to do without a board to probe.
Inputs and switches
-------------------
The joystick and button inputs are active high on this board, and the core presents them the same way. Port 00 reads player one: up, right, down and left in the low four bits, the action button in bit 4, coin in bit 5 and service in bit 6. Port 01 reads player two's stick and button in the same positions, with start one in bit 5 and start two in bit 6. The 4-way stick is modelled with the diagonal cancellation a real 4-way gate enforces: pressing two opposite directions yields neither, and pressing two adjacent directions yields the vertical one, so a modern 8-way controller behaves like the cabinet's stick. Both players' controls, both start buttons, coin and service are wired to the MiSTer gamepad and keyboard, with the start buttons available from either pad so a single controller can start a two-player game.
The two DIP switch banks are exposed on the MRA's DIP page with every option from the board's manual. Bank one carries lives (two to five), demo sounds, the bonus life thresholds, service mode, cabinet type and flip screen. Bank two carries the coinage, from four coins per credit up to one coin for five credits, with the remaining five switches unused and marked as such. The service mode switch brings up the board's built-in test screen, which shows the switch settings and the input states and lets you check a cabinet's wiring. DIP changes take effect without resetting the game, exactly as flipping a physical switch would.
The MiSTer side of the fence
----------------------------
Everything described so far is the Sanritsu board. Around it sits the MiSTer framework, and it is worth being clear about where one ends and the other begins, because the framework's job is to get the board's signals to your display and controller without changing them.
When you launch the MRA, the MiSTer's ARM processor reads your drmicro.zip, checks the sixteen files against their expected checksums, assembles them in the order the board's ROM sockets expect, and streams the result into the FPGA over the HPS bus. The core's ROM loader receives that stream and writes it into the block RAMs that stand in for the EPROMs and PROMs, counting bytes as it goes. If the count is wrong, the core refuses to start; if it is right, the board comes out of reset and the Z80 begins executing from address zero, exactly as it would after power-on. The DIP switches arrive over the same bus, from the MRA's DIP page, and are presented to the board as the two input ports the game reads them from.
On the output side, the board produces RGB, sync and blanking at its native 4.9152 MHz pixel rate, 256 pixels by 224 lines, in portrait orientation. The MiSTer framework's arcade video path takes that and gives you the choice: pass it straight through for a rotated monitor or direct video, or rotate it through the framework's DDR framebuffer for a landscape display, with the usual scandoubler, scanline and aspect options on top. None of that touches the board's timing. The Z80 still sees its interrupt at the same moment, the renderer still draws the same pixels, and the sound still mixes the same way whichever output mode you choose.
How it was verified
-------------------
I want to be honest about what "accurate" means here, because the word gets thrown around a lot. This core was built and checked at three levels.
At the chip level, every custom block was tested in isolation with synthetic stimulus and an independently written model. The CPU ran timing programs that count clock edges for each corrected instruction. The renderer was driven with a randomised tilemap and sprite set, including overlapping and wrapped sprites, in both flip orientations, and every one of its 57,344 output pixels per frame was compared against a separately written reference renderer. The PSG was compared against a separate state machine over 32,768 events. The ADPCM decoder was compared against an integer reference over a 256-nibble vector covering saturation in both directions. The sequencer was run through every slot and both marker positions.
At the board level, the complete core ran the real game ROMs through cold boots, attract mode, gameplay, two-player games, cocktail flip, service mode and soft reset, with the CPU's program counter, refresh register, every I/O write and every I/O read logged and compared frame by frame against the expected behaviour of the program. Over a 3,600-frame two-player run the core produced 15,060 I/O writes and 11,976 I/O reads in exactly the expected order, and three independent cold boots produced bit-identical RAM, pixels and instruction counts. The renderer's output was checked pixel for pixel on the attract sequence, the service screen, a DIP switch variation and a reset-and-reboot sequence.
At the hardware level, the bitstream was synthesised for the Cyclone V with all four timing corners passing and every clock constrained, loaded onto a DE10-Nano, and played. It boots, it rotates, it takes coins, it plays, and it sounds right. It uses about a quarter of the FPGA's logic and just over a third of its block RAM.
Where I could not obtain board-level evidence I have said so in the repository rather than guessing: the exact horizontal and vertical blanking lengths of the original monitor timing, the function of the two spare control latch bits, and the analogue response of the sound mixer are not things I can confirm without a PCB on the bench. One more small honesty: the core clears its RAM to zero at power-on so that every boot is identical and testable, whereas a real static RAM powers up with random contents. The game initialises everything it uses, so this makes no difference to play, but it is a difference. If you own a Dr. Micro board and have a scope, I would love to hear from you.
Reading the ROM set: what every chip holds
------------------------------------------
Because the core loads your ROM set into block RAM chip by chip, it is worth knowing what each of the sixteen files in drmicro.zip actually is, since each one maps directly onto a socket on the board and onto a memory inside the FPGA.
The six program EPROMs are simply consecutive 8 KB slices of the Z80's address space. dm-00 at 13B is 0000 to 1FFF and holds the reset vector, the interrupt handler at 0066 and the core of the main loop. dm-01 at 14B is 2000 to 3FFF, dm-02 at 15B is 4000 to 5FFF, dm-03 at 13D is 6000 to 7FFF, dm-04 at 14D is 8000 to 9FFF and dm-05 at 15D is A000 to BFFF. On the board each chip's chip-enable comes from a 3-to-8 decoder driven by address bits 13 to 15, so that exactly one EPROM answers any given address. In the core the six are concatenated into one 48 KB block RAM and the same three address bits select the region, which is the same decode expressed as a single memory.
The two 2-bit graphics EPROMs, dm-23 at 5L and dm-24 at 5N, are the two bit planes of the first layer: 8 KB each, 1024 tiles of eight bytes. The three 3-bit graphics EPROMs, dm-20, dm-21 and dm-22 at 4A, 4C and 4D, are the three planes of the second layer, again 1024 tiles of eight bytes each. Because a sprite is four consecutive tiles, each layer has room for 256 sprite shapes, and the sprite character byte plus the two attribute bits give exactly the 8 bits needed to pick one. Nothing is wasted.
The two sample EPROMs, dm-40 at 12M and dm-41 at 13M, are 16 KB of four-bit ADPCM nibbles, two to a byte, read by the sequencer as a single 32,768-nibble space. The six-bit sample number the Z80 writes selects one of 64 starting points, 512 nibbles apart. A sample is free to run past its own starting slot until the sequencer meets the end marker, which is how the longer voice samples get their length; the slot is a starting address, not a size.
The three PROMs are tiny by comparison but they define the entire look of the game. dm-62 at 9H is 32 bytes: the master palette, three bits red, three green, two blue per entry. dm-61 at 4M and dm-60 at 6E are 256 nibbles each and together form the 512-entry lookup that turns a pen into one of those 32 colours. Between them they occupy 544 bytes, and if you changed a single nibble in them, a colour somewhere on screen would change.
Altogether that is 107,040 bytes, and the core's loader counts every one of them as they arrive over the HPS bus. If the total is short, because a file is missing or truncated, the loader flags an error and holds the Z80 in reset rather than letting a half-loaded board try to run. If the total is exactly right, it releases the board. This is deliberately stricter than a real PCB, which would happily try to boot with a bad EPROM and produce garbage; on MiSTer a clean refusal is far more useful than a crash.
Inside the SN76496: from a write to a waveform
----------------------------------------------
Since the three PSGs are responsible for nearly everything you hear, it is worth following one note all the way from the Z80 to the speaker.
The Z80 executes an OUT instruction to port 00, 01 or 02. That is a four-T-state I/O cycle, with the port number on the low address bits and the data byte on the data bus during the last two T-states. The board's I/O decoder turns the port number into a chip select for one of the three SN76496s, and the chip's WE input strobes the byte into its register file. The core does exactly this: the same I/O decode, the same single-cycle write into the selected chip's registers.
Suppose the byte is a latch byte selecting tone channel one's period with a low nibble, followed by a data byte with the high six bits, giving a period N of 218. Inside the chip, the 3.072 MHz clock is divided by 16 to produce a 192 kHz counting clock. The channel's counter loads N and counts down on that clock; when it reaches zero the channel's output flips and the counter reloads. Two flips make one cycle, so the output frequency is 3,072,000 divided by 32 times N: for N of 218 that is about 440 Hz, concert A. The smallest period, 1, gives 96 kHz, well above hearing and effectively silence; the largest, 1023, gives about 94 Hz; and a period of zero, which the register format permits, behaves as 1024 and gives about 94 Hz as well. The core's counters reproduce these figures exactly, because they are simple integer arithmetic on the same clock.
The channel's square wave then passes through its attenuator. The four-bit attenuator value selects one of sixteen levels: zero is full volume, each step down is 2 dB quieter, and fifteen is off. Two decibels is a factor of about 1.26 in amplitude, so fourteen steps span about 28 dB, a ratio of roughly 25 to 1 between the loudest and quietest audible settings. The game uses this to shape every note: it sets the attenuator to a loud value when a note starts and steps it towards silence over successive frames to produce a decay envelope, all under software control, one OUT per step. The core's amplitude table holds the same sixteen logarithmically spaced levels.
The noise channel works differently. Its shift register is clocked at one of three fixed rates, the chip clock divided by 512, 1024 or 2048, which on this board is 6 kHz, 3 kHz or 1.5 kHz, or at the rate of tone channel three's counter, which lets the program pitch the noise anywhere. In white mode the register's feedback is the exclusive-or of two of its stages, and the output is a long pseudo-random sequence that sounds like hiss or an explosion depending on the rate. In periodic mode the feedback is a single stage, the register recirculates a short pattern, and the output is a buzzy tone at the shift rate divided by the register length. Writing the noise control register resets the shift register to its initial state, so every effect starts from the same point in the sequence; the core does the same, and its shift register has been checked stage by stage.
One thing about the real chip that I have chosen not to invent: when it accepts a write, the SN76496 pulls its READY output low for about 32 clock cycles while it processes the byte, and some boards wire READY to the Z80's WAIT input so that the processor stalls until the chip is ready for the next write. Whether Sanritsu did that on this board is not something I can determine without a schematic or a PCB to probe, so the core does not insert those wait states. If a board turns up and shows READY wired to WAIT, adding the stall is a small change.
The four-bit voice: the MSM5205 in more depth
---------------------------------------------
The ADPCM algorithm deserves a closer look, because it is a genuinely clever piece of 1980s signal processing packed into a small chip, and the core reproduces it exactly.
Ordinary PCM stores each sample as a number. At eight bits and 6 kHz that would be 6 KB per second, so the 16 KB of sample ROM on this board would hold under three seconds of sound. ADPCM instead stores the difference between each sample and the previous one, and, crucially, stores it at a variable scale. The decoder keeps two pieces of state: the current output level, a signed 12-bit accumulator, and a step index, a number from 0 to 48 that selects an entry from a table of step sizes running from 16 up to 1,552. Each four-bit code is a sign bit and three magnitude bits. To decode one nibble, the chip computes a delta as the step size times the magnitude, with the magnitude interpreted in one-eighth increments so that the delta ranges from one eighth of the step to fifteen eighths of it, adds or subtracts that delta from the accumulator according to the sign bit, and clamps the accumulator to the 12-bit range. Then it adjusts the step index using the magnitude: small magnitudes move the index down one, large magnitudes move it up by two, four or eight, and the index is clamped to its 0 to 48 range.
The effect is that quiet, slowly changing passages are decoded with small steps and fine resolution, while loud transients quickly grow the step size so the decoder can keep up with a fast-moving waveform. Four bits per sample at 6 kHz is 3 KB per second, so the 16 KB ROM holds over five seconds of speech and effects, and the voice comes out clear enough to understand every word. The core's decoder uses the same step table, the same delta arithmetic, the same clamping and the same index adjustment, and produces a 12-bit signed output that is checked nibble by nibble against a separate integer implementation.
The MSM5205 has one more behaviour that the core reproduces: reset. When the sequencer hits the end marker and asserts the chip's reset, the decoder's step index returns to zero and its output settles back to its rest level, so that the next sample begins from a known state rather than wherever the previous one left off. Without this, each sample would start with a click at the previous sample's final level.
Sprites in depth: sixteen at a time, and the 240 convention
-----------------------------------------------------------
Dr. Micro can show sixteen sprites on screen: eight from each layer. Each sprite's record in video RAM is four bytes, and the meaning of those bytes tells you a lot about how the sprite hardware was built.
The first byte is the vertical position, but it is stored inverted: the hardware draws the sprite with its top edge at line 240 minus the byte's value. This is a very common convention on boards with vertical monitors and TTL sprite hardware. The video counter counts lines upward from the top of the raster, and the sprite comparator needs to know at which line to start. Rather than have the software subtract, the designers let the comparator do it, so that a sprite byte of zero puts the sprite just off the bottom of the visible area and increasing values move it up. The core's comparator performs the same 240-minus-Y, and, as on the board, the arithmetic is done in eight bits so it wraps modulo 256.
The second byte is the character, but only its top six bits are the shape number; its low two bits are the sprite's horizontal and vertical flip. The third byte is the attribute: the low four bits are the colour group, the top two extend the shape number to eight bits, and the two bits in the middle are unused by sprites. The fourth byte is the horizontal position, taken straight, with the sprite's left edge at that pixel.
On each scanline the sprite logic asks, for each of the eight records, whether the current line falls within the sprite's sixteen rows. On the board that is a magnitude comparator on the line counter against the sprite's start line and start line plus sixteen. In the core it is the same comparison, done in nine bits so that a sprite near the bottom of the screen is clipped rather than wrapping to the top. If the sprite is on this line, the row within the sprite is the line minus the start line, XORed with the vertical flip bit to select rows in reverse for a flipped sprite. That row selects one of sixteen eight-byte rows from the shape's four cells in the graphics ROM, and the two eight-pixel halves are fetched and shifted out, with the horizontal flip bit reversing both the order of the halves and the order of the pixels within them.
The horizontal position is an eight-bit counter on the board, so a sprite placed at, say, 250 draws its first six pixels at 250 through 255 and its remaining ten at 0 through 9 on the same line. That is how a creature walking off the right edge appears to emerge from the left, and the core wraps the position in exactly the same way. Vertically there is no wrap: a sprite that starts on line 235 draws its first five rows and is clipped, because the comparator simply stops matching when the line counter passes 239.
The order of the eight records decides priority: the hardware evaluates them in sequence and each later sprite's opaque pixels replace whatever was already in the line, so record seven is always on top of record zero. Between the layers, all eight second-layer sprites are drawn after all eight first-layer sprites, so a second-layer sprite is always on top of a first-layer sprite wherever they overlap. The game uses this to put the doctor, drawn from the richer 3-bit graphics, in front of the creatures. Pen zero is never drawn, so sprites can have any outline, and the background shows through their transparent pixels.
The colour lookup in practice
-----------------------------
The nine-bit pen and the two-stage PROM lookup are easier to appreciate with an example.
Suppose the renderer is drawing a tile from the first layer whose attribute selects colour group 5, and the current pixel's two bits from the graphics ROM are 3. The pen is assembled as layer bit 0, group 5, pixel value 3, which lands somewhere in the first 256 entries of the lookup PROMs. The four-bit value found there, say 12, selects entry 12 of the 32-entry colour PROM, whose byte might be, say, 1F: red bits 111, green bits 011, blue bits 00. Through the ladder that is red 255, green 104, blue 0, an orange. Every pixel of every colour group 5 tile that has pixel value 3 comes out that orange, because the lookup is a fixed function of pen.
Now suppose a second-layer tile in colour group 5 has pixel value 3. Its pen has the layer bit set, so it addresses the upper 256 entries of the lookup, and it can map to an entirely different master colour. That is what the two-stage scheme buys the artist: each layer has sixteen colour groups, the first layer's groups have four pens each and the second layer's have eight, and every one of those 192 pen slots can be assigned any of the 32 master colours independently. The screen can show far more distinct colour combinations than the 32 master colours would suggest, and changing the mood of a whole layer is a matter of rewriting a few nibbles in the lookup PROM rather than redrawing graphics.
In the core the colour PROM and the two lookup PROMs are three small block RAMs loaded from your ROM set. The pen from the line buffer addresses the lookup, the lookup's nibble addresses the colour PROM, and the colour byte is split into its three fields and scaled through the ladder weights, all in a short pipeline of registers that adds a fixed delay of four pixel clocks. The sync and blanking signals are delayed by the same four clocks so that everything stays aligned, exactly as the propagation delays through the real PROMs and the DAC are absorbed by the monitor's timing.
Cocktail mode, in detail
------------------------
A cocktail cabinet is a flat table with the monitor facing up through the glass and a player sitting at each end. When play passes from one player to the other, the picture must turn through 180 degrees so that the new player sees it the right way up. The board supports this with the flip-screen latch, bit 1 of the control port, and the game program drives it based on the cabinet DIP switch and whose turn it is.
Flipping a tilemap in TTL is elegant. The tile column address is the top five bits of the horizontal pixel counter and the tile row address is the top five bits of the line counter. Invert all ten of those bits with XOR gates controlled by the flip latch, and the hardware reads the grid from the bottom-right corner instead of the top-left, so the whole map is rotated. Then invert the three pixel bits within the tile and the three row bits within the tile in the same way, so each tile's own pixels are rotated too. The result is a perfect 180-degree rotation with no extra memory and no software cost. The core performs the same inversions: the tile column and tile row are XORed with the flip latch, and the tile's internal row and pixel selects are XORed with the flip latch as well as with the tile's own flip attribute bits.
Sprites need a little more. Their positions are absolute, so the flip logic changes how the position bytes are interpreted: in normal orientation the vertical byte is inverted through 240 minus Y and the horizontal byte is used directly, while in flipped orientation the vertical byte is used directly and the horizontal byte is inverted through 240 minus X. The sprite's own flip bits are XORed with the flip latch so that a sprite drawn facing right in the normal orientation faces right from the second player's point of view too. The core reproduces this position arithmetic and the XOR into the flip bits, and the two-player cocktail game has been played through with the screen flipping at every turn change and the picture correct in both orientations.
Because the latch is written by the CPU, the flip takes effect at the exact frame the game chooses, and because the core samples the latch once per rendered line, the transition is clean: there is never a frame with half the picture in each orientation.
Power-on, reset, and what the Z80 does first
--------------------------------------------
When power arrives on the board, or when the reset button is pressed, the Z80's RESET input is held low for a few clocks and the processor initialises itself: the program counter goes to 0000, the I and R registers go to zero, both interrupt enable flip-flops are cleared so that maskable interrupts are disabled, and the interrupt mode is set to 0. The first instruction the Z80 fetches is at 0000 in dm-00.
Dr. Micro's program does what almost every arcade program does first. It writes zero to the control latch at port 04, which disables the NMI gate so that the video hardware cannot interrupt the initialisation; on the board the latch powers up in an undefined state, so this write matters. It clears its work RAM, sets up the stack pointer, initialises its object tables and sound state, reads the DIP switches to find out how many lives and what coinage the operator has set, and writes the initial screen into the video RAMs. Only then does it write a one to the control latch, enabling NMI, and enter its main loop to wait for the first frame interrupt.
The core reproduces this sequence exactly because it is running the same program on the same processor with the same reset behaviour. What it adds is the MiSTer reset path: the OSD's reset option pulses the board's reset line without disturbing the loaded ROMs, so a reset from the menu is exactly like pressing the reset button on the PCB, and a ROM reload is exactly like power-cycling the board with fresh EPROMs. The reset-then-reboot sequence has been verified frame for frame: after a reset at an arbitrary point in the attract mode, the board returns to the same title screen with the same picture and the same I/O traffic as a cold start.
The one place where the core deliberately differs from a real board at power-on is RAM contents. A real static RAM comes up with whatever pattern its cells happen to fall into, different every time. The core clears all 16 KB of RAM to zero before releasing the Z80, so that every boot is identical and can be compared against every other. Because the program initialises every location it uses before reading it, this has no effect on the game, but I mention it because it is the kind of thing a purist would want to know.
Fitting a 1983 board into a 2020s FPGA
--------------------------------------
The DE10-Nano's Cyclone V has about 42,000 adaptive logic modules, 553 blocks of 10 kilobits of RAM, and 112 DSP multipliers. The complete Dr. Micro board, plus the MiSTer framework around it, uses about 10,100 logic modules, 202 memory blocks and 34 multipliers. Nearly all of the multipliers and a good share of the logic belong to the framework's video scaler and HDMI path, not to the game; the board itself is small.
The game's memory is the interesting part. The 48 KB of program ROM, 40 KB of graphics ROM, 16 KB of sample ROM, 16 KB of RAM and 544 bytes of PROM add up to a little over 120 KB, all held in block RAM. That is well within the chip, which is why no SDRAM board is needed and why every memory access is a single clock. The graphics ROMs are arranged so that all the planes of a tile row can be read in one access, which is what lets the renderer finish a line in less than half the time available.
The whole design runs from the 50 MHz system clock, with the board's three clock rates produced by the fractional enables described earlier. Running everything on one clock domain means there are no clock-crossing hazards between the CPU, video and sound, which is a real advantage over a board with separate oscillators, and it means the FPGA tools can verify every path. They did: the design meets timing at all four of the manufacturer's operating-condition corners, slow and fast silicon at low and high temperature, with positive slack on every path and no unconstrained clocks. That is what lets me say the RBF will behave identically on every DE10-Nano, not just the one on my desk.
What "accurate" means here, precisely
-------------------------------------
I have used the word accurate a lot in this post, so let me pin down what I am claiming and what I am not.
The core is accurate at the level of digital behaviour: every bus cycle the Z80 performs, every byte that lands in every memory, every pixel the video hardware generates from those bytes, every register write the sound chips receive and every sample they produce from those writes. Those things are determined entirely by the logic of the board, and the core reproduces that logic. Where I could check it against documentation of the chips involved, it matches. Where I could check it by running the game and comparing its behaviour frame by frame against what the program should do, it matches, over thousands of frames.
The core is not, and cannot be, accurate at the level of analogue electronics: the exact rise time of a TTL output, the exact voltage of a colour after the resistor ladder, the frequency response of the audio amplifier, the phosphor of a particular monitor. None of those affect what the digital logic does, so none of them affect gameplay, but they do affect what a real cabinet looks and sounds like, and MiSTer's video and audio options are the right place to taste those to your liking.
There are a few specific points about the board that I have not been able to confirm without a PCB to measure: the exact number of blanked lines and pixels in the original monitor timing, which affects the refresh rate by a fraction of a percent; the purpose of the two undocumented control latch bits; and whether the PSG READY line is wired to the CPU. In every case the core follows the most likely behaviour and documents the uncertainty, and in every case the game plays identically whichever way the question resolves.
The Z80 pin by pin: what the core drives and why
------------------------------------------------
The Z80 in a 40-pin package has a well-defined set of control signals, and because this core implements the processor as real logic, every one of those signals exists inside the FPGA and behaves as the pin would. Walking through them is the clearest way to show what "a real Z80" means here.
MREQ, memory request, goes low whenever the CPU wants a memory cycle: an opcode fetch, a data read, a data write, or a refresh. RD goes low with it for reads and WR for writes. On the board these three lines, together with the address decoder, are what tell an EPROM or a RAM to drive or accept the data bus. In the core they are the same three signals, generated by the same machine-cycle state machine, and the memory block reacts to them exactly as the chips would: it drives data when MREQ and RD are low and the address is in its range, and it accepts data on the trailing edge of WR.
M1 goes low during an opcode fetch and during an interrupt acknowledge. Combined with MREQ it marks the fetch of the first byte of an instruction; combined with IORQ instead it marks an interrupt acknowledge. Dr. Micro never uses maskable interrupts, so the acknowledge case never arises on this board, but the core still qualifies I/O cycles against M1 so that if it ever did, an acknowledge would not be mistaken for a port write. The core also exposes the fetch condition, M1 and MREQ and RD all low, to the test harness so that instruction execution can be counted: over a 3,600-frame two-player game the core performed 22,792,401 opcode fetches, which is one every 158 system clocks on average, exactly what a 3.072 MHz Z80 spending most of its time on four- to seven-T-state instructions produces.
RFSH goes low during the second half of every M1 cycle, and the address bus carries the I and R registers. The core generates it, and, as described earlier, the bus logic uses it to make sure a refresh cycle is never treated as a write even though MREQ is low. On the real board the refresh cycles are simply ignored by the static RAMs; the core matches that.
IORQ goes low for I/O cycles and the low eight address bits carry the port number. Dr. Micro's port decoder only looks at those eight bits, so the core does too. An I/O cycle on the Z80 is one T-state longer than a memory cycle because the processor inserts an automatic wait state; the core's cycle counts include that state, which is why an OUT to a PSG takes eleven T-states in total.
WAIT is an input that, when pulled low, stretches the current cycle until the slow device releases it. Nothing on the Dr. Micro board is slow enough to need it, and the core ties WAIT permanently inactive. I mentioned above that some boards use the PSG's READY line to drive WAIT; if that turned out to be true here it would be wired to this input.
INT, the maskable interrupt, is never asserted on this board. The game runs entirely on NMI. The core ties INT inactive and, since the program leaves maskable interrupts disabled, it would make no difference if it did not. NMI is the one interrupt line that matters, and the core drives it from the video counter through the control latch gate exactly as described earlier, holding it low for two CPU clock periods so the Z80's edge detector sees precisely one falling edge.
HALT goes low when the CPU is executing the HALT instruction and idling until an interrupt. The core exports this too, mainly for the test suite, which uses it to confirm that HALT followed by NMI wakes the processor at the right cycle. BUSRQ and BUSAK, the bus-request handshake for DMA, are unused on this board; the core ties the request inactive.
Finally, RESET. The core holds it active while the ROM is loading and while the RAM is being cleared, and releases it in the same clock in which it releases the clock-enable generators, so that the first instruction fetch happens at a known phase relative to the video counter. That shared release is what makes every boot identical.
How long each instruction takes, and why it matters
---------------------------------------------------
Because the frame's game logic all runs between one NMI and the next, the total time the CPU spends is the sum of the times of every instruction it executes, and those times are fixed properties of the Z80. Here are the ones that dominate this game, and that the core's test programs verify by counting clock edges.
NOP takes four T-states, a single M1 cycle. LD A,n, loading an immediate byte, takes seven: an M1 for the opcode and a three-state read for the operand. LD SP,nn takes ten: M1 plus two operand reads. JR, the relative jump, takes twelve when taken and seven when not, because the taken case spends five extra internal states computing the target. DJNZ, the loop instruction, takes thirteen when the loop continues and eight when it exits. CALL takes seventeen: an M1, two operand reads, an internal state, and two stack writes. RET takes ten, as discussed. PUSH takes eleven and POP ten. OUT (n),A and IN A,(n) each take eleven: M1, an operand read, and a four-state I/O cycle. LDIR, the block copy that the program uses to move tables around, takes twenty-one T-states per byte while repeating and sixteen on its final byte. LD A,R takes nine: a two-byte instruction with an ED prefix, so two M1 cycles, and both of them increment R, which is exactly why the value read back reflects the second increment.
Every one of these numbers is a hard fact about the Z80, and the core reproduces every one of them. The test programs are straightforward: set up a known instruction sequence in memory, start counting clock enables at a marker, execute the sequence, and stop counting at a second marker. If the count is off by even one, the test fails. The donor CPU failed three of these tests before I corrected it. The corrected core passes all of them, and it also passes a longer program covering the extended instruction set: conditional returns in both directions, indexed loads through IX and IY, the bit-test and shift group, and the block instructions in both their repeating and terminating forms.
Why does this matter for Dr. Micro specifically, beyond the general principle of getting things right? Because the frame is a fixed budget. At 3.072 MHz there are 51,200 T-states between one NMI and the next. The game's handler uses some fraction of them; the rest is spent in the main loop. If the CPU is slow by a few percent, the handler takes longer, and the point in the main loop at which the next NMI arrives shifts. That shifts the value of R when the game reads it, which shifts the randomness, and it can shift whether a video RAM write lands before or after the beam passes a given row. A cycle-exact CPU keeps all of that where the board keeps it.
The video counter chain, as the board built it
----------------------------------------------
On the PCB, the video timing is a chain of 4-bit synchronous binary counters, the 74LS161 or 74LS163 family, clocked by the pixel clock. Two and a bit of them count horizontal position from 0 to 319 and reset; their carry out clocks the next chain, another two counters that count lines from 0 to 255 and wrap. The counters' outputs are the address lines of the video system: the horizontal count's bits 3 to 7 pick the tile column, bits 0 to 2 pick the pixel within the tile, the line count's bits 3 to 7 pick the tile row and bits 0 to 2 pick the row within the tile. Decoders and gates on those same counter outputs produce horizontal and vertical blanking, the two sync pulses, and the frame interrupt.
The core's counters are the same thing written as two registers: a nine-bit horizontal counter that runs 0 to 319 and an eight-bit line counter that increments when the horizontal counter wraps. Blanking, sync and the NMI request are comparisons on those registers. The numbers are worth stating because they define the picture's timing to the microsecond. At 4.9152 MHz a pixel period is 203.5 nanoseconds. A line of 320 pixels is 65.1 microseconds, so the line rate is 15,360 Hz, in the middle of the range a standard-resolution arcade monitor accepts. Of those 320 pixels, 256 are visible and 64 are blanked, giving 13 microseconds of horizontal blanking, within which a 32-pixel, 6.5-microsecond sync pulse sits. A frame of 256 lines is 16.67 milliseconds, which is 60.00 Hz. Of those lines, 224 are visible and 32 are blanked, giving 2.08 milliseconds of vertical blanking with a four-line sync pulse inside it. The interrupt is requested four pixels before the end of the last visible line.
There is one subtle point about the counters that the core gets right and that is easy to get wrong. The line counter wraps from 255 to 0, and the first sixteen lines of the frame, 0 through 15, are blanked, then 224 visible lines follow, then lines 240 through 255 are blanked. So vertical blanking straddles the counter's wrap: it runs from 240 up through 255 and then 0 through 15. The interrupt at line 239 comes at the start of that blanking period, which gives the game's handler the full 32 lines, about two milliseconds, to update the video RAM before the beam returns to visible territory at line 16. The core's reset also drops the counters at line 240, the start of blanking, so that the very first frame after reset gives the program its full blanking window before any picture is drawn.
Every signal that comes out of the video system, the colour, the syncs, the blanking, and the pixel-enable strobe that tells the MiSTer framework when a new pixel is valid, is delayed together through four register stages. Those four stages are the pipeline: read the line buffer, look up the pen, look up the colour, split and scale the colour. Because they are delayed as a group, the syncs and the picture stay in exact alignment, just as they do on a board where the PROMs and DAC add a fixed few tens of nanoseconds to the colour path and the monitor never notices.
The line buffer: how much time a line really has
------------------------------------------------
A scanline renderer lives or dies by whether it can finish every line before the beam needs it, and it is worth showing the arithmetic, because the margin is what makes the core robust rather than merely working.
At 4.9152 MHz pixels on a 50 MHz system clock, a line of 320 pixels lasts 3,255 system clocks. The renderer must produce all 256 visible pixels of the next line within that time. It does so by walking the two tile layers and the two sprite banks in sequence, using the fast block RAM.
For each of the 32 tile columns in a layer, the renderer spends two clocks fetching the tile code, two fetching the attribute, two fetching the graphics row, and eight writing the eight pixels into the line buffer: fourteen clocks per tile, 448 per layer, 896 for both layers. For each of the eight sprites in a bank it spends eight clocks reading the four record bytes, one clock testing whether the sprite is on this line, and, if it is, two fetches and eight writes for each of the two eight-pixel halves plus one clock to move on: at most 30 clocks per sprite, 240 per bank, 480 for both banks. One more clock marks the line complete. The worst case, every sprite on every line, is 1,377 clocks, well under half the 3,255 available.
That margin is not wasted. It means the renderer has no timing dependence on how many sprites happen to be on a line, which on some real boards was a genuine limitation that made sprites flicker or vanish when too many lined up. Dr. Micro's TTL evaluated its eight sprites per bank in parallel hardware and had no such limit, and the core's sequential renderer, thanks to the margin, has none either. A sticky flag records if the renderer is ever still busy when a new line starts; across every test and every hour of play it has stayed clear.
The two line buffers alternate: while one is being read out to the screen at pixel rate, the other is being filled for the next line at system clock rate. Each buffer stores 256 nine-bit pens, and carries a tag with the number of the line it holds so that the read-out logic can confirm it is displaying the right line. On the real board this double-buffering is implicit in the pipeline of latches and shift registers between the ROMs and the DAC; the FPGA makes it explicit, but the effect is the same: a stable, complete line of pixels delivered in step with the beam.
Static RAM, and why dual-port is the same thing
-----------------------------------------------
The video RAMs on the board are ordinary static RAM: a 2 KB by 8 part with eleven address lines, eight data lines, a chip select, an output enable and a write enable, and an access time in the range of 100 to 200 nanoseconds. A static RAM cell is a pair of cross-coupled inverters that hold a bit indefinitely as long as power is applied, with no refresh needed, which is why the Z80's refresh mechanism goes unused on this board.
A single-port RAM can only serve one address at a time, so the board has to arbitrate between the CPU and the video hardware. The usual arrangement, and the one that fits this board's timing, is time-slot multiplexing: during the part of each pixel period when the video hardware does not need the RAM, the CPU's address and data are switched onto it through multiplexers, and any pending CPU write is performed. From the CPU's point of view the RAM simply responds within its normal bus cycle; from the video hardware's point of view it always gets its tile byte when it asks. Neither side ever sees a conflict, because the multiplexing happens faster than either side's cycle.
The FPGA offers a cleaner way to achieve exactly the same observable behaviour: dual-port block RAM, which has two independent address and data ports and can serve both in the same clock. The core uses it for the video RAMs, with the CPU on one port and the renderer on the other. The one case that needs care is a write from the CPU to the very address the renderer is reading in the same clock. The block RAM is configured so that the read returns the old contents, which is what a multiplexed single-port RAM would produce if the read slot precedes the write slot in the pixel period, and which is the safe behaviour: the renderer never sees a half-written byte. A dedicated test drives this collision at every address and confirms the old-data result.
All of the other memories on the board, program ROM, graphics ROM, sample ROM, PROMs and work RAM, are also block RAM in the core, each with a one-clock synchronous read. On the board the EPROMs' access time of around 250 nanoseconds is well inside the Z80's read cycle at 3.072 MHz, so the processor never waits; in the core a one-clock read at 50 MHz is 20 nanoseconds, more than an order of magnitude faster than necessary, and the result is simply held on the bus until the CPU samples it, which is the held-read behaviour described earlier.
Mixing the sound
----------------
The board's audio section takes four sources, three PSG outputs and the ADPCM decoder's output, and sums them into a single mono signal for the cabinet's amplifier. On the PCB that summing is a resistor network into an operational amplifier, with the resistor values setting each source's relative level.
In the core the summation is done digitally with the same intent. Each SN76496 produces an output that is the sum of its four channels, each channel contributing its attenuator level when its square wave is high and nothing when it is low; the full-scale output of one chip is therefore four times the loudest single channel level. The three chip outputs are added and scaled down by a factor of eight to leave headroom. The MSM5205's 12-bit signed output is scaled up by three, reflecting the higher gain the sample channel gets in the board's mixer so that the voice sits above the music. The sum is clamped to the signed 16-bit range and sent to the MiSTer framework as identical left and right channels. The scaling factors are chosen so that the loudest simultaneous passage the game produces stays just inside the range without clipping.
What the core does not attempt is the analogue character of the original amplifier: its low-pass roll-off, any tone shaping the designers built in, and the response of whatever speaker sat in the cabinet. Those belong to the cabinet rather than the board, and MiSTer's audio filter options are the place to approximate them if you want to.
Inputs in detail: from the MiSTer pad to the Z80's port
-------------------------------------------------------
The path from your controller to the game has a few stages, and each one is designed to leave the board's view of the world unchanged.
The MiSTer framework delivers each gamepad's state as a set of bits over the HPS bus, updated continuously, along with any PS/2 keyboard traffic as scan codes. The core takes the pad bits for directions, the action button, start, coin and service, and decodes the keyboard scan codes for the same functions on the keys listed in the OSD. Keyboard decoding handles the make and break codes properly: a key is held from the moment its make code arrives until its break code, prefixed by F0, arrives, and the extended-key prefix E0 used by the arrow keys is honoured. The result is a set of held-down flags, one per game input, that are ORed with the pad bits.
Those flags feed the 4-way arbitration. On the original cabinet the joystick had a restrictor plate that made it physically impossible to press two adjacent directions at once, and its switches were wired directly to the input port. A modern pad has no such plate, so the core enforces the same constraint in logic: if up and down are both pressed, neither is reported; if left and right are both pressed, neither is reported; if a vertical and a horizontal direction are both pressed, only the vertical one is reported. This gives a clean, predictable result that plays like the cabinet without ever presenting the game with a combination the original stick could not produce.
The arbitrated directions and buttons are then assembled into the two eight-bit port values with exactly the board's bit assignment, up in bit 0, right in 1, down in 2, left in 3, action in 4, and coin, service or the start buttons in 5 and 6 depending on the port, and presented to the Z80 when it executes an IN from port 00 or 01. During reset the inputs are gated to zero so that a held button cannot influence the program's initialisation, and released on the same clock as the CPU.
The DIP switches, switch by switch
----------------------------------
The board has two banks of eight DIP switches, read by the Z80 through ports 03 and 04. The MRA exposes every switch, and it is worth knowing what they do, because the board's manual is not exactly easy to find.
Bank one, switches 1 and 2, set the number of lives: off-off gives two, on-off gives three, off-on gives four and on-on gives five. Switch 3 enables the attract-mode sound. Switches 4 and 5 set the bonus life thresholds: 30,000 then 100,000; 50,000 then 150,000; 70,000 then 200,000; or 100,000 then 300,000. Switch 6 puts the board into service mode, where it shows its test screen instead of the game. Switch 7 selects the cabinet type, upright or cocktail, which tells the program whether to flip the screen for the second player. Switch 8 flips the screen permanently, for cabinets where the monitor was mounted the other way up.
Bank two, switches 1 to 3, set the coinage: one coin for one, two, three, four or five credits, or two, three or four coins for one credit. Switches 4 through 8 are unused, and the service screen shows them as such.
The core's default, taken from the MRA, is three lives, attract sound on, bonus at 50,000 and 150,000, service off, upright cabinet, flip off, and one coin per credit. When you change a switch in the OSD, the new bank values are sent to the core over the HPS bus on a dedicated index, and the core updates the values presented on ports 03 and 04 without resetting the game, exactly as a real switch change takes effect the next time the program reads the port. The game reads the switches during initialisation for lives and coinage, and continuously for service mode and cabinet type, so some changes take effect immediately and others on the next reset, just as on the board.
Loading the board: the HPS protocol and the loader
--------------------------------------------------
The MiSTer's ARM processor and the FPGA talk over a bus that the framework calls the HPS bus. When you launch an MRA, the ARM side parses the MRA, opens your ROM archive, verifies each file's checksum, arranges the files in the order the MRA specifies, and streams the result into the FPGA as a sequence of bytes, each with an address and an index that identifies what kind of data it is.
The core's loader watches that stream. Index zero is the ROM payload. For each byte, the loader uses the address to decide which block RAM it belongs to, program, graphics plane, sample, colour PROM or lookup PROM, and writes it there. It counts bytes as it goes, and when the download signal drops it checks the count against the expected 107,040. If they match, it marks the ROM as loaded; if not, it flags an error, and the board stays in reset with an error indication rather than running corrupt code. Index 254 is the DIP switch path: two bytes, one per bank, that update the switch values without touching the ROM or the board's reset. The loader distinguishes the two indexes so that a DIP update during play never disturbs the game.
While the loader is running, the whole board is held in reset: the CPU, the video counters, the sound chips and the clock-enable generators. When the ROM is complete, the core clears all 16 KB of RAM, which takes 16,384 clocks, about a third of a millisecond, and then releases everything together. The program starts at address zero on a board with a fully loaded ROM and a blank RAM, and every boot begins from exactly this state.
The OSD reset is a different path. It pulses only the board's reset, leaving the loaded ROM intact, so the CPU restarts, the RAM is cleared again, and the game reboots, just as if the cabinet's reset button had been pressed. A ROM reload from the menu takes the loader path again, which is the equivalent of powering the board down and up with the EPROMs reseated. Both paths have been exercised repeatedly in the test suite: cold starts, reloads, resets in the middle of attract mode, deliberately short loads that must be rejected, and DIP updates that must not reset, all behaving as designed.
How the core was tested, in detail
----------------------------------
I gave an outline of the verification earlier. Here is the detail, because I think anyone who cares about accuracy deserves to see what "tested" means rather than take it on faith.
The lowest level is a set of four-state simulations, meaning simulations that track not only ones and zeros but also unknown and undriven values, so that any uninitialised signal or bus conflict shows up as an X rather than being silently resolved. At this level the clock-enable generators are checked for their exact long-term rates and their bounded phase error. The loader is fed complete, short, and repeated downloads and checked for acceptance, rejection and recovery. The bus qualification is checked so that refresh cycles and interrupt acknowledges never produce writes. Every one of the 65,536 CPU addresses is read and checked against the memory map. Same-cycle collisions between CPU writes and video reads are checked for old-data results. The 4-way arbitration and the keyboard decoding are checked for every combination. And the CPU runs its timing programs: the RET, NMI and refresh corrections, the extended instruction set, and HALT and RETN.
The next level is independent fixtures for the video and sound blocks. For the renderer, a program generates a random tilemap for both layers and random sprite records for both banks, deliberately including sprites that overlap each other, sprites that wrap off the right edge, and sprites clipped at the top and bottom, together with random graphics ROM contents that are asymmetric so that any flip error is visible. It also generates random PROM contents. A separately written renderer, sharing no code with the hardware description, computes the expected pen and colour for every one of the 57,344 visible pixels. The hardware renderer is then run on the same data in both orientations and every pixel is compared. For the PSG, a separately written model of the chip is fed 32,768 random writes with random spacing, including back-to-back writes and writes during a counter reload, and the two outputs are compared event by event. For the ADPCM decoder, a 256-nibble vector designed to drive the accumulator into saturation in both directions is decoded by the hardware and by an integer reference, and compared sample by sample. For the sequencer, every one of the 64 sample slots is triggered, restarted mid-play, and run to its end marker, and the nibble stream is checked.
The third level runs the complete board on the real game ROMs. The simulator loads the ROM set through the real loader path, releases the board, and applies a scripted sequence of inputs: coins, starts and joystick moves at fixed frames, for attract mode, a single-player game, a two-player game, the DIP switch variant, service mode, cocktail mode and a mid-run reset. Throughout, it records every I/O write and read with its frame and clock, the CPU's program counter and refresh register at every frame boundary, the RGB of every visible pixel, the raw pen of every pixel, the full RAM contents at periodic frames, and the four audio sources at 48 kHz. These recordings are then checked: the I/O sequences in order, the pixel captures against the independently rendered RAM contents, and the boot sequences against each other. The longest run, 3,600 frames of a two-player game, produced 22,792,401 opcode fetches, 3,510,136 RAM writes, 15,060 I/O writes, 11,976 I/O reads and 3,587 interrupts, with every I/O event in the expected order.
The fourth level is the hardware itself. The bitstream is synthesised, placed and routed, and its timing analysed at all four operating-condition corners. It is then loaded onto a DE10-Nano through the normal MRA path, and played.
None of these levels is sufficient on its own. The unit tests cannot tell you the game is right; the game run cannot tell you which block is wrong when something differs; the hardware cannot tell you anything about internal signals. Together they give a picture I am comfortable calling accurate, with the specific exceptions I have listed.
Design decisions, and the roads not taken
-----------------------------------------
Every core embodies choices, and a few of the ones in Dr. Micro are worth explaining, because they were made in the service of accuracy rather than convenience.
The core has no frame buffer, by choice. It would have been simpler in some ways to render a whole frame into memory and then scan it out, but that is not what the board does, and it would have introduced a frame of latency and a different relationship between CPU writes and the displayed picture. The scanline renderer is more work to build and to verify, but it behaves like the board.
The core uses block RAM for everything, by choice. SDRAM would have allowed a larger design, but it brings a controller, refresh, and variable latency, none of which the board has. A 120 KB board has no need of it, and keeping everything on-chip keeps every memory access deterministic.
The core runs from one clock, by choice. It would have been possible to use a PLL to generate a true 3.072 MHz and a true 4.9152 MHz and run the CPU and video on them directly. But multiple clock domains bring synchronisation problems wherever they meet, and the meeting points here, the CPU writing video RAM that the renderer reads, are exactly where the board's behaviour is most sensitive. Fractional clock enables on one 50 MHz clock give the same long-term rates with a bounded, well-understood jitter of one system clock, and a design that the tools can verify completely.
The core uses a corrected TV80 rather than another Z80 implementation, by choice. TV80 is a mature, widely used core whose structure closely follows the Z80's actual machine-cycle behaviour, which made it the right starting point for cycle-exact corrections. The corrections are recorded as exact patches against the original files, so that anyone can see precisely what was changed and why, and the original files are kept alongside.
And the core keeps its uncertainties in the open, by choice. Where the board's behaviour is not known for certain, the documentation says so and says which way the core has gone. I would rather have a short list of honest unknowns than a long list of confident guesses.
Open questions about the board
------------------------------
For completeness, here is everything about the Dr. Micro PCB that I have not been able to settle without a board to measure, and what the core does in each case.
Monitor timing. The board's exact number of pixels per line and lines per frame, and therefore its exact horizontal and vertical rates, are not documented. The core uses 320 by 256 at 4.9152 MHz for exactly 60.00 Hz, which matches the rate the game is generally described as running at. Contemporary sources disagree on the exact figure, and a measurement of a running board's sync would settle it; the difference, if any, would be a fraction of one percent in speed.
PSG clock. Sources also disagree on whether the three sound generators are clocked at the CPU's 3.072 MHz or at 4.608 MHz, the crystal divided by four. The core uses 3.072 MHz. A recording of a board's music would settle this immediately, because the two produce pitches a fifth apart.
The control latch. Bits 0 and 1 gate the interrupt and flip the screen; the game also writes bits 2 and 3, and their function is unknown. Candidates include a coin counter drive and a coin lockout, both common uses for spare latch bits on boards of this era. The core ignores them.
Port 05. The game reads port 05, inverts the value, and writes it back, every frame. This is the signature of a watchdog kick or a similar keep-alive, but no device is documented at that address. The core returns zero on reads and ignores writes, which lets the program's loop run exactly as it would; if the board has a watchdog there, the core is behaving as one that is always satisfied.
READY and WAIT. Whether the PSGs' READY outputs are wired to the Z80's WAIT input, stalling the CPU briefly after each sound write, is unknown. The core does not stall. The effect, if the wiring exists, would be a handful of T-states per sound write, small relative to the frame.
The analogue path. Colour DAC resistor values, the audio mixer's exact gains and filtering, and the amplifier's response are all things the core approximates with the standard values for boards of this type.
If any of these gets resolved by someone with a board and the right test equipment, the fix in each case is small and well-contained, and I will be glad to make it.
The attract mode, and what it tells you about a board
-----------------------------------------------------
The attract mode is the loop a cabinet runs when nobody is playing: a title screen, a demonstration of play, a high score table, and back to the title. It exists to sell the game to a passer-by, and it is also, for anyone bringing a board back to life, the single most useful diagnostic there is.
The reason is that the attract loop exercises almost everything. It draws both tile layers and moves sprites from both banks. It cycles the colour groups. It plays music on all three sound generators and, on this board, triggers the voice samples. It reads the DIP switches to decide whether to make any sound at all. And it does all of that on a fixed schedule with no player input, which means two runs of it should be identical, frame for frame, forever.
That last property is what makes it the backbone of this core's testing. Three independent cold boots of the core, each starting from a fresh ROM download and a cleared RAM, were run for 120 frames of attract mode and their outputs compared: every pixel of every captured frame, the raw pen indices behind those pixels, the complete contents of all 16 KB of RAM, and the running counts of opcode fetches, memory writes, I/O writes and interrupts. All three runs were bit-identical in every one of those measures. That is a strong statement about the core: it says there is no uninitialised state anywhere, no race between the CPU and the video hardware whose outcome varies, and no dependence on anything outside the design.
It is also, incidentally, a statement about the board. A design that produces identical attract loops is a design in which the CPU and the video hardware are locked to the same crystal with a fixed phase relationship, which is exactly what a single-crystal board with a video-derived interrupt gives you. A board with two independent oscillators would drift, and the attract mode would wander. Dr. Micro does not wander, and neither does the core.
Watching the attract mode is also how you can hear the sound design. Sanritsu used the three generators as three distinct voices: a lead melody, a bass line, and a third part that carries harmony during the music and effects during play. Because each generator has its own noise channel as well, effects can overlap the music without stealing a tone channel from it, which is why the game never has that characteristic thinning-out that single-chip boards suffer when a sound effect fires during a tune.
Service mode: the board's own self-test
---------------------------------------
Flip switch 6 of the first DIP bank and the board boots into service mode instead of the game. This is the operator's diagnostic screen, and it was standard equipment on arcade boards from about 1982 onward, because a cabinet on location had to be maintainable by someone who was not an engineer.
The screen shows the state of the DIP switches, laid out so the operator can confirm that what the switches say matches what the board reads, and it shows the state of the inputs, so that each joystick direction, button, coin and service input can be pressed in turn and seen to register. It is the fastest way to find a broken microswitch, a dirty coin mech, or a wiring fault in a control panel, and it also confirms that the CPU, the program ROM, the video RAM, the graphics ROMs and the colour PROMs are all functioning, because none of the screen would appear if any of them were not.
The core runs service mode exactly as the board does, because service mode is a branch in the game program rather than a hardware feature: the program reads the switch, sees it set, and enters a different loop. Everything the screen shows is the program reading the same ports the game reads. This makes service mode a useful test in the core too, and the test suite uses it: a 120-frame service-mode run is compared pixel for pixel and I/O event for I/O event against the expected behaviour, and it matches exactly, all 234 writes and 190 reads in order, on every capture.
If you want to check that your controls are mapped the way you expect, service mode is the honest way to do it: not by playing and guessing, but by watching the board itself report what it sees on each input pin.
The family resemblance: Sanritsu's board lineage
------------------------------------------------
Dr. Micro did not appear from nowhere. Sanritsu built a series of boards in this period that share a clear design language, and recognising the family helps explain why Dr. Micro is put together the way it is.
The common elements are a single Z80 doing everything, a bank of 2764 EPROMs for program and graphics, tile layers described by parallel code and attribute tables, sprite records living inside the tile RAM rather than in a separate memory, colour defined by a small master palette PROM behind a larger lookup PROM, and TI sound generators. Set a Dr. Micro board next to its siblings and the same building blocks are there in the same arrangement, with the differences being counts and sizes rather than concepts: how many layers, how many bits per pixel, how many sound chips, whether there is a sample channel.
Dr. Micro sits at the more elaborate end of that family. Two layers is generous for the year and the price bracket. Three bits per pixel on the second layer, giving eight pens per colour group rather than four, is what lets the doctor and the more detailed objects have shading that the background does not. Three sound generators instead of one is unusual. And the ADPCM channel with its own crystal, its own ROM and its own sequencer is a real addition, not an afterthought: a board designer does not add a separate 384 kHz crystal and two EPROMs unless the game is going to use them.
What is striking, looking at the whole board, is how little is wasted. The sprite table lives in the first 32 bytes of the tile RAM, which the tile hardware then simply skips over because those cells are off the visible area. The graphics ROM is addressed so that a sprite is four consecutive tiles, so the same address decoder serves both. The colour lookup gives 192 usable pen slots from 32 master colours. The board does not have one chip more than it needs, and every design decision in it is a decision about how to get more out of fewer parts. Rebuilding it, you end up with a lot of respect for whoever laid it out.
How this core came together
---------------------------
A short account of the build, because I think the process is as interesting as the result, and because it shows where the accuracy actually came from.
It started with the memory map and the bus. Getting a Z80 to fetch its first instruction from a block RAM sounds trivial and is not: the first attempt ran, fetched FF from a bus that had already stopped driving, took that as a RST 38, jumped to 0038, fetched FF again, and sat in that loop forever. The fix was the held read described earlier, and once it was in, the program booted and the machine started doing recognisable things.
Then came the video, built to the tile and sprite formats decoded from the graphics ROMs. The first pictures were nearly right and wrong in instructive ways: tiles flipped when they should not have been, because the flip bit was applied to the wrong stage of the pixel shift; sprites in the wrong vertical position, because the 240-minus-Y convention had not been spotted yet; the second layer covering the first, because pen zero was not being treated as transparent. Each of those was found by rendering the same video RAM contents with a separately written renderer and comparing pixel by pixel, which is a much faster way to locate a fault than staring at a wrong picture.
The sound came next, and the ADPCM decoder produced its first vector output one count away from where it should rest at reset. That turned out to be a signed-versus-unsigned comparison in the decoder's reset path, which sent every negative sample down the wrong branch. It is a one-character fix and it is the difference between speech that sounds right and speech with a persistent distortion.
Then the CPU timing work, which was the longest phase. Comparing the core's instruction-by-instruction behaviour against the documented T-state counts turned up the RET, the NMI entry and the disabled refresh, in that order. The refresh discovery was the significant one, because it explained something that had been nagging: the game's enemy behaviour was repeating in a way that felt too regular. With the refresh counter working, the game came alive.
The last phase was interrupt placement, and it was the most painstaking. With the CPU cycle-exact and the video counter running, the remaining question was exactly where in the raster the interrupt should fire so that the CPU is interrupted at the same instruction the board would interrupt it at. That was settled by recording the program counter and the refresh register at every frame boundary over hundreds of frames, trying candidate positions a pixel apart, and keeping the one that matched across the whole run rather than at a single checkpoint. Positions one pixel either side were tried and measured; one was clearly worse and one was equivalent, and the better-supported of the two was kept.
Then synthesis, timing closure, and the first load onto real hardware, which is always the moment of truth. It booted to the title screen on the first attempt, which after all that work felt slightly anticlimactic, and then entirely satisfying.
What is next
------------
The core is complete and playable, and I consider it finished for release. There are three things I would still like to do, none of which affects how it plays today.
The first is to settle the open board questions listed above, which needs a Dr. Micro PCB and a few hours with a scope and an audio recorder. The monitor timing and the PSG clock are both a single measurement each. If any reader has a board, I would genuinely like to hear from you.
The second is a small refinement to the internal test harness. The core and its reference are compared frame by frame by freezing the state at a defined instant in vertical blanking, and the two sides currently choose slightly different instants within that blanking period. When the game happens to update a background animation between those two instants, the comparison reports a handful of differing pixels for one frame even though both sides are behaving identically. It is a measuring-instrument artefact rather than a fault in the core, and it does not affect the picture you see, but I want the harness to be clean so that any future difference is unambiguous.
The third is simply more play testing across more cabinets, monitors and setups. A core that works on my DE10-Nano and yours is worth more than a core that works on mine.
Beyond that, this board's family has other members, and the work done here, the corrected CPU, the tile and sprite renderer, the sound generators and the ADPCM path, transfers directly to them. That is the nice thing about building a board properly rather than making a game run: what you end up with is a set of parts that were common to a whole generation of hardware.
Glossary
--------
A few of the terms used above, for anyone who wants them spelled out.
T-state: one period of the Z80's clock. Every instruction takes a fixed number of them.
Machine cycle: a group of T-states that performs one bus operation, such as an opcode fetch or a memory read.
M1: the first machine cycle of every instruction, the opcode fetch, during which the M1 pin is asserted and, in its second half, a refresh cycle occurs.
NMI: non-maskable interrupt, an interrupt the program cannot disable inside the CPU. On this board it arrives once per frame from the video hardware and is gated by a latch outside the CPU.
Refresh register, R: a seven-bit counter in the Z80 that increments on every M1 cycle, intended for dynamic RAM refresh and used by this game as a random number source.
EPROM: erasable programmable read-only memory, the ultraviolet-erasable chips that hold the game's program, graphics and samples.
PROM: programmable read-only memory, here the small fusible-link bipolar chips that hold the colour tables.
Tilemap: a grid of small fixed-size images, the tiles, described by a table of tile numbers in memory. The board has two, one per layer.
Sprite: a small image that can be placed anywhere on screen independently of the tile grid. The board has sixteen, eight per layer.
Pen: the raw colour index produced by the graphics hardware before it is translated by the colour PROMs.
Blanking: the parts of each line and each frame when the beam is returning and nothing is drawn. Vertical blanking is when the game updates the picture.
Line buffer: a small memory holding one scanline's worth of pixels, filled ahead of the beam and read out in step with it.
LFSR: linear feedback shift register, the structure inside the PSG that generates noise.
Attenuator: the volume control on each PSG channel, in 2 dB steps.
ADPCM: adaptive differential pulse-code modulation, the four-bit sample compression the MSM5205 decodes.
Block RAM: the small fast memories built into the FPGA, used here for every ROM and RAM on the board.
RBF: the bitstream file that configures the FPGA with the core.
MRA: the small XML file that tells MiSTer which core to load and how to arrange the ROM files for it.
HPS: the ARM processor side of the DE10-Nano, which runs MiSTer's menu and loads ROMs into the FPGA.
Frequently asked
----------------
Do I need an SDRAM board? No. The entire board fits in the FPGA's internal memory.
Does it support a rotated monitor? Yes. Choose Native orientation in the OSD and the core outputs the board's native portrait picture for you to rotate physically, or leave it on Vertical for the framework to rotate it for a landscape display.
Why does it look sharper than the videos I have seen of the cabinet? Because you are seeing the board's exact digital output through a modern display path. The cabinet's monitor added its own blur, bloom and scanlines; the OSD's scanline and scandoubler options let you add those back to taste.
Can I change the difficulty settings? Yes, through the DIP switch page in the OSD, exactly as an operator would have on the board.
Does the core include the game? No. You supply your own ROM set as drmicro.zip; the MRA tells MiSTer how to load it. Nothing from the game is distributed with the core.
Is the source available? Yes, on the Meathax GitHub, with the full test suite and the documentation describing every decision above.
To Guy Hutchison and Daniel Wallner for the TV80 and T80 lineage the CPU grew from. To Jose Tejada for the JT89 and JT5205 designs that seeded the sound generators and the ADPCM decoder. To Sorgelig and the MiSTer team for the platform that makes all of this possible. And to Sanritsu's engineers, who in 1983 built a tight, clever little board that was a pleasure to take apart and put back together in silicon.
Enjoy the game.
/meme post
You made it this far? :D
Source code: https://github.com/meathax/drmicro
INSTALLATION:
Download downloader_meatcores.txt, place that in your misters root folder, the same folder as downloader.ini, then run update all to get all my cores!
OR
Get Dr. Micro files from here, extract to Mister root folder
Comments (21)
Great work .. you know what I am going to ask for :) any chance of high saving please
Keep it up Meat! You're the man!
i see that you've made some progress here on your core development skills, but i can't truly enjoy a core that hasn't been artisanally constructed by brazilian and/or trangendered hands, kept in beta for a while, and paywalled
Totally read this. PCB blah blah blah. Human millipede Blah blah. Play video games.
Great game and write up - thank you - found another bug in Spider-Man - on the first level when you come up to the truck that parked and has venom in it the player disappears behind the upper truck (just walk up to it) not sure whether it can be fixed or not - cracking work otherwise and loving the cores
Please sir my scrollwheel is only rated for 10 million cycles
You made it down here to the comments, congrats :)
Tl; dr
You missed the important bit you said you was going to going to mention! 😆
That was a master class. Meat, do you think that early-ish 3D game called Stunn Runner can be done? Reason I ask: I used to play it a LOT, but every emulated version feels wrong. I dont know if its something related to timing or some hardware specfiic feature that needs to be implemented the proper way, but something is off.
fascinating to read....made me appreciate your work that much more..
Impressive post. Lots of info behind it. Thanks Meathax!
Took me two years to read this post!
Included a little more info for you :)
I love the older 80s arcade games. Especially obscure older games and prototypes. Thank you so much for this!
Bow wee gra na weep nini bon!
Blahm1d... I'm not a turd nugget!.. jk. I probably am. Thanks Meathax!
Well done 👏🏼👍🏼
I left my book here somewhere
I felt there's more you haven't said
I need more details!!
