How Emulators Work: A Look Inside the Game Boy

What an emulator actually does, from fetching CPU instructions to drawing pixels and switching cartridge banks, using the Game Boy and some C# as the example.

Tinkering.NET & code 7 min read

I’m a retro games enthusiast, and I’ve been playing games on emulators for a long time. For me, emulation is about more than nostalgia: it’s how games get preserved. Cartridges wear out, save batteries die, consoles stop working and stop being made, and plenty of games were never re-released. Without emulators, a lot of them would simply be lost to time. As long as an emulator can run a game, anyone can still play it, study it and enjoy it decades later.

I even built a NES console with a Raspberry Pi. But writing an emulator of my own always felt like a real challenge. Emulation is hard: you have to understand how old hardware works down to the clock cycle, and that knowledge is spread across decades-old manuals, forum posts and reverse-engineering notes.

That changed with AI. It let me research how the hardware works much faster, ask questions about the strange corners of a 1989 console and get to the right documentation sooner. That’s how I ended up writing AcidBoy, a Game Boy emulator in C#. In this post I want to explain how an emulator works, using the Game Boy as the example because it’s small enough to understand completely.

What is an emulator?

A game cartridge holds a program written for a specific machine: its CPU, its memory layout, its graphics and sound chips. Your computer can’t run that program directly, because it speaks a different machine language and has none of that hardware.

An emulator is a program that pretends to be that machine. It reads the original game’s bytes and does what the real hardware would have done with them, one instruction at a time. The game has no idea it isn’t running on a real Game Boy.

To pull that off, we need to recreate every part of the console in software:

  • CPU: reads and executes the game’s instructions
  • Memory bus: decides what each address means (ROM, RAM, video memory, hardware registers)
  • PPU (Picture Processing Unit): draws the screen
  • APU (Audio Processing Unit): makes the sound
  • Timers, input and interrupts: the glue that keeps everything talking
  • Cartridge: including the extra chips some games carry

The machine we’re emulating

The original Game Boy (1989) is tiny by today’s standards:

Part Spec
CPU Sharp SM83, a cousin of the Z80 and Intel 8080, at 4.194304 MHz
RAM 8 KB work RAM, 8 KB video RAM
Screen 160 × 144 pixels, 4 shades of green-gray
Sound 4 channels: two square waves, one programmable wave, one noise
Address space 16 bits, so 64 KB visible at once

Everything the CPU can touch lives in that 64 KB address space, which brings us to the first piece.

The memory map

The CPU doesn’t know about “the screen” or “the cartridge”. It only reads and writes addresses from 0x0000 to 0xFFFF. The hardware wires each address range to a different place:

Range What’s there
0000–3FFF Cartridge ROM, bank 0 (always the same)
4000–7FFF Cartridge ROM, switchable bank
8000–9FFF Video RAM (tiles and background maps)
A000–BFFF Cartridge RAM (battery-backed saves live here)
C000–DFFF Work RAM
E000–FDFF Echo RAM, a mirror of C000–DDFF
FE00–FE9F OAM, the sprite table
FF00–FF7F I/O registers (joypad, timer, sound, LCD…)
FF80–FFFE High RAM
FFFF Interrupt enable register

So the heart of an emulator is a bus: a pair of Read and Write methods that route every access to the right component.

public byte Read(ushort address) => address switch
{
    < 0x8000 => _cartridge.ReadRom(address),
    < 0xA000 => _ppu.ReadVram(address),
    < 0xC000 => _cartridge.ReadRam(address),
    < 0xE000 => _wram[address - 0xC000],
    < 0xFE00 => _wram[address - 0xE000],   // echo RAM
    < 0xFEA0 => _ppu.ReadOam(address),
    < 0xFF00 => 0xFF,                      // unusable area
    < 0xFF80 => ReadIo(address),
    < 0xFFFF => _hram[address - 0xFF80],
    _        => _interruptEnable,
};

Notice that the joypad, the sound chip and the LCD are all just addresses too. When a game wants to know if you pressed A, it reads 0xFF00. When it wants to change the background scroll, it writes 0xFF42. This is called memory-mapped I/O, and it means a lot of emulation is answering “what happens when someone reads or writes this byte?”.

The CPU: fetch, decode, execute

A CPU is a loop. It reads the byte at the program counter (PC), figures out which instruction that byte is, does it, and moves on. That’s the whole idea:

public int Step()
{
    byte opcode = Read(PC++);   // fetch
    return Execute(opcode);     // decode + execute, returns cycles used
}

The SM83 has eight 8-bit registers (A, F, B, C, D, E, H, L), which can be paired into 16-bit registers (BC, DE, HL), plus a stack pointer and the program counter. F holds the flags:

  • Z: the result was zero
  • N: the last operation was a subtraction
  • H: a carry from bit 3 to bit 4 (half carry, used for decimal math)
  • C: a carry out of bit 7

There are 256 main opcodes plus 256 more behind the 0xCB prefix. Most emulators implement them as a big switch:

private int Execute(byte opcode)
{
    switch (opcode)
    {
        case 0x00:                  // NOP
            return 4;

        case 0x3E:                  // LD A, n8
            A = Read(PC++);
            return 8;

        case 0x80:                  // ADD A, B
            Add(B);
            return 4;

        case 0xC3:                  // JP a16
            PC = ReadWord(PC);
            return 16;

        // ...and about 500 more
    }
}

private void Add(byte value)
{
    int result = A + value;
    FlagZ = (byte)result == 0;
    FlagN = false;
    FlagH = (A & 0x0F) + (value & 0x0F) > 0x0F;
    FlagC = result > 0xFF;
    A = (byte)result;
}

That Add method is where a lot of emulator bugs live. Get the half-carry flag wrong and most games still boot, but some score counter, somewhere, shows the wrong number.

The good news is that the instruction set is very regular. Opcodes 0x40 to 0x7F, for example, are almost all LD r, r and follow a bit pattern, so you can decode them in a few lines instead of 64 cases. The gbdev opcode table lists every instruction with its length, cycles and flags.

Timing is everything

Running instructions isn’t enough. Every part of the Game Boy runs off the same clock, and games depend on the parts staying in step. That’s why Execute returns a number of cycles.

The screen takes exactly 70,224 cycles per frame (154 lines × 456 cycles per line), which gives the Game Boy’s odd refresh rate of about 59.73 frames per second. So the main loop looks like this:

const int CyclesPerFrame = 70224;

public void RunFrame()
{
    int elapsed = 0;
    while (elapsed < CyclesPerFrame)
    {
        int cycles = _cpu.Step();
        _ppu.Tick(cycles);
        _timer.Tick(cycles);
        _apu.Tick(cycles);
        elapsed += cycles;
    }
}

The CPU runs an instruction, then every other component catches up by the same number of cycles. This is the simplest approach and it runs most games fine.

The problem is that real hardware doesn’t work in whole instructions. A 16-cycle instruction reads memory at specific points along the way, and some games (and nearly all test ROMs) notice if a read happens 4 cycles too early. AcidBoy goes further and times its memory accesses per M-cycle (4 clock cycles), which is called M-cycle accuracy. It costs more CPU time, but it’s how you pass the timing tests.

This is the central trade-off in emulation: accuracy versus speed. A fast emulator takes shortcuts that work for 95% of games. An accurate one models the hardware closely enough that the remaining 5% work too.

Drawing the screen

The PPU draws the screen one line at a time, and each line goes through a set of modes:

Mode Cycles What happens
2: OAM scan 80 Find the (up to 10) sprites on this line
3: Drawing 172–289 Push pixels to the LCD
0: HBlank the rest of 456 Idle until the next line
1: VBlank lines 144–153 Idle for 10 lines before the next frame

Games use these modes. VBlank is the safe moment to update video memory, so most games do their drawing work there. Others change the scroll registers in HBlank to make wavy or split-screen effects. If your PPU gets the timing wrong, those effects break.

The Game Boy doesn’t have a framebuffer the game can draw into. Instead, graphics are built out of tiles: 8 × 8 pixel blocks, 2 bits per pixel, 16 bytes each. Every row of a tile is two bytes, and each pixel takes one bit from each:

// Returns a color index (0-3) for pixel x of one tile row.
static int PixelColor(byte low, byte high, int x)
{
    int bit = 7 - x;
    return ((high >> bit) & 1) << 1 | ((low >> bit) & 1);
}

The background is a 32 × 32 grid of tile numbers. The PPU reads the tile number for each position, looks up the tile, picks the right row, and turns each color index into a shade through the palette register at 0xFF47. Then it draws the window layer and the sprites on top, following the priority rules.

The Game Boy Color adds palettes with real colors, more video memory and a few attributes per tile, but the model is the same.

Interrupts

How does a game know a frame is done, or that you pressed a button? Interrupts. When the PPU enters VBlank, it sets a bit in the interrupt flag register (0xFF0F). If that interrupt is enabled in 0xFFFF, the CPU stops what it’s doing, pushes PC on the stack and jumps to a fixed address:

Interrupt Jumps to
VBlank 0x0040
LCD STAT 0x0048
Timer 0x0050
Serial (link cable) 0x0058
Joypad 0x0060
private int HandleInterrupts()
{
    int pending = _interruptEnable & _interruptFlag & 0x1F;
    if (!IME || pending == 0) return 0;

    int bit = BitOperations.TrailingZeroCount(pending);   // lowest bit wins
    _interruptFlag &= (byte)~(1 << bit);
    IME = false;
    Push(PC);
    PC = (ushort)(0x40 + bit * 8);
    return 20;
}

Many games spend most of their time in a HALT instruction, sleeping until the next VBlank interrupt wakes them up. Get interrupts wrong and the game simply freezes.

Cartridges are hardware too

The CPU can only see 32 KB of ROM at once (0000–7FFF), but Pokémon Red is 1 MB. How?

Bigger cartridges carry a Memory Bank Controller (MBC), a chip that swaps which part of the ROM appears at 4000–7FFF. The game switches banks by writing to ROM addresses, which would do nothing on a plain cartridge but are picked up by the MBC:

// MBC1: a write to 0x2000-0x3FFF selects the ROM bank.
public void WriteRom(ushort address, byte value)
{
    if (address < 0x2000)
        _ramEnabled = (value & 0x0F) == 0x0A;
    else if (address < 0x4000)
        _romBank = Math.Max(value & 0x1F, 1);   // bank 0 is mapped as 1
}

public byte ReadRom(ushort address) => address < 0x4000
    ? _rom[address]
    : _rom[_romBank * 0x4000 + (address - 0x4000)];

Other MBCs add a real-time clock (Pokémon Gold and Silver use one to track day and night) or a rumble motor. Each one is a small piece of extra hardware the emulator has to model. The cartridge header at 0x0147 tells you which one the game expects.

Sound

The APU generates four channels of audio and mixes them. The emulator steps it with the same cycles as everything else, samples its output at your sound card’s rate (say 48,000 times per second), and sends those samples to the speakers.

Audio is also a useful clock. Your monitor might refresh at 60 Hz or 144 Hz, while the Game Boy runs at 59.73. If you sync to the monitor, the game runs at the wrong speed; if you sync to the audio buffer, you get the right speed and no crackling, as long as you keep the buffer fed.

How do you know it’s right?

You can’t just play a few games and call it done. The emulation community has built test ROMs: small programs that run on real hardware and check one behavior at a time.

  • Blargg’s tests check every CPU instruction, its flags and its timing, then print “Passed” or “Failed”.
  • dmg-acid2 and cgb-acid2 by Matt Currie draw a face using a pile of PPU edge cases. If any rule is wrong, the face comes out broken.
  • The Mooneye test suite covers the fine details of timing and cartridge controllers.

cgb-acid2 rendering correctly in AcidBoy

AcidBoy passes Blargg’s CPU and timing tests and both acid tests, and I ran them constantly while writing it: they catch regressions long before you’d notice them in a game.

A note on legality

Emulators themselves are legal: they’re original code that reproduces how hardware behaves. Games and console boot ROMs are copyrighted, though, so an emulator shouldn’t ship with them. AcidBoy includes no games and no boot ROMs. Use cartridges you own (there are cheap USB dumpers for that) or the large library of homebrew games people still make for the Game Boy today.

Where to start

If this made you want to write your own, the Game Boy is a great first real console (some people start with CHIP-8, which takes a weekend). These are the best resources to start with:

  • Pan Docs: the reference for every register and behavior.
  • gbdev opcode table: every instruction, its length, its cycles and its flags.
  • The Ultimate Game Boy Talk by Michael Steil: an hour that explains the whole console.
  • The test ROMs above: start running them as soon as your CPU boots.

My advice is to start with the CPU and Blargg’s cpu_instrs, get the background drawing with a simple game like Tetris, and only then worry about timing. And if you want to see where all of this ends up, AcidBoy is open source on GitHub, and you can read more about it on its project page.

Thanks for reading!

Share this article

Written by

Gustavo Barrientos

Azure AI Certified Engineer | 15+ yrs in full-stack, cloud & AI architecture | Building intelligent, production-ready systems with .NET & LLMs

About Get in touch