Sample programs
Each sample is a single, self-contained C file that builds to a .lnx cartridge image. They double as worked examples of this fork’s Lynx-specific features — the static Lynx graphics, joystick and serial libraries, and the Suzy hardware-math operators !* !/ !%. Build any one with the command shown, or run make in examples/ to build them all. Each entry carries a screenshot captured by booting its .lnx on the headless GearLynx emulator (tests/emu/gearlynx).
Getting started
lynxdemo.cstarter

The smallest complete Lynx program in the tree — the place to start.
- Uses the static Lynx graphics library: no driver to install, just
gfx_init(). - A single hardware-scaled sprite bounces around a double-buffered screen.
- Fractionally scaled text is drawn on top each frame.
standaloneown Makefile

The barest self-contained project in the tree — the one to copy out and start from nothing.
- Unlike every other sample, it is not built by the shared
examples/Makefile: it carries its own one-linecl65build rule, so the directory works after you copy it out of the SDK tree and rename it. - Does only the minimum to put text on screen:
gfx_init()brings up the static Lynx graphics library (no driver to load),gfx_setdefpalette()loads the built-in default palette, and onegfx_clear()/gfx_outtextxy()/gfx_updatedisplay()pass draws the message. - No game loop and no input: it renders a single frame and holds it, so the whole program fits in one screenful of C.
Games
breakout.cSuzy math

Single-file Breakout, built to exercise the fork's Suzy hardware math in real game code.
- Paddle deflection, brick-grid hit testing and score formatting all run on Suzy's 16×16 multiply and 32/16 divide (
!*!/!%) instead of software loops. - The whole scene — 32 bricks, paddle and ball — is one SCB chain drawn with a single
gfx_sprite()call; dead bricks are skipped with the SKIP bit. - All math sites stay in the main loop (never in IRQ), honouring the Suzy math contract.
invaders.ccolour + sound

Single-file Space Invaders — a companion to breakout that adds colour and audio.
- Coloured enemies: every invader shares one sprite image; its row colour comes from the SCB penpal, and the RGB behind each pen is repainted from a 12-entry rainbow LUT so colour flows down the formation with zero extra sprite data.
- Music + effects: channels C and D play the two-voice Space Invaders theme as compiled
snd-engine streams (invtheme.s, extracted from the reference cartridge as interlocking pattern/loop sequences over a shared attack envelope); the streams self-loop while the interrupt walks them. Channels A and B stay hand-driven for laser and explosion noise (death/UFO share channel A) with per-frame volume envelopes. - Suzy math lays out the grid, does the hit-test lookup, paces the march and formats the score.
lander.cphysics

A complete lunar-lander — MOON LANDER — with Newtonian flight, a fuel budget, randomised terrain and a full title menu, instructions screen and land / crash prompts.
- Rotate the module and fire the descent engine against gravity; touch down slow, upright and on a flat pad to score, with narrower pads worth more. Position and velocity are 7.7 fixed point; a 24-entry sin/cos table turns the ship's heading into a thrust vector, so no trigonometry runs on the 6502.
- The lander and its exhaust are pre-rendered rotation sprite sheets — 24 headings each, sliced from
lander.pcxandflame.pcxbysp65 --sprite-sheet— so drawing a heading is one table index. Terrain columns, pads and stars are one solid sprite stretched and recoloured through each SCB pen palette, and the whole scene is onegfx_sprite()chain per frame. The HUD read-outs and landing score use the Suzy operators!*!/!%in the main loop. - Four-channel audio through the snd engine: a calm menu loop and a driving melody-plus-bass game theme (compiled by
abcccfrom the committed.abctunes), a looping engine roar from thesfxpack while the thruster burns, and one-shot touchdown / crash blips.
raycaster.cscaled sprites

A Wolfenstein-3D-style raycaster that leans on five things Lynx hardware makes cheap.
- Hardware sprite scaling as a fill primitive: each vertical wall slice is one 2×1 solid sprite stretched by the SCB's vsize field — 80 scaled sprites paint the 3D view with no per-pixel plotting, and the same trick fills the ceiling band and the whole status-bar panel.
- Suzy hardware math throughout the main loop: the first in-cell step is a hardware multiply (
!*), and the billboard and hitscan projections are the fork's fused multiply-divide (lat !* projh !/ depth, one 32-bit operation). The per-column DDA delta-distances and slice height were hardware divides but are now reciprocal-table lookups built once at startup, so the wall cast issues no divide at all. None runs in an IRQ, so the math unit is never contended. - Cheap per-frame ray setup: the camera-plane sweep is stepped incrementally with a 32-bit add instead of a per-column divide-plus-multiply — and because those per-column values depend only on the view angle, the ramp runs only on frames the player turns; walking reuses the cached tables, a frame where nothing moved skips the wall cast entirely, and the DDA inner loop is add/index/load/test on a flat 256-byte map with its hot scalars in the zero page.
- A Wolfenstein-style status bar across the bottom 22 rows — animated soldier face plus wave, score, health and enemies-left. Because it is opaque the 3D view is rendered only into the top 80 rows, a third fewer scaled-sprite fill pixels than a full-screen view.
- One master sprite chain: sky, floor, all 80 wall columns, the billboard guards, the gun, the muzzle flash and the three status-bar pieces are linked back-to-front through their SCB
.nextpointers and painted by a singlegfx_sprite()launch, so chain order is z-order, the CPU issues one sprite call per frame instead of ~90 — and because the chain members are opaque and cover every row between them there is no per-frame screen clear at all.
sybil.cplatformer

A single-screen Super-Mario-Bros.-style platformer starring Sybil.
- Multi-colour 16×16 hardware sprite with true transparency: Sybil uses an identity SCB penpal (pixel value N → pen N), so her ten colours come straight from the 12-bit palette and pixel value 0 is the transparent pen of a
TYPE_NORMALsprite. Idle / run / jump animation just swaps the data pointer; left-facing frames are pre-mirrored arrays. - Sprite scaling as a fill primitive: every platform is one 8×8 solid block sprite stretched to size with the SCB
hsize/vsizefields — a brown body plus a green cap, no tile map. - Direct Mikey audio (no driver): channel A = jump, B = coin / stomp, C = win & game-over jingles, D = ouch. Suzy math (
!*!/!%) formats the score and does coin scoring, all in the main loop.
tetris.cpuzzle

A complete falling-block puzzle — TETROIDS — with a title menu, an instructions screen and the seven tetromino shapes.
- A menu (Start / Instructions), a controls screen, gameplay and a game-over prompt, all driven by one state machine in the main loop.
- The whole scene — grey well frame, every settled cell, the falling piece and the next-piece preview — is a single SCB chain drawn with one
gfx_sprite()call. One 4×4 block image paints all seven piece colours plus the frame purely through per-SCB pen palettes (comparebreakout.c). - Wall-kick rotation, hard drop and a level curve that shortens the drop interval as rows clear. Score formatting and the level-scaled line award use the Suzy hardware operators
!*!/!%, all in the main loop.
Suzy hardware
muldivtest.ccorrectness

An on-hardware correctness test for the Suzy math operators !* !/ !%.
- Six sweeps over a corner-value table compare each Suzy result against an independent software reference, in signed and unsigned variants.
- Divisors 1, 127, 255 (narrow), 256 (boundary) and wide values exercise both sides of the small-divisor normalisation shift.
- Shows pass/total per sweep and the first failing case; “ALL PASS” means every case matched.
spritetest.cbuild-time packing

The offline counterpart to packtest: sprite data packed at build time by sp65, not at runtime.
- The Makefile runs the in-tree
sp65sprite converter (-c lynx-sprite,mode=packedandmode=literal) overheart.pcxto emit two C headers, which the sample#includes and drops straight into an SCBdatapointer — no runtime packer in the ROM. - Both encodings of the same 16×16 image are drawn side by side at 3× scale with one identity-penpal
SCB_REHV_PAL; only thePACKEDbit ofSPRCTL1and the data pointer differ, so the columns must be pixel-identical while the packed block is the smaller asset. heart.pcxkeeps pen 0 along both side edges, so no scan line ends on an odd pen value and Suzy's last-pixel bug needs no pad byte; the PCX itself is reproduced byheart.pcx.py.
spritesheet.csprite sheet

Sprite sheets the easy way: sp65's --sprite-sheet driver turns one image into one indexable frame table.
- One source image,
sheet.pcx(a 4-frame, 16×16 bouncing-ball strip generated bysheet.pcx.py), is sliced in a singlesp65 --sprite-sheetcall that emits one header: asheet_anim_data[]blob plus a generatedsheet_anim[]pointer table and asheet_anim_COUNTdefine. - Animating is just
scb.data = (unsigned char *)sheet_anim[frame]— no per-frame files, no hand-written table. - The frame data is byte-for-byte identical to the manual
--slicechain inspriteslice.c; only the packaging differs (verified on GearLynx, framebuffer read-back).
spriteslice.cslice + pop

Sprite sheets the manual way: sp65's --slice/--pop chain, no special tooling.
- Reads the same
sheet.pcxonce and dices it into four standalone headers (frame0…frame3) in onesp65run, popping back to the whole image between cells. - Because each header is an independent
const unsigned char frameN[]sprite, the program gathers them into its ownframes[]table and tracks the count itself — the hand-work the driver inspritesheet.cremoves. - Draws the identical bouncing ball, proving the two routes produce the same frames; the right choice when you only want a few frames or want per-frame control.
sprpcktest.csprpck BMP + SPS

The sprpck counterpart to spritetest: sprites packed offline from the two input formats sp65 cannot read — a Windows BMP and a plain-ASCII SPS file.
- The Makefile runs the vendored
sprpck(tools/extern/sprpck) twice:-t6 -s4 logo.bmp logo.sprpacks an indexed BMP, and-t2 -i016016 -s4 icon.sps icon.sprpacks the ASCII star inicon.sps(one hex digit per pixel, space = pen 0). - sprpck writes the packed sprite as a raw binary
.spr, not a C array, sosprpckdata.spulls both in with ca65.incbinand the C side reaches them asexternarrays — the idiomatic way to link sprpck output. - One SCB with a shared 16-pen palette draws both: the crystal in the BMP's compacted pens 1–3 (sprpck also emits a matching
logo.pal), the star in its SPS pens 6 and 8. Default sprpck output isPACKED, so the SCB carries the packedSPRCTL1bit.
spritefx.ctransforms + action point

An interactive tour of Suzy's four sprite transforms — hsize, vsize, stretch and tilt — and of where a sprite's action point sits.
- One shape (cube / crystal / star / ball) is drawn around a fixed on-screen anchor and the selected transform is animated back and forth, so the picture visibly grows or shears outward from the anchor while the anchor pixel never moves. A bright magenta cross (a separate
marker.pcxsprite whose own action point is its centre) is drawn at that anchor every frame to make the pivot unmistakable. - The action point is baked into the sprite data by
sp65, not the SCB, so the Makefile compacts each shape five times —ax,ayat the four corners and the centre — and the program keeps a 4×5 table of the results. Cycling the action point swaps only thedatapointer; every SCB scale field stays byte-for-byte identical, yet a scaled or sheared shape lands somewhere else because it now pivots about a different pixel. The centre variant is a true four-quadrant sprite, the case thehsizeoff/vsizeoff$007Fcorrection (set once at start-up) exists to serve. - The four shapes use disjoint pen ranges baked in by
spritefx_shapes.py, so one 16-entry palette and an identity SCB penpal colour all of them;sp65picks each shape's bit depth from its highest pen index and the program reads the generated_COLORSdefine back to set the matchingSPRCTL0depth.
suzyasync.casync math

A realistic use of the fork's asynchronous Suzy math (start / poll / harvest).
- A perspective starfield: each star's screen position is a perspective divide, exactly the repeated divisor-varying divide the async API is built for.
- The per-star projection is software-pipelined so the slow signed divide overlaps real, non-Suzy CPU work (depth update, screen-bounds culling).
- A one-time self-check compares async results against the software operators; the HUD shows MATH OK or MATH FAIL.
suzyasyncbench.casync speed

An honest speed benchmark for the asynchronous Suzy math API.
- For three workload sizes (no / light / heavy work) it times SOFT (software divide), SYNC (blocking Suzy) and ASYNC (overlapped Suzy) per divide.
- ASYNC runs unrelated CPU work in the shadow of the divide; the crossover where it overtakes SYNC is the whole point — with no overlap work it is honestly slower.
- Every loop cross-checks SOFT, SYNC and ASYNC so a speed win is never a correctness loss.
suzybench.caccuracy + speed

The thorough accuracy-and-speed test for the synchronous Suzy math operators.
- Correctness: each Suzy result is checked against the stock software operator over a corner cross-product plus a pseudo-random sweep, exercising all five runtime routines.
- Speed: a free-running 24-bit, 1µs Mikey timer times software vs Suzy loops over identical operands, for both 8-bit and 16-bit widths.
- A final screen pits cc65's compile-time strength reduction (shifts, AND masks, mulaxN helpers) against Suzy doing the same arithmetic.
packtest.cpacked vs literal

On-hardware proof that Suzy's PACKED (RLE) sprite encoding is interchangeable with the LITERAL encoding, at every depth.
- For each of the four Suzy depths (1/2/3/4 bpp) it draws the same 16×16 source image twice at 1× scale: a
LITERALcopy as the control and aPACKEDcopy built at runtime by an in-programpack_line()encoder. - The source is deliberately adversarial — a vertical rainbow on top (every pen value, all adjacent pixels distinct: exercises literal packets and the value→pen map) over solid horizontal bands (exercises RLE runs).
- Identity penpal and a
TYPE_NORMALsprite, so pixel value v draws pen v and value 0 is transparent; the literal copy carries the per-line pad byte and the packed copy's00000terminator supplies the same trailing slack for Suzy's last-pixel bug. If packing is correct the two columns are pixel-identical (verified on GearLynx, framebuffer read-back).
fonttest.cgraphics fonts

Shows the compact 5×5 Lynx graphics font and runtime font switching.
- Selects
GFX_FONT_COMPACT— 6-px pitch, transparent background, foreground drawn in the current pen. - Screen cleared to blue so the glyph transparency is obvious.
- Suzy scales the text sprite natively in 8.8, so the banner is drawn at 1×/2×/3×.
fontvar.cproportional font

Shows the proportional (variable-width) Lynx graphics font and the advance-aware width query.
- Selects
GFX_FONT_VARIABLE— an all-caps pixel font whose glyphs are 1–5 px wide with a 1-px gap, transparent background, foreground in the current pen. The alphabet line makes the proportional spacing obvious: theIis tight, theMandWare wide. - Uses
gfx_gettextwidthto centre the title and to drop a caret flush against a measured string — a visible proof that the proportional width query matches the glyphsgfx_outtextactually draws. - The B button cycles the sample block through all three fonts (proportional / 5×5 / 8×8), and Suzy scales the proportional text in 8.8 so glyphs and spacing grow together at 1×/2×/3×.
textdir.cgraphics text

Shows how gfx_settextdir changes the way the text cursor advances between successive gfx_outtext calls.
- Each individual string is always drawn as a normal left-to-right strip; the direction only controls the post-draw cursor move — glyphs are never rotated.
GFX_TEXT_HORIZONTALadvances the cursor right by the string width, so chained tokens run on as010203;GFX_TEXT_VERTICALadvances it down by one text line (the scaled font height), so the same calls stack top to bottom.- Both panels issue an identical
gotoxy+ three cursorlessgfx_outtextsequence, isolating direction as the only difference.
collision.ccollision buffer

Demonstrates Suzy's hardware collision buffer and the per-sprite collision depository — the only collision facility the Lynx has.
- Four fixed target blocks carry distinct collision numbers 1–4; a white player block sweeps across them. Targets are drawn first so they lay their numbers into the collision buffer, then the player last — as it paints, Suzy reads those numbers back and drops the highest into the player's depository byte.
- The depository lands one byte in front of the SCB (
gfx_initsetsCOLLOFF = −1), so a wrapper struct with a leadingcollbyte reads which target was struck with no per-pixel testing in C; the hit target flashes and aHIT TARGET nread-out shows the value. - The one example in the tree that links with
lynx-coll.cfginstead of the default config, because the collision buffer must be reserved in RAM;gfx_setcollisiondetection(1)turns detection on and makesgfx_clear()wipe both buffers each frame.
palette.cpalette

Loads one palette by both of the arrays the palette generator emits, and proves they are equivalent.
- The generator prints two C arrays for the same sixteen colours: a 32-byte
unsigned chararray forgfx_setpalette(16 green bytes, then 16 blue/red bytes) and a condensed 16-entryunsigned shortarray forgfx_setpalette16(one packed0x0GBRvalue per pen). - The example installs the 32-byte array, snapshots the hardware palette with
gfx_getpalette, installs the 16-entry array, snapshots again, and compares the two:SNAPSHOTS: MATCHconfirmsgfx_setpalette16splits each packed entry into the twoGCOLMAPhalves and lands exactly whatgfx_setpalettedoes. - The sixteen pens are drawn as horizontal bands with
gfx_clearrows; pressing A toggles which loader is live, and the bands do not change because both arrays describe the same colours.
Mikey display
setbpp.c2bpp mode

Demonstrates gfx_setbpp() — the Lynx 2-bit / monochrome display mode.
- Toggles Mikey's display DMA between 4bpp (Suzy-rendered) and a CPU-rendered 2bpp framebuffer (40 bytes/line × 102 lines, 4 pixels/byte).
- Greyscale palette turns 2bpp into a monochrome mode: solid bands, three ordered-dither fields and a CPU-animated bouncing block.
- Page-swap machinery is depth-independent, so the 2bpp screen is double buffered like any other.
Mikey audio
sndtune.csnd engine

Plays a compiled ABC tune through the snd sound engine alongside a direct-register beep.
- The looping melody in
theme_music[]is the event stream theabccctune compiler emits offline fromtheme.abc;theme.sis committed beside the example so it links without the host tool present. snd_init()thensnd_play()starts the tune on channel 0, and the sound-timer interrupt advances the stream on its own whilemain()idles.- A one-shot rising blip on channel 3 uses only the
mikey_snd_*direct helpers —taps,octave,pitchandvolume— showing register-level SFX with no stream.
sfxtest.csnd engine

A player-style sound test for the snd engine's compiled effect streams: pick an effect from a scrolling menu and audition it.
- The effects in
sfx.sare listed in a table-driven menu (sfx_list[]); adding a row to the table adds a menu entry automatically, so the same front-end scales to any number of effects. - The d-pad moves the highlight (the list scrolls when it overflows),
Aplays the selected effect on channel 0, andBstops every channel; the selected row is green and a still-sounding effect turns yellow, driven bysnd_active(). - Each effect is a self-contained event stream handed straight to
snd_play(): the UFO drone loops until stopped, the rest are one-shots that free their channel on their own.
sfxdemo.csfx pack

A sound test for the reusable sfx pack — the batteries-included effect library (<lynx/sfx.h>) that layers over the snd engine.
- Fires every ready-made effect in the pack with the
sfx_<name>(ch)macros — all 56 entries, fromsfx_coinandsfx_laserto looping ambience likesfx_alarm— grouped into the same seven categories as<lynx/sfx.h>, each a pre-built compiled stream inlib/lynx-audio.lib. - Everything plays on channel 3, following the convention that reserves one channel for effects so they duck only themselves, never music on channels 0–2. The looping effects (alarm, ambient hum, engine, heartbeat) run until
Bcallssnd_stop_channel. - Links with no extra source files: effects are still pulled out of the audio library at member granularity, but because this demo references the whole catalogue as a browser, it links in every effect object rather than a subset.
System
poweroff.csoft power-off

Turns the Lynx off in software with poweroff().
- Clears bit 1 of
SYSCTL1(0xFD87), the regulator's soft on/off line, which powers up as1; clearing it disconnects the system from the battery — the same mechanism that auto-powers-off an idle unit. - The call masks interrupts and does not return on real hardware. A real game would save state to the EEPROM first; this demo keeps to the one call so the mechanism is clear.
- A
|/-\spinner turns as a running-activity indicator: while it animates, power is on (SYSCTL1bit 1 is still 1). It stops the instantpoweroff()halts the CPU. - Emulators generally do not model the regulator soft-off, so under emulation the screen simply freezes on the “powering off” frame instead of switching off.
Memory
heaptest.cheap correctness

On-target verification that the heap allocator's 2-byte block header behaves correctly.
- Runs 17 checks across the public API —
malloc,calloc,realloc,free,_heapblocksize,_heapmemavail,_heapadd— covering exact sizing, in-place vs movingrealloc, coalescing and full reclamation. - Cross-checks the library against direct memory inspection: the raw size word stored just below each user pointer, the runtime heap variables (
_heaporg/_heapptr/_heapend) and the free-list head, confirming the raw block is always(user − 2). - Draws a colour-coded grid — each test green (OK) or red (X) — with a
PASS k/17summary and the first failing test; the heap variables are shown live in hex.
zeropage.czero page

Places C globals in the zero page with the __zeropage attribute.
- Three counters are declared
__zeropage(from<zeropage.h>), so the compiler emits them into theZEROPAGEsegment and addresses them with the fast 2-byte zero-page opcodes —inc _frameassembles toE6, not the 3-byte absoluteEE. - No companion assembler file and no
#pragma zpsym: a single C declaration both defines the storage and marks the symbol. - The Lynx graphics text harness shows the live counters; A and B bump the zero-page
pressescounter up and down.
Network
comlynx.cserial + joypad

A ComLynx serial loopback self-test that needs no cable.
- The ComLynx wire is open-collector with Tx and Rx tied together, so every transmitted byte is also received — a full send/receive/close test runs against itself.
- Sends a known pattern at the Lynx-native 62500 baud, expects every byte back, then confirms reception stops once the port is closed.
- Also demonstrates the static joy API: all nine inputs from one
joy_read()call, with the one-line edge-detection idiom.
Storage
sdcardls.cSD/GD flash cart

Lists the root directory of a RetroHQ Lynx SD / GD flash cartridge using the sdcard_gd_* API.
- Wakes the cart MCU with
sdcard_gd_init(), opens the card root withsdcard_gd_opendir("/")and walks it withsdcard_gd_readdir(), printing each 8.3 name and marking sub-directories in green. - The opt-in
lib/lynx-sdcard-gd.libis auto-linked bycl65(no-lflag) via the SDK manifest, exactly like the audio and compress libraries. - Only does anything on real hardware with an SD card inserted: in the emulator there is no cart-MCU to answer the FIFO handshake, so the capture shows just the title while the directory call waits. See SD / GD flash cart for the protocol and the on-card layout.
Multicart
multicartmenu loader

A single .lnx that bundles a menu and three independent game ROMs; picking one loads it over the top of the menu and runs it.
- The menu and each game are separate, self-contained programs built as BLL objects (
cl65 -C lynx-bll.cfg);lnx multicartwrites a lynxdir layout andlynxdirstitches them into one bootable cart. multicart_run(n)hands off from the menu to game n: it stops the frame timers, blanks the palette, copies a small relocatable loader to$0040and jumps to it; the loader pulls that game off the cartridge by its directory number and starts it.- Launching a game overwrites the menu, so there is no way back without a reboot — one game per power-on, as the LynxJam multicart worked on hardware.