tuanp.dev

Part 1 of 20 · about an hour

A CPU that can hold a number

A games console sounds like a big thing to build, and a new programming language sounds like a big thing to learn. We are going to do neither in one go. Today's program is about twenty lines long, and it will already be a real, if very small, piece of a NES.

You can already write small programs in some language: variables, loops, functions. You have never written Rust and you have never looked inside an emulator. That is exactly the right place to start. Today we get the smallest possible thing working: a pretend NES processor that runs a program three numbers long.

By the end of this part

  • You can create a Rust project and run it with one command.
  • You can read a number like $A9 without flinching.
  • Your emulator runs a three-byte NES program and tells you what it did.

Get Rust and make a project

Install Rust by following the one-line instruction at rustup.rs. It gives you a tool called cargo, which creates, builds and runs Rust projects. Check that it is there:

$ cargo --version
cargo 1.99.1 (5f94df478 2026-08-27)

Your version number will differ; any recent one is fine. Now ask cargo for a new project called nes and run it:

$ cargo new nes
    Creating binary (application) `nes` package
$ cd nes
$ cargo run
   Compiling nes v0.1.0 (/home/you/nes)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.11s
     Running `target/debug/nes`
Hello, world!

Cargo wrote a tiny program for you in src/main.rs, and cargo run turned it into a real program and started it. That one file, src/main.rs, is where we will work for the whole course. Every part makes it a little more of a NES.

What a NES does all day

Inside the grey box is a processor chip, the 6502. A game cartridge is, to that chip, nothing but a long list of numbers. The chip reads a number, does the small thing that number stands for, then reads the next number. It does this over a million times a second, and somehow that adds up to a plumber jumping.

Here is a complete program for that chip. It is three numbers long:

Three boxes in a row holding A9, 05 and 00, numbered 0, 1 and 2. A bracket under the first two says "put 5 into A". A bracket under the third says "stop".012A90500"put 5 into A""stop"program
The first two numbers belong together: one says what to do, the next says what to do it with.

Two questions are probably forming. Why does a number have a letter in it? And what is "A"?

Numbers with letters in them

Everything in the NES is made of bytes. What is a byte? A byte is eight on/off switches side by side, which is enough to count from 0 to 255. Each switch is called a bit.

Writing eight ones and zeros every time is tiring, so people split a byte into two halves of four bits. Four bits can count from 0 to 15, and we give each of those sixteen values a single character: 0 to 9, then A for ten, B for eleven, up to F for fifteen. This way of writing is called hexadecimal, or hex for short. What is hexadecimal? It is counting in sixteens instead of tens, so that one byte is always exactly two characters.

The byte A9 drawn as eight bits: 1 0 1 0, then 1 0 0 1. The first four bits are labelled A, meaning ten. The last four are labelled 9. Ten times sixteen plus nine is 169.10101001A8 + 2 = ten98 + 1 = nine10 × 16 + 9 = 169one byte
One byte, two hex digits. A9 is just the number 169 in a spelling that matches the hardware.

To make clear that a number is in hex, people who write for the 6502 put a dollar sign in front: $A9. Rust spells the same thing 0xA9. You will see both in this course: $A9 in the prose, 0xA9 in the code. So $05 is five, $10 is sixteen, and $FF is 255, the biggest value a byte can hold.

What the three bytes mean

The 6502 looks at the first byte, $A9, and treats it as a command. A byte used this way is called an opcode. What is an opcode? An opcode is a byte that tells the processor which operation to carry out. The people who designed the chip decided that $A9 means "take the byte that follows me and keep it in A".

And A? The processor has a few tiny storage slots built into it, each one byte big. They are called registers. What is a register? A register is a one-byte slot inside the processor itself, the only place it can do work on a value. The most used one is named A (the "accumulator").

Programmers gave each opcode a three-letter nickname so they would not have to memorise numbers. $A9 is LDA, "load A". $00 is BRK, "break", which we will use to mean "stop". So our program reads:

A9 05    LDA #$05    put 5 into A
00       BRK         stop

One more thing the processor needs: it must remember which byte of the program it is up to. It keeps that position in a counter called the program counter, or pc. What is the program counter? It is the position of the next byte the processor will read.

That is the whole machine for today: a list of bytes, one register and one counter. Step through it. Use the Next button and watch pc and A.

The pc arrow walks along the three program bytes A9, 05, 00. When it passes A9 and 05, register A changes from 00 to 05. At 00 the loop stops.012A90500A00pcopcode = ?
loop {
    let opcode = program[pc];
    pc += 1;
    match opcode {
        0xA9 => {
            a = program[pc];
            pc += 1;
        }
        0x00 => break,
    }
}
  1. The start. pc is 0, so the next byte to read is the first one. A holds 0.
  2. Read the byte under pc: the opcode is $A9. Step pc past it straight away, so it is ready for whatever comes next.
  3. Look the opcode up. $A9 is LDA: "load the next byte into A".
  4. Do it. The next byte is the one under pc, which is 05. A becomes 05, and pc steps past that byte too.
  5. Round the loop again. Read the byte under pc: the opcode is $00. Step past it.
  6. $00 is BRK: leave the loop. The program is over and A still holds 5.

Read, step, look up, do. Every processor ever made runs this loop, and every emulator is this loop written in software. You have just seen the whole idea; the rest of the course is detail.

Write it in Rust

Open src/main.rs, delete what cargo put there, and type this in. Typing it yourself is slower than pasting and much better for learning.

src/main.rsSnapshot
fn main() {
    let program: [u8; 3] = [0xA9, 0x05, 0x00];

    let mut a: u8 = 0;
    let mut pc = 0;

    loop {
        let opcode = program[pc];
        pc += 1;

        match opcode {
            0xA9 => {
                // LDA: load the next byte into A
                a = program[pc];
                pc += 1;
            }
            0x00 => break, // BRK: stop
            _ => panic!("unknown opcode ${:02X}", opcode),
        }
    }

    println!("A = ${:02X}", a);
}

It is the loop from the picture with a little Rust around it. Line by line, the Rust you have not seen before:

  • fn main() { … } is the function where every Rust program starts.
  • let creates a variable. After the colon comes its type. u8 means "unsigned 8-bit number", which is exactly one byte: 0 to 255. [u8; 3] is a row of three of them.
  • let mut: in Rust a variable cannot change after it is created unless you say mut (for "mutable"). program never changes, so it has no mut. a and pc do change.
  • pc has no type written. Rust works it out from how we use it.
  • loop { … } repeats forever, until a break.
  • match opcode { … } compares opcode with each pattern on the left of a => and runs the code on the right of the first one that fits. The pattern _ fits anything.
  • panic! stops the program with an error message. We use it for opcodes we have not taught our processor yet.
  • println! prints a line. Each {} in the text is a hole for a value; {:02X} is a hole that prints its value as two hex digits.

Run it:

$ cargo run
   Compiling nes v0.1.0 (/home/you/nes)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
     Running `target/debug/nes`
A = $05

The first three lines are cargo talking; the last line is your program. A real 6502 instruction, carried out by a processor you wrote. Change the 0x05 to something else and run it again.

Break it on purpose

Two experiments. Before each one, guess what will happen.

First, slip a byte our processor does not know into the program. Change the program line to:

    let program: [u8; 4] = [0xA9, 0x05, 0xE8, 0x00];
$ cargo run -q
thread 'main' (4102422) panicked at src/main.rs:18:18:
unknown opcode $E8

(The -q tells cargo to be quiet and show only our program's output.) That is our own panic! speaking, and it names the file, line and column it came from. $E8 is a real 6502 opcode. We will teach it to our processor in Part 2.

Second, forget the BRK at the end:

    let program: [u8; 2] = [0xA9, 0x05];
$ cargo run -q
thread 'main' (4102478) panicked at src/main.rs:8:22:
index out of bounds: the len is 2 but the index is 2

We did not write that message. With nothing to stop it, the loop asked for program[2], which does not exist. In many languages that would quietly read garbage. Rust checks every access and stops the program instead. You will come to like this: when your emulator goes wrong, it tends to say so at once.

Put the three-byte program back before you go on.

Shortcuts we took on purpose

  • The program sits in a Rust array, off to the side. On a real NES, program and data share one big memory. Fixed in Part 3.
  • Our processor knows two opcodes. The real one has 151. We add them a few at a time, and only the ones our cartridge needs.
  • BRK does something more complicated on a real 6502. Using it as "stop" is a common emulator-builder's trick; we replace it in Part 6.

What changed today

  • We have a Rust project, nes, that builds and runs with cargo run.
  • A program is an array of bytes; pc walks along it.
  • A loop reads one opcode at a time and a match decides what to do.
  • Our processor knows LDA ($A9) and BRK ($00).

Now you

  1. Write these in hex, then check with a calculator: 16, 32, 100, 255. And the other way: what are $0A, $20 and $80 in ordinary numbers?
  2. The processor has a second register called X. Add a variable for it, and teach your processor opcode $AA, nicknamed TAX: "copy A into X". The program A9 05 AA 00 should leave 5 in both. Print both registers at the end.
    HintIt needs one new let mut line and one new line in the match. TAX has no second byte, so pc does not move again.
  3. Now add $E8, nicknamed INX: "add one to X". Run A9 05 AA E8 E8 00 and check that X ends up as 7. Then change the 05 to FE and run it again. Something surprising happens. Do not fix it; Part 2 starts right there.
  4. Close this page and write today's program again from an empty file. Reading code and being able to write it are different skills, and only the second one builds emulators.

Check your understanding

  1. What is a byte?
    AnswerEight on/off switches (bits) side by side, enough to count from 0 to 255.
  2. What is hexadecimal, and why do we use it?
    AnswerCounting in sixteens, with digits 0–9 and A–F. One byte is always exactly two hex digits.
  3. What is an opcode?
    AnswerA byte that tells the processor which operation to carry out.
  4. What is a register?
    AnswerA one-byte slot inside the processor itself, where it works on a value.
  5. What is the program counter?
    AnswerThe position of the next byte the processor will read.
  6. In Rust, what does mut allow?
    AnswerIt allows a variable to be changed after it is created. Without it, the variable is fixed.

Next time

Right now our processor can hold a number and nothing else. It cannot even add one to it. In Part 2 it learns to count, we find out what a byte does when it runs out of room, and we tidy the loose variables into our first Rust struct.