Skip to content
sadovskyPublic

About

A VT100 terminal for the NES in 6502 assembly, with serial over the controller port: a real Linux shell on a NES (in the Mesen emulator, so far).

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

nes-ssh: a VT100 terminal for the NES

A VT100 terminal emulator for the NES, in 6502 assembly: 32x28 characters, an 8x8 font in CHR-ROM, a serial line on the controller port, a Family BASIC keyboard to type on. Bridge the serial line to a pty and you get a real Linux shell on a NES.

A shell session on the NES: uname, ls, vim scrolling through its own source, seq, top

That is the ROM running at real NES speed in the Mesen emulator, with a real bash on the other end (same clip as MP4). Nothing here has run on a physical console yet. On a real console says what that would take. There is a shorter write-up at manvsmidi.com/projects/nes-ssh.

A shell prompt on the NES after uname, ls and wc vim on the NES showing the top of src/video.s top on the NES with its reverse-video header row

In plain words

This is a homemade NES "game" that turns the console into an old-style computer terminal: a screen that shows text and a keyboard you type on. The NES is not running Linux. A normal PC runs Linux, and the NES is only its screen and keyboard, like a TV showing what another computer is doing.

  • How they talk: through the controller port. Instead of "is button A pressed?", the wire carries letters, one bit at a time.
  • The hard part: the NES can only change about a fifth of the screen per frame, so it cannot redraw everything when text scrolls. It leaves the text where it is and tells the video chip to draw the rows in a different order.
  • What you get: 32x28 characters of text, enough for a shell, vim and top.
  • What it is: about 2,500 lines of 6502 assembly.

The name is the goal rather than the mechanism. You do not SSH into the NES; the NES is the terminal. Run host/bridge.py ssh somewhere and the NES is the screen and keyboard of that SSH session, while the SSH client and its cryptography run on Linux.

Quick start

tools/setup.sh          # fetches and builds cc65, fetches Mesen 2 into tools/
make                    # -> build/vt100.nes
host/bridge.py          # terminal 1: waits for the NES, then runs your shell
make run                # terminal 2: Mesen with the ROM and the serial adapter

make run is Mesen build/vt100.nes mesen/nes_serial.lua. With your own Mesen 2, open the ROM, load mesen/nes_serial.lua in Debug > Script Window, and in the script window's settings turn on Allow access to I/O and OS functions and Allow network access (the adapter is a TCP client).

bridge.py runs $SHELL -l on a 32x28 pty with TERM=vt100; give it a command to run something else:

host/bridge.py ssh example.com
host/bridge.py --keys           # also type from the bridge's own terminal

Mesen on Windows with the bridge in WSL should work through WSL's localhost forwarding (not tested). If it does not, run bridge.py --listen 0.0.0.0 and set NESVT_HOST to the WSL address before starting Mesen, and read the warning below first.

Typing

The ROM's NES 2.0 header asks for a Family BASIC keyboard, which Mesen connects automatically and maps to your PC keyboard (emulator shortcut keys are off while it is connected). The default layout assumes Mesen's default key bindings and a US keyboard, so keys produce what is printed on them, with these exceptions:

PC key sends
F9 Tab (the keyboard has no Tab key; rebind Mesen's @ key to Tab if you like). Ctrl+I also works
Left Alt (GRPH) Meta: prefixes ESC
Backspace (DEL) DEL (^?)
Insert / Delete / Home / End ESC[2~ / ESC[3~ / ESC[1~ / ESC[4~
F1-F8 PF1-PF4, then ESC[15~ ...

make LAYOUT=JIS builds the layout printed on the real keyboard instead (STOP sends ^C, KANA sends Tab).

How the pieces connect

Family BASIC keyboard
        |
        v
NES running vt100.nes ----> screen, 32x28 characters
        ^
        |  controller port 2: three wires, the NES supplies the clock
        v
serial adapter              in Mesen: mesen/nes_serial.lua
        ^
        |  TCP, 127.0.0.1:6502
        v
host/bridge.py
        ^
        |  pty, 32x28, TERM=vt100
        v
bash, vim, ssh, ...

The NES has no network stack and is not on a network. The only network piece is one TCP connection between the adapter and bridge.py, and by default it never leaves the machine: the bridge listens on 127.0.0.1 only.

That port has no authentication. Whoever connects to it gets a shell as the user who started the bridge. On the loopback address that means local processes. With --listen 0.0.0.0 it means anyone who can reach the port, so only do that on a network you trust.

Scrolling with the PPU

The PPU can scroll a whole picture for free, and that is all it can do. A terminal needs more: scroll regions, reverse index, insert and delete line. Copying is not an option. One vblank has time for about 200 tile writes, a screen has 896.

The line table. The two nametables ($2000 and $2400, side by side) hold 60 physical text rows. A table says which physical row each of the 28 screen rows is shown from. The rest are free and kept blank. Scrolling, in any direction and over any region, permutes the table and blanks one row (a 32-byte fill). Characters never move.

The ring. The PPU's vertical scroll wraps from row 29 to row 0 of the same nametable, so the 30 rows of a nametable form a ring. When a region scrolls up, the new bottom row is taken from the ring position after the row above it whenever that is free. A plain full-screen scroll therefore walks around the ring of nametable 0 and is displayed with nothing but the Y scroll register. The two spare rows of the ring are the blank margins that overscan hides on a TV.

Seams. Where neighbouring screen rows are not ring neighbours (a status line that stays put, a scroll region, lines inserted in the middle) the frame has a seam. The line table is compiled into a list of seams, and an MMC3 scanline IRQ rewrites the PPU address at each one, timed so the write lands in hblank. With vim or less that is typically one or two seams. The worst case is one per text row, which works too.

Atomic frames. The main thread never touches the PPU. It queues update packets (copy and fill) and tracks the vblank time they will need. A deadline IRQ late in the frame tells it to commit. The NMI handler then plays the queue, switches seam lists and moves the cursor in a single vblank, so no frame shows a half-finished scroll. While the terminal waits for vblank it does not clock in serial data, which is all the flow control needed.

The details are in src/video.s.

The serial line

A terminal needs a stream of bytes in and out, and the controller port is the only general-purpose I/O a NES has: no UART, no network hardware, no disk. The port is already serial. A controller is a shift register that the console latches and then reads one button per clock pulse. The terminal uses the same signals to shift whole bytes both ways.

wire register use
OUT0 $4016 bit 0, write data to the adapter
CLK pulses on each $4017 read clock
D0 $4017 bit 0, read data from the adapter

An exchange starts with a sync: OUT0 pulsed high and low with no clock in between. On the first clock each side says whether it has a byte (the NES on OUT0, the adapter on D0). If either does, eight more clocks move one byte each way, MSB first. The keyboard shares these lines but never produces a sync, so the adapter ignores it.

The NES is the clock master, so there is no baud rate and no overrun. A UART would need a timer the NES does not have, and the NES goes deaf whenever it is busy with video. Here the other side simply waits until it is clocked.

mesen/nes_serial.lua plays the adapter inside Mesen and forwards the bytes over TCP to host/bridge.py, which owns the pty. It works at the level of the $4016/$4017 registers, so the ROM is written as it would be for hardware.

Throughput is about 3 to 4.7 kB/s of NES time (test/throughput.py), depending on how much scrolling the text causes. The link is not the limit; parsing and drawing are.

On a real console

Everything above has only run in Mesen. No cartridge and no adapter have been built. This section is the plan for making it physical, with what is known separated from what is open. Pinouts and electrical facts are from the NESdev wiki.

The cartridge

The ROM is a plain mapper 4 (MMC3) image: 32K PRG-ROM, 8K CHR-ROM, 8K PRG-RAM with no battery, NTSC timing.

  • Quick route: a flash cartridge with MMC3 support.
  • A cartridge of its own: an MMC3 board that has PRG-RAM, which means TKROM or TSROM. Those boards take 128K or larger ROMs, so the 32K and 8K images are repeated to fill the chips.

What should carry over, and why:

  • The ROM does not rely on power-on state. It clears RAM, cartridge RAM and both nametables, waits for the PPU to warm up, and writes every MMC3 register it uses. The test suite passes with Mesen set to random power-on memory, random mapper state and random CPU/PPU alignment. (That run found one bug, since fixed: sprite memory was shown for a frame before it had been loaded.)
  • The scanline counter is used in the standard way: background tiles at $0000, 8x8 sprites at $1000. The ROM never asks for an IRQ fewer than three scanlines after the previous one. MMC3 revisions are known to differ for a reload value of 0, which it never uses.
  • The mid-frame PPU writes land on dots 275 to 296 of the scanline in Mesen. The safe window is roughly dots 258 to 318, so there are about six CPU cycles of slack on either side. Mesen is cycle-accurate, which makes this a good prediction, and it is still a prediction.

Not supported: PAL consoles. The timing constants are for NTSC.

The serial adapter

Five of the seven pins of controller port 2:

pin signal role
+5V, GND power powers the adapter
OUT $4016 bit 0 data to the adapter, and the sync pulse
CLK goes low during each $4017 read bit clock
D0 $4017 bit 0 data from the adapter

What the adapter has to get right:

  • Levels. The port is 5 V logic. A 3.3 V microcontroller needs level shifting.
  • D0 is inverted. The console inverts the data lines, so the adapter pulls D0 low to send a 1. With nothing plugged in the line reads 0, which the protocol takes as "no byte for you", so the ROM runs fine without an adapter.
  • Clock edges. Like a controller's shift register, the adapter must have a bit on D0 before the clock pulse and move to the next bit on the rising edge that ends it. OUT0 is stable from before the pulse until well after it.
  • Speed. While receiving, the ROM reads a bit every 11 CPU cycles, about 6 µs (160 kHz), and the first clock comes about 7 µs after the sync. That is easy for a shift register and too fast for bit-banging from an interrupt handler. A PIO program on an RP2040, an SPI-slave peripheral (the link is SPI-shaped, with 9-bit frames and the sync pulse in place of chip select) or a small CPLD would do. If it is still too tight, the ROM's bit loop can be padded: each NOP adds 1.1 µs per bit, and the link has time to spare.
  • The keyboard's traffic. The keyboard scan toggles OUT0 and clocks $4017 too. It always clocks while OUT0 is high, so a sync detector that wants "high, then low, no clock in between" never fires on it.
  • Flow control. The adapter holds bytes from the host until the NES clocks them out, and must make the host wait when its buffer is full.

On the host side bridge.py only speaks TCP today. An adapter that shows up as a USB serial port could be joined to it with something like socat /dev/ttyACM0,raw,echo=0 TCP:127.0.0.1:6502 (untested), or the bridge could grow a serial mode.

The keyboard

The ROM reads a Family BASIC keyboard (HVC-007), a real Nintendo accessory that was made for the Japanese Famicom. It plugs into the Famicom's 15-pin expansion port and needs three outputs (OUT0 to OUT2) and four inputs ($4017 bits 1 to 4). A NES controller port carries only OUT0 and, of those inputs, bits 3 and 4. So on a NES the keyboard cannot go on a controller port.

console keyboard serial adapter ROM changes
AV Famicom expansion port, as designed controller port 2 none expected
Original Famicom expansion port must share the expansion port, and cannot use $4017 bit 0: the built-in player 2 pad drives it the link's input has to move to another line
Front-loading NES its signals are all on the 48-pin expansion connector under the console, which needs a breakout board controller port 2 none expected
any none: type on the host with bridge.py --keys controller port 2 none

The AV Famicom is the one machine where everything plugs in as designed. The last row works everywhere and makes the NES a display only.

The keyboard code already follows the timing the hardware needs (about 50 cycles for the matrix to settle after each column select, 12 after the reset). Mesen does not model that, so it is untested.

Where SSH would live

With the bridge, SSH is host/bridge.py ssh somewhere: the client runs on Linux and the NES sees only the terminal stream.

A stand-alone version would put Wi-Fi and the SSH client in the adapter, so that the console, a keyboard and the adapter make an SSH terminal with no PC. The cryptography would still not be on the 6502. With 2K of RAM plus 8K on the cartridge and no multiply instruction, the adapter is the practical place for it. That is not built either.

A sensible order

  1. The ROM on a flash cartridge, nothing in port 2. It should show its banner and a blinking cursor. This checks the video and IRQ timing.
  2. The adapter on port 2, typing on the host.
  3. The keyboard, by one of the routes above.

What it understands

  • Cursor movement (CUU/CUD/CUF/CUB, CNL/CPL, CHA/HPA, VPA, CUP/HVP), tabs (HT, HTS, TBC), index, reverse index, next line, save/restore cursor
  • Erase in line and display, erase/insert/delete character
  • Scroll regions (DECSTBM), insert/delete line, scroll up/down
  • Autowrap with VT100 pending-wrap behaviour, origin mode, cursor keys mode, cursor visibility
  • Reverse video. Bold, underline, blink and colours are parsed and ignored: the NES cannot colour single 8x8 cells
  • G0/G1 with the DEC special graphics (line drawing) set
  • Device status, cursor position and device attribute reports
  • OSC/DCS strings are swallowed, UTF-8 characters show as a box, BEL beeps

Not implemented: 80/132 columns, double-size lines, smooth scroll, the alternate screen, insert mode. Use TERM=vt100; xterm descriptions assume more.

Tests

make test                           # everything
python3 test/run_tests.py fuzz 150 7   # 150 random streams, seed 7
python3 test/throughput.py

The tests run the ROM in headless Mesen and read the screen back from the rendered picture, matching every 8x8 cell against the font, so raster splits are covered. Hand-written cases and random streams are compared with pyte, corrected in test/nesvt.py where it deviates from a VT100. Other tests script the keyboard matrix and inspect every frame of a long scroll to check that commits are atomic. Each run also reports where the mid-frame PPU writes landed and when vblank work finished.

They need pyte and Pillow, and Mesen at tools/mesen/Mesen (or $MESEN) with Lua file access enabled, which tools/setup.sh arranges.

Layout

src/vt100.s     memory map, header, reset, main loop
src/video.s     update queue, line table, seams, NMI and IRQ handlers
src/term.s      escape sequence parser and screen operations
src/serial.s    serial link
src/kbd.s       keyboard scan and key translation
tools/          font and keymap generators, setup script
mesen/          the serial adapter for Mesen (Lua)
host/           the pty bridge
test/           test rig

Mapper 4 (MMC3), 32K PRG, 8K CHR, 8K PRG-RAM (a copy of the 60 rows), NTSC timing.

Licence

MIT. See LICENSE.

About

A VT100 terminal for the NES in 6502 assembly, with serial over the controller port: a real Linux shell on a NES (in the Mesen emulator, so far).

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages