# Skill: BASIC V2 Bridge — SYS, USR, PEEK, POKE, and BASIC Internals ## Use this skill when The task involves BASIC V2, calling assembly from BASIC, calling BASIC ROM routines from assembly, `SYS`, `USR`, `PEEK`, `POKE`, `WAIT`, tokenization, variable storage, or BASIC program layout. ## Core concepts - BASIC V2 is interpreted. Each statement is parsed and executed at runtime, which is why BASIC is slower than ML. - BASIC program lines are tokenized and linked in memory. - BASIC and ML can cooperate if memory ownership is clear. - `SYS` calls an ML routine as a command. - `USR(x)` calls an ML routine as a function-like expression. - `PEEK` reads one byte; `POKE` writes one byte. ## Calling ML with SYS BASIC: ```basic 10 SYS 49152 ``` Assembly routine at `$C000` must normally end with: ```asm rts ``` ### Passing registers through SYS Before `SYS`, BASIC can place values in these locations: | Decimal | Hex | Register | |---:|---:|---| | 780 | `$030C` | Accumulator A | | 781 | `$030D` | X register | | 782 | `$030E` | Y register | | 783 | `$030F` | Processor status | Example: ```basic 10 POKE 780,65:REM A = PETSCII "A" 20 SYS 49152 30 PRINT PEEK(780) ``` ## Calling ML with USR `USR(x)` is best when an ML routine should behave like a function. Use cases: - Fast math helper. - Custom string/numeric function. - BASIC extension experiments. Cautions: - `USR` uses BASIC floating-point accumulator conventions. - It is more complex than `SYS`; use `SYS` first unless function syntax is needed. ## BASIC pointers worth knowing | Decimal | Hex | Meaning | |---:|---:|---| | 43-44 | `$002B-$002C` | Start of BASIC text | | 45-46 | `$002D-$002E` | End of BASIC text | | 47-48 | `$002F-$0030` | Start of variables | | 49-50 | `$0031-$0032` | Start of arrays | | 51-52 | `$0033-$0034` | End of arrays/start of strings | | 55-56 | `$0037-$0038` | Top of BASIC memory | ## BASIC patterns ### Change border and background ```basic 10 POKE 53280,6:REM BORDER $D020 20 POKE 53281,0:REM BACKGROUND $D021 ``` ### Write to screen and color RAM ```basic 10 POKE 1024,1:REM SCREEN CODE A 20 POKE 55296,2:REM COLOR RED IN LOW NYBBLE ``` ### Protect ML at $C000 with simple convention For many C64 BASIC programs, `$C000` is outside normal BASIC RAM. Still, document the assumption and avoid loaders that extend into `$C000`. ## Agent checklist When producing BASIC+ML examples: 1. Give a BASIC loader if the user needs type-in code. 2. Give the assembly source separately when possible. 3. Include exact `SYS` address. 4. Ensure ML routine ends in `RTS`. 5. Explain which locations are POKEd and why.