Now that we’ve taken a look astatine the benignant of power that the Spectrum’s BASIC gives us complete the hardware, it’s clip to dip down into instrumentality connection and spot what is offered to america there. There’s rather a spot much to screen successful this realm, and I expect it’s going to extremity up dispersed retired complete rather a fewer posts.
It is besides rather a spot much fraught than connected galore different platforms, because Sinclair only paid minimal attraction to exposing a accordant and system firmware interface. Commodore’s 8-bits, from the original PET done to the C128, each had backwards-compatible jump tables astatine the extremity of their “KERNAL” ROMs which meant that rather a batch of instrumentality connection codification could usability identically moreover erstwhile doing things for illustration record processing and disk access. MSX was not a azygous machine astatine all, but an manufacture modular that manufacturers wrote to, and a awesome portion of that was a well-defined jump array up adjacent the interrupt vectors. The IBM PC’s BIOS served a akin role, though little voluntarily.
The Spectrum, however, has only a fistful of defined introduction points and arsenic a consequence developers tended to straight telephone heavy wrong the strategy ROM itself successful bid to get the results they wanted. The Timex Sinclair 2068 had an incompatible ROM and arsenic a consequence almost nary Spectrum package ran connected it—it seems for illustration this was understood to person been a awesome contributor to its nonaccomplishment successful the US Market. I’m a spot skeptical of this, because that meteoric US clang was shared by the MSX, the Commodore 16, and the Coleco Adam, each of which were plausible nonstop competitors to the TS2068. However, fixed that the 128 was released aft the 2068’s failure, and that the 128 kept the applicable parts of its ROM very cautiously compatible pinch the 48K version, I fishy that Sinclair nevertheless learned an important instruction here.
For the purposes of this bid I will beryllium taking the 48K Spectrum arsenic the target platform, but besides making judge that the techniques I picture besides activity connected the 16K and 128K machines. There were a vast number of Spectrum clones and successors, of varying fidelity; if I brushwood thing absorbing regarding them on the measurement I’ll bring it up, but it will each beryllium purely sidebar territory.
For our first foray, I’m going to look astatine the accommodation we person to bid to get a show for illustration the 100%-BASIC “Manic Mechanic” crippled I showed disconnected past week:

In this first post, we’ll commencement by looking astatine basal strategy organization: really instrumentality connection programs beryllium connected the system, really they are loaded and run, and really they coexist pinch BASIC and the BIOS. Then we’ll excavation into the accommodation for text-based displays connected the system, including the “user-defined graphics” installation that Manic Mechanic itself relies on. We’ll wrap up by looking astatine keyboard and joystick input, which turns retired to beryllium rather adjacent to what we had to do successful BASIC.
First Principles: Running Code astatine All
When I first started exploring the ZX Spectrum, I was very pleasantly amazed astatine really easy the BASIC could coexist pinch instrumentality code. Many of the modular BASIC commands person other modes that lend themselves very good not only to axenic instrumentality codification programs but to mixed BASIC/ML combinations.
- Files connected cassette place themselves arsenic BASIC code, BASIC data, aliases binary data. BASIC’s SAVE and LOAD commands person extensions to specify what precisely is to beryllium loaded, akin to the chopped LOAD and BLOAD commands successful different BASICs. To load instrumentality codification from tape, we put the keyword CODE aft the filename.
- BASIC tin restrict its representation usage by passing a parameter to the CLEAR command. By lowering the apical of BASIC’s representation to conscionable beneath your instrumentality code’s loading point, representation conflicts should beryllium wholly avoidable.
- BASIC calls into instrumentality codification subroutines pinch the USR function. This takes the reside of the regular arsenic its argument; the regular does its work, past returns to BASIC pinch a RET instruction. The worth of the BC registry brace is returned to BASIC arsenic the worth of the usability arsenic a 16-bit unsigned integer. Routines pinch nary meaningful return worth mostly dispose of it by passing it to the random number generator: RANDOMIZE USR successful Sinclair BASIC accomplishes overmuch the aforesaid point arsenic SYS successful C64 BASIC.
In summation to redeeming retired ranges of binary data, the SAVE usability tin besides prevention a BASIC programme specified that it starts moving instantly aft LOADing—and it allows you commencement execution from immoderate statement number you wish. Back successful 2017 I created a somewhat much blase BASIC stub for my Spectrum programs that I’ve been utilizing ever since. The wide strategy was this:
- The BASIC programme is saved truthful that it originates execution connected statement 30 alternatively of 10.
- Code astatine statement 30 restricts BASIC’s representation pinch a CLEAR bid and past loads the adjacent record connected the portion (our existent program) arsenic binary. Once the load finishes it past jumps up to the apical of the program.
- Lines 10 and 20 telephone the loaded instrumentality codification pinch RANDOMIZE USR and past jump past the loader logic to origin the programme to exit normally.
The extremity consequence of each of this a programme that runs its instrumentality codification constituent erstwhile run, but which also, erstwhile loaded, carries retired each basal preparations precisely once. Turning this into thing I could usage arsenic a turnkey packaging book is simply a spot retired of scope for this tour, truthful I’ll conscionable nexus to the original article astir it and a transcript of the book itself, if you want it.
Machine Code’s View of the Spectrum
The Z80 has a 64KB reside abstraction and connected a 48K Spectrum each of it is used.
- $0000–$3FFF is the strategy ROM.
- $4000–$5AFF is the graphics RAM, for some the bitmap information and the colour table.
- Everything other is RAM for usage by the system.
This is fundamentally what it looks for illustration connected 16K and 128K Spectrums arsenic well, though RAM connected the 16K ends astatine $7FFF and some the ROM and RAM connected the 128 are bankswitched.
When penning our assembly connection code, we can’t usage accommodation that are owned by the strategy ROMs. That includes everything to do pinch interrupts, the protector registers, and the IY register.
The IY registry is typical though, because while we are not allowed to edit it, we tin and regularly will read it (it’s ever $5C3A) and besides index from it: it holds the guidelines reside of what Sinclair calls the system variables, a postulation of information astir the existent strategy authorities that we will regularly find ourselves reference and writing. The locations of these variables are acold much accordant crossed incompatible variants than the ROM; I leaned connected this rather heavy erstwhile I made my first project.
The ROM itself turns retired to beryllium beautiful casual astir this, often referring to strategy variables straight by address, but past besides indexing IY to entree them arsenic needed. Indexed operations are much costly but much flexible, truthful a usage lawsuit for illustration this 1 wherever you cognize precisely what your guidelines reside is but besides person an scale registry will origin you to switch backmost and distant betwixt utilizing absolute addresses and utilizing indexed access. I’ll beryllium penning my codification present specified that each strategy adaptable entree goes done IY but this wasn’t mostly done. (Indeed, I myself do not do it successful the Spectrum level guide.)
Printing Out Text
As we saw successful our BASIC tour, the Spectrum divides the surface into a 22-line precocious model for its main show and a 2-line little model for input and position messages. This is not an artifact of BASIC; this section is coming astatine the machine-code level arsenic well. In bid to people retired matter to the precocious window, we request to configure the strategy variables appropriately to show its output routines to nonstop matter output there; we tin do this by penning a 0 to TVFLAG astatine IY+2. Once this has been done, we whitethorn telephone the ROM regular astatine reside $10 to people the characteristic successful A. Spectrum uses ASCII truthful normal matter will beryllium rather acquainted to us.
That makes Hello World beautiful straightforward:
org $7000 ld (iy+2),0 ; Write to precocious screen ld hl,msg lp: ld a,(hl) inc hl aliases a ret z rst $10 jr lp msg: db "Hello, world!",13,0I usually usage $7000 arsenic my root reside because it’s heavy capable into RAM to time off BASIC immoderate breathing room while still having capable abstraction near to astir apt fto my smaller projects still fresh connected a 16K machine. I combine this pinch a bid for illustration sjasm hello.asm hello.bin and package it pinch spectralink.py hello.bin 7000, past load up hello.bin.tzx into FUSE and…

We are disconnected the ground!
Defining and Using Graphical Characters
When moving pinch BASIC, we recovered that we had 2 kinds of graphical characters: built-in semigraphics and past a suite of reprogrammable characters it called “user-defined graphics.” We’d type them successful by shifting into “graphics input mode” and past pressing keys 1-8 for the semigraphics (using inverse-video mode arsenic basal to get each 16 imaginable combinations) and A-U for the user-defined characters.
This is simply a spot wherever things are somewhat easier successful instrumentality connection than BASIC. “Graphics Mode” is simply a quirk of the input system, and freed of the necessity of straight typing successful the characters we want we tin simply walk extended characters connected to the character-printing regular astatine RST $10.
When utilizing the predefined semigraphics, we get different bully bonus: the full messiness pinch inverse video was an awkward workaround we faced owed to not having capable keys connected our keyboard. Under the hood, we person each 16 imaginable semigraphics characters instantly disposable successful the scope $80–$8F. They are besides laid retired successful a sensible order: bits 1, 2, 4, and 8 correspond to the upper-right, upper-left, lower-right, and lower-left quadrants of the character, respectively.
The user-defined graphics are similar; these inhabit the scope $90–$A4 and tally from graphic-A done graphic-U. (The 128, pinch 2 less characters available, only offers up done $A2.) The remainder of the characteristic group done $FF is the abbreviated forms of BASIC keywords. (That’s why we suffer a mates spots connected the 128, incidentally; that’s wherever the SPECTRUM and PLAY commands show up.)
The precise location of the user-defined graphics varies from strategy to system, but there’s a 16-bit pointer to them named UDG astatine IY+65. This is precisely the worth that is returned by the BASIC usability USR "A", and since BASIC itself was past treating that arsenic a buffer to POKE we get to do the aforesaid ourselves successful instrumentality code. Here’s a very elemental loader routine, assuming location are num_chars worthy of characteristic information astatine gfx:
These really activity successful BASIC, too; we tin PRINT retired each the graphics characters pinch CHR$ without having to dip into graphics aliases inverse mode.
Making Our Text Fancier
A batch of our clip past week was dedicated to 7 commands that we could connection connected our ain aliases moreover weave into PRINT and DRAW commands to power location, color, and behaviour for illustration blinking text. The character-printing regular handles most of this for america automatically, but the protocols are a spot different than successful BASIC.
The basal penetration is that we tin recreate the inline changes to matter attributes by printing retired typical power codes. Character codes $10 done $17 replicate the matter power commands that we saw past week, representing, successful order: INK, PAPER, FLASH, BRIGHT, INVERSE, OVER, AT, and TAB. (Well, OK. We didn’t spell complete TAB past week because it’s modular BASIC and isn’t really a Spectrum thing, but it turns retired it’s implemented this measurement too.) All of these return a azygous byte afterwards arsenic argument, isolated from for AT, which takes two. These each activity precisely the measurement they do successful BASIC, including the typical transparent/high opposition modes for colors 8 and 9 successful PAPER and INK, and the AT arguments being successful row, file bid pinch (0,0) successful the precocious near corner.
What does not activity precisely the measurement we saw it successful BASIC is that they do not reset erstwhile our PRINT connection finishes. Not moreover printing a newline (which is simply a bare carriage return, $0D, connected this system) restores the first state. The strategy does person a favoritism of sorts betwixt “permanent” and “temporary” characteristic attributes, but it’s overmuch much tightly bound up pinch the internals of the ROM itself. To make due usage of those, we request to commencement looking much intimately astatine things that Sinclair did not, astatine first, really expect america to beryllium looking at.
Working More Closely With the System ROM
There are six bytes successful the strategy variables that interact pinch matter display:
- ATTR-T astatine IY+85: the “temporary” matter attributes. When we people retired a characteristic pinch the RST $10 instruction, the byte successful this adaptable is copied into the corresponding compartment successful colour representation to group its colors, its brightness, and its blinkiness.
- MASK-T astatine IY+86: the “temporary” property mask. As it happens, the byte successful ATTR-T isn’t copied exactly. Any spot group successful this byte won’t beryllium changed arsenic portion of the copy. This is really PAPER 8 and INK 8 work; they disguise retired the applicable parts of this adaptable and the printing regular leaves those parts of the colour compartment alone.
- ATTR-P and MASK-P astatine IY+83 and IY+84: the “permanent” matter attributes and mask. These get updated erstwhile commands for illustration INK and PAPER are utilized arsenic bare commands successful BASIC, and the first point a PRINT connection does is transcript them complete into the impermanent slots. This is what makes the impermanent colour changes temporary. Screen-clearing instructions besides consult ATTR-P to determine what colour to clear the surface to.
- P-FLAGS astatine IY+87: non-color matter controls. The OVER and INVERSE modifiers aren’t portion of the matter attributes, and the logic required by the typical INK 9 and PAPER 9 modes isn’t straight captured by either ATTR aliases MASK. Those values are stored arsenic azygous bits here, pinch the impermanent values stored successful the even-numbered bits and the imperishable ones successful the odd-numbered bits. This interleaving allows the strategy ROM to transcript imperishable to impermanent colors pinch immoderate compact bit-manipulation operations.
- BORDERCR astatine IY+14: the separator color. Writing this doesn’t actually set the separator color—that is controlled by penning the little 3 bits of I/O larboard $FE—but the strategy ROM consults it erstwhile resetting the separator itself and also, much importantly, erstwhile it is mounting up the colour attributes successful the little input window. The worth successful this byte is stored successful bits 3-5; multiply your colour worth by 8 earlier storing it here.
Again, nary of this was portion of immoderate general BIOS interface aliases anything; usage of the strategy ROM accommodation benignant of presumes that you person an annotated ROM disassembly to hand. Fortunately, we do: we’re utilizing the hyperlinked type connected skoolkid’s site. That lets america get our bearings a bit.
Nothing we entree done the character-printing codification ever touches the imperishable data. However, location is an soul ROM regular that the published disassembly calls TEMPS astatine $0D4D that copies each imperishable values into the impermanent spaces, carrying retired the property reset. This usability takes nary arguments and trashes A and HL, but different tin beryllium called whenever you want.
The imperishable attributes are chiefly utilized by the screen-clearing usability CLS, a ROM regular astatine $0D6B. These are what are utilized to capable the precocious window’s property cells, pinch the little model taking its values from BORDERCR and immoderate logic that fundamentally replicates what INK 9 does. It besides resets the impermanent colors to beryllium the imperishable ones. Annoyingly, contempt checking BORDERCR here, it doesn’t really group the border. Even much annoyingly, it resets our output location into the little window.
We tin woody pinch each this by relying connected a helper usability of our ain and relying connected that. This clrto usability takes an property byte successful A and clears the full surface to that color; precocious window, little window, and border. It besides clears retired immoderate non-color modes that mightiness beryllium on, and restores the output to the precocious model connected the measurement out. We tin do that pinch TVFLAG, but arsenic agelong arsenic we’re straight invoking strategy ROM routines, we whitethorn arsenic good do it “right” and really unfastened the precocious window’s output channel. The CHAN-OPEN regular astatine $1601 selects an output instrumentality to nonstop characters to, and instrumentality 2 is the precocious window. The complete clrto usability runs for illustration so:
There’s 1 past quirk successful the Spectrum’s matter systems that we haven’t tally into yet. If you people retired capable matter that the surface would extremity up scrolling, by default it won’t really scroll down. Instead it will region the output and hold for the personification to corroborate that they really want the surface to scroll, aliases if they for illustration to extremity the program. The strategy adaptable SCR-CT astatine IY+82 measures really galore lines to people earlier prompting again; by regularly resetting it to immoderate ample affirmative number you tin guarantee a continuous scroll if that is what you want.
Reading Keypresses and Doing I/O
BASIC gave america 2 options for reference input: the INKEY$ usability that checked to spot if location was a keypress waiting to beryllium processed, and past nonstop speech pinch keyboards and joysticks utilizing the IN function. Both person their parallels astatine the instrumentality codification level.
An interrupt fires each frame, which the firmware intercepts. Its interrupt handler updates a timer (FRAMES, a 3-byte worth astatine IY+64) and scans the keyboard ports. If a keypress is found, it decodes it into a character, places that characteristic successful LAST-K astatine IY-50, and past sets spot 5 of FLAGS astatine IY+1. Here is simply a elemental regular that waits for a cardinal to beryllium pressed and past returns its worth successful A:
We put a HALT successful our loop present because only the interrupt handler really updates these flags; there’s nary request to spinlock connected them erstwhile we tin simply hold for the adjacent scan.
Direct input is moreover easier, because arsenic assembly connection programmers we get nonstop entree to the I/O autobus pinch IN and OUT. However, location is 1 small quirk: dissimilar BASIC, our instruction group suggests that we only person 8 bits of I/O address, not 16. This turns retired to beryllium a creation oversight by Zilog that turned into a characteristic that Sinclair relied on: the instructions IN A,(C) and OUT (C),A put the entire BC register connected the reside bus, not conscionable C. To cheque if the A cardinal is pressed, we tin constitute thing for illustration this:
ld bc,$fdfe ; IN 65022 successful BASIC successful a,(c) rra jr nc,pressedAThe Kempston joystick only uses an 8-bit larboard address, truthful that codification ends up moreover much straightforward. Here’s a complete scholar regular that returns delta-x successful L, delta-y successful H, and the occurrence fastener successful C:
For afloat archiving connected which ports correspond to which keys, and the various joystick layouts, Martin Korth’s ZX Docs person galore bully tables. Joystick operations are fundamentally identical to BASIC, truthful my various caveats from past week still apply, but pinch somewhat little force. Emulators are still a small inconsistent astir synthetic SHIFT keys, but we nary longer person to interest astir an accidental L BREAK INTO PROGRAM correction erstwhile we move and sprout astatine the aforesaid time.
Putting It All Together
To wrap up each the things we’ve learned here, let’s knit them together into a programme that produces the aforesaid banner show that we sewage retired of BASIC past time:

The main programme fundamentally conscionable calls each point we’ve done present successful turn, isolated from for nonstop keyboard aliases joystick reads:
org $7000 ld a,$20 ; Clear to achromatic connected green telephone clrto ld hl,gfx ; Load our 4 civilization characters into $90-$93 ld e,(iy+65) ; UDG ld d,(iy+66) ld bc,32 ldir ld hl,msg ; Print the display telephone print telephone getkey ; Wait for keypress ld a,$38 ; Clear backmost to achromatic connected white jp clrto ; and exit erstwhile we're doneThe clrto and getkey functions are precisely arsenic we listed them above. Our print function, however, needs to alteration a spot from the Hello World program. We were utilizing a 0 byte arsenic the drawstring terminator up there, and that’s nary longer a reasonable point to do; we group some PAPER and BRIGHT to zero astatine various points successful our show present and we request to do that by really printing retired existent CHR$ 0 characters. The solution isn’t difficult; we request simply switch our OR A instruction that implicitly compared A to zero pinch a CP $FF usability that explicitly compares it pinch 255. That’s a safer codification to usage arsenic a sentinel; it corresponds to the BASIC keyword COPY which we will ne'er really beryllium printing out.
Then there’s the information itself: the connection to people retired and the graphics definitions for the umbrella. The connection information makes dense usage of the matter power codes above, and is broadly unreadable arsenic a result. The graphics information is precisely the aforesaid arsenic the DATA statements from the BASIC original, conscionable backmost successful hex this clip the measurement they were successful the TI BASIC original:
This turns retired to beryllium a importantly smaller programme than our BASIC original; moreover taking into relationship the BASIC stub and the other portion header, this programme is simply a spot nether half the size.
Does Benny Get the Last Laugh?
The worldly we’ve covered coming is capable that we could ideate a axenic instrumentality codification type of the Manic Mechanic type-in crippled I utilized arsenic an illustration past week. We’ve now seen capable to recreate the main crippled show and besides negociate input and animation. We’re still missing sound, though, and we can’t lucifer the title surface yet:

Line graphics for illustration what the DRAW bid makes are inconvenient successful instrumentality language, but we’ve sewage immoderate tricks up our sleeves yet that BASIC can’t lucifer astatine all. Stay tuned.
English (US) ·
Indonesian (ID) ·