Showing posts with label Z80. Show all posts
Showing posts with label Z80. Show all posts

Sunday, 28 September 2025

Revisiting the Minstrel 4th Enhanced Forth ROM

When I relaunched the Minstrel 4th earlier this year, I added some more ROMs to the standard ROM image. These included the ZX80 and ZX81 BASIC I have talked much about, and the Enhanced Forth ROM which I have not.

This is the work of Alexander Sharikhin, and features additional code by George Beckett (and I think the clock check and BEEP patch might have been by me? or maybe just "Based on an original idea by Tony Warren Dave Curran")

This takes advantage of the extra 5K of ROM space I gave the Minstrel 4th, and adds various new functionality to the Forth ROM, including:

  • Serial communications using the 68B50 RC2014 module
  • LOAD and SAVE via serial using server program at PC end
  • LOAD and SAVE blocks of memory using XMODEM
  • Serial => Keyboard input and Screen => Serial
  • Programming tools to support hex characters and code blocks
  • CASE statements
  • BEEP patched to adjust frequency when run at 6.5MHz

When I came to add that, even though the latest source was 5 years old, I appeared to have an older version, so I though it best to get the latest version and tried to build it.

That didn't go well. It needed the sjasmplus compiler with LUA support, and I couldn't get that working. Not sure what I was doing wrong. I guess something in current version of LUA or sjasmplus has changed to make it incompatible with the other.

At the time, I took the easy option of asking George to build it for me, and that was the version that went into the ROM.

I have been planning to revisit that for a while, I wanted to achieve a few things:

  • Be able to built it (quite important)
  • Add new functionality
  • Integrate the ACE ROM source
  • Rename some words

The current version is a patch. It takes the compiled Jupiter ACE ROM binary and patches a few things in there to graft in the new commands, which are compiled and added onto the end. 

It also patches the names of LOAD, SAVE, BLOAD and BSAVE to change those to LOAT, SAVT, BLOAT and BSAVT to allow the new routines to use the standard names (the change of letter so not to change the code size, hence why it wasn't changed to TLOAD for example)

I can see why that has been done, but I think I would prefer to leave the standard tape load as LOAD and make the serial load SLOAD (or ULOAD to match things like UINIT which initialises the UART).

That way, I think I would push this as the main ROM, with the option of going to the original unmodified version if you want. A normal user could just run LOAD as normal for a tape load without being aware of the new functionality.

It would be ideal if I could have all the source together in a single place and do one build command to build the whole ROM from source. That is non-trivial, since the ACE source I have is based on Geoff Wearmouth's commented disassembly, and that is written to use the TASM assembler.

That's fine by me as I have been using TASM to write Z80 code since I got a copy on 5¼" floppy from a teacher at school. All of the ZX80 and ZX81 BASIC etc. is written in TASM so it seemed the best bet to stick with that.

All I had to do was manually apply the patches to the Ace source and merge the source together.

Easy.

End of post, take the rest of the day off.

Ah, no. Not quite.

It turns out there are quite a few differences between TASM Z80 and sjasmplus. Many of them were just search and replace, but some required a bit more thought.

Here are some examples I found.

Numbers

The numbers were in several formats, 0x1234 and also #1234 (which I found rather annoyingly Visual Studio Code displayed with a box to the left showing what #1234 would look like if it were an HTML colour).

I am sure there is a way to turn that off, but I need to change them anyway since TASM used $1234 for hexadecimal numbers (and also 1234H, but I rarely use that notation).

RECV_RETRY: equ 0x1000  🠆  RECV_RETRY .EQU $1000

TMP_DICT = #2709  🠆  TMP_DICT .EQU $2709

That was mostly search and replace, but as with all of these changes, a good opportunity to read through the code and find out what it all did (and for me to unnecessarily align all the comments because that's the way I roll).

Local Labels

Local labels save you having to think of a new name for the point you jump back to in a loop every time.

You can't call them all "loop", so you can use a local label that's just called "loop" within this scope of your function. sjasmplus uses ".loop" for this, but TASM uses "_loop" (you can change that, but I'd rather stick with the standard). That's not too bad, just search and replace again.

But the scope is also different. In sjasmplus this seems to be relative to the last proper label only.

main:

    ld b, 42

.loop

    djnz .loop

That .loop is treated as main.loop, which makes sense and is a neat way to do it.

I use ACME for 6502 code, and that also has + and -, so you can do

main:

    lda, 42

-   dec

    bne -

Where - just refers to the previous - label, and + to the next + label (you can do -- and ++ as well for the one before / after that, but it starts to get a bit complicated and is usually better to give things names unless it's obvious)

TASM doesn't have either of those, it needed .MODULE definitions adding where necessary to control the scope.

main:

          .MODULE MAIN       

    ld b, 42

_loop

    djnz _loop

So that is now MAIN._loop.

Instruction differences

There were a few instructions that had to be changed.

ex hl, de

That was used in a couple of places. This isn't an "official" Z80 opcode, but the assembler just accepted it and converted it to the more correct

ex de, hl

TASM didn't, so I had to do that manually.

I wanted to check that to be sure, so I disassembled the Enhanced part of the ROM.

z80dasm -a -g 0x2800 -l -t 2800.bin

That gave me a listing of the code so I could check what had actually been built.

ex de,hl

Yes, the compiler had just replaced the instruction.

The next one confused me, as far as I know, there isn't an ld (hl), de instruction.

.save:

ld (hl), de

ret

Checking the disassembly, it turns out the code actually generated was:

ld (hl),e

inc hl

ld (hl),d

dec hl

ret

Interesting, not sure why you would use an instruction that doesn't exist, particularly if for example, you didn't need the value in hl, so the last dec hl would be unnecessary.

_save:

   ld (hl),e                ;ld (hl), de

inc hl                     ;

ld (hl),d                  ;

dec hl                     ;

ret

I left the original instruction in the comment for reference.

This one also confused me.

dup 4

call loadVar

jr c, _error

edup

I was thinking this was some kind of forth thing, since dup is a forth word to duplicate the item at the top of the stack

But no, it must be a compiler thing. Looking at the disassembly it appears to mean "duplicate this 4 times......end duplicate"

   call sub_2ac6h

jr c,l2ce0h

call sub_2ac6h

jr c,l2ce0h

call sub_2ac6h

jr c,l2ce0h

call sub_2ac6h

jr c,l2ce0h

I just replace that with the unrolled code, again with a comment

RST calls

There were two variations of RST calls, using 0xnn and #nn (both seen in this function)

.cont:

rst 0x08 ; Print character

pop bc

djnz .loop

ld a, CR

rst #08

ld a, e ; Retrieve block type

and a ; Indicate success

ret

Unfortunately it turns out TASM doesn't accept either of those. Furthermore, it doesn't accept what I would have expected

    rst $08

You have to do

    rst 08H

More search and replace and we are getting closer.

Just a side note, got to love Z80 syntax

    cpl  ; Compute 255-A, ones ComPLiment

    cp l ; Compare A to the L register

And

    rra  ; Rotate accumulator right through carry (4 cycles)

    rr a ; Rotate accumulator right through carry (8 cycles)

Oh, for a RISC processor ......

Forth Words

The elephant in the room.

The is probably described better somewhere else, by someone who understands it better that I do, but here goes.

The forth dictionary is a singly linked list. There are two bytes at the end of the original ROM at $1FFD. This points to the first word in the dictionary (after FORTH).

On the original ROM that is UFLOAT, but if you wanted to add a new word into the ROM, you would change the value at $1FFD to point to your new word, and you would set your word to point back to UFLOAT, inserting it into the chain.

(what, you didn't expect me to include a vlist print out? at least I might have surprised you by not using the inverse colour scheme I normally do)

There are lots of forth words added in the enhanced ROM, all of which are linked between FORTH and UFLOAT.

(paused part way through as they normally scroll off the top of the screen - do we need a new vlist word with a ZX Spectrum style SCROLL? function????)

(a benefit of the work I previously did getting the extra 5K supported in EightyOne means I can now run and debug the enhanced ROMs. Not perfect as the save detection has to be disabled to avoid false triggering with the ZX ROMs)

In the original ROM, forth words are defined as follows:

; ---------------

; THE 'BASE' WORD

; ---------------

; ( -- 15423)

; A one-byte variable containing the system number base.

; $3C3F BASE

L0483:  DEFM    "BAS"                   ; 'name field'

        DEFB    'E' + $80

        DEFW    L047F                   ; 'link field'

L0489:  DEFB    $04                     ; 'name length field'

L048A:  DEFW    L044D                   ; 'code field'

The actual code follows elsewhere, pointed to by the code field.

The name is "BASE", the last letter of which has $80 added to it to indicate the end of the string.

There is also a length field, which in some cases has $40 added to indicate an immediate word (for things like DO WHILE, IF THEN ELSE etc.)

The links are all hard coded, from word to word, in the order they appear in the file (not sure if that is true for all of them, but it seems to be the general case).

This was one of the nice features that the enhanced ROM needed sjasmplus assembler with LUA for.

w_uinit:

FORTH_WORD "UINIT"

call uart_init

jp (iy)

.word_end:

FORTH_WORD is a macro which expands out to the type of header above, creating the name, link and length fields automatically.

I couldn't use that, so I had to do it manually, in the same way as the original ROM (or at least the disassembly - maybe they had some equivalent function in whatever assembler was used for the Ace ROM).

w_uinit:

;FORTH_WORD "UINIT"

    .MODULE UINIT

    .BYTE "UINI"            ; 'name field'

    .BYTE 'T'+$80           ;

    .WORD w_uread_link      ; 'link field'

w_uinit_link:    

    .BYTE $05               ; 'name length field'

    .WORD w_uinit_code      ; 'code field'

w_uinit_code:    

call uart_init

jp (iy)

I initially hard coded all the links, setting the link address to the label for the previous word (in this case UREAD), and then setting a new link label for the next word to use.

Right, almost there.

CASE

The last thing to tackle was the code for the case statement construct. This was in a different format to the standard assembly code words. This one used FORTH words (or bits of them), in the same way as a few original words, such as ROT. This rotates the top three bytes of the stack:

; --------------

; THE 'ROT' WORD

; --------------

; (n1, n2, n3 -- n2, n3, n1)


L08F9:  DEFM    "RO"                    ; 'name field'

        DEFB    'T' + $80

        DEFW    L08ED                   ; 'link field'

L08FE:  DEFB    $03                     ; 'name length field'

L08FF:  DEFW    L0EC3                   ; 'code field' - docolon

; ---

L0901:  DEFW    L08D2                   ; >R

L0903:  DEFW    L0885                   ; swap

L0905:  DEFW    L08DF                   ; R>

L0907:  DEFW    L0885                   ; swap

L0909:  DEFW    L04B6                   ; exit

It does that using five forth words, rather than any assembly language.

It appears CASE and related words are the same, but the version in the source is just a list of bytes.

;; CASE

ABYTEC 0 "CASE"

dw LINK

SET_VAR LINK, $

db 0x44

db 0x08, 0x11

dw $ + 0x0f ; 0x93, 0x3C

db 0x11, 0x10, 0x00, 0x00, 0x11, 0x10, 0x09, 0x00

db 0x40, 0x11, 0x00, 0xE7, 0xFF

db 0x42, 0x11, 0x79, 0x08, 0xB6, 0x04

To get building, I just pasted in the bytes from the disassembly (code and header).

;; CASE

.BYTE $4F, $C6, $69, $29

.BYTE $42, $08, $11, $A1, $29, $11, $10, $09, $00

.BYTE $46, $29, $60, $04, $11, $10, $00, $00, $4E

.BYTE $0F, $11, $10, $07, $00, $40, $11, $02, $DF

.BYTE $FF, $42, $11, $D2, $08, $12, $09, $4A, $0C

.BYTE $DF, $08, $85, $08, $83, $12, $09, $00, $79

.BYTE $08, $79, $08, $71, $12, $0B, $00, $B3, $08

.BYTE $DF, $08, $D2, $0D, $D2, $08, $A4, $12, $B6

.BYTE $04

OK I think it's there, so time to build it.

wine TASM.EXE -80 -b -L minstrel4th.asm minstrel4th.rom

I am on linux, but still using the old DOS command line TASM, via wine.

I had a few typos to fix here and there, but finally got it built.

I use HxD hex editor (again because I have been using that since the year dot), and that brought up a few differences, usually cut and paste errors with links in the word definitions.

A few more tweaks and I finally got it to build binary identical.

Great.

End of post, take the rest of the day off.

Ah, no. Not quite.

The challenge now was to fix the links, and do something with the case code.

Automatic linked list

The FORTH_WORD macro used a variable called LINK, which was initialised to the address of UFLOAT (first word after FORTH in the original ROM). This was then updated each time to the current link.

Once I worked out the syntax for TASM, I was able to use the same sort of thing, so I went through and replaced all the hard coded links with this new automated link code. E.g.

w_hex:

    .TEXT "HE"              ; 'name field'

    .BYTE 'X'+$80           ;

    .WORD LINK            ; 'link field'

LINK .SET $ ;   

    .BYTE $03               ; 'name length field'

    .WORD w_hex_code        ; 'code field'

w_hex_code: 

ld (IX + $3F), $10

jp (iy)

That was neater and will also allow me to change things more easily.

I rebuilt it and it was still binary identical. Great.

Making the case

I now had various different sources for case the version in the enhanced ROM with a header and just bytes. The version from the disassembly that was just bytes.

I now had found a third, from Geroge's github

https://github.com/markgbeckett/jupiter_ace/tree/master/case

This was in the form of the forth words.

0 COMPILER CASE

  0 ( MARKER ON STACK, USED BY ENDCASE TO CHECK DONE )

  9 ( SYNTAX GUIDE, MUST MATCH WITH 'OF' )

RUNS>

  DROP ( NOTHING TO DO EXCEPT DROP ADDR OF PARAMETER FIELD )

;

With a bit of searching through the various versions, I was able to create something a bit more readable than the list of bytes (but still binary identical)

.TEXT "CAS" ; 'name field'

.BYTE 'E' + $80

.WORD LINK            ; 'link field'

LINK .SET $ ;

.BYTE $04 + $40 ; 'name length field' (immediate word)

.WORD L1108 ; 'code field' - compile

.WORD w_case    ;

.WORD L1011 ; stack next word

.WORD $0000 ; 0

.WORD L1011 ; stack next word

.WORD $0009 ; 9

.WORD L1140 ; (part of) RUNS>

.BYTE $00, $E7, $FF ; ???

w_case:

.WORD L1142 ; (part of) RUNS>

.WORD L0879     ; DROP

.WORD L04B6 ; exit

I think I understand most of that, although I am not sure about the code that makes up the "RUNS>" bit.

The important thing is that it still builds binary identical, and I do not think there are any absolute links, so the code could move around and still build and work.

What next?

I have a few things to add in terms of functionality and also hardware support. If you think of anything else that would be useful, there is still about 2.5KB remaining.

I am also thinking about spiting up the source further into separate files for each word, grouped in folders, rather than all the related words in a single file etc. Not sure if that is necessary or beneficial, but it might make reordering things a bit easier. I will try it for the new words, and if it works out, I will probably go back and reformat the existing code (I will go back to this version and make it build identical before I add back the new code).

I also hope none of that comes off as critical or negative, that wasn't my intention, this was just my choice to give myself a lot of work translating someone else's code to an archaic assembler that I happen to like, to theoretically make my life easier in future.


Adverts

The Minstrel 4th is available form my Tindie store:

I can still ship worldwide.

Currently it looks like Royal Mail to the US is working although it seems I now have to pay the 10% tariff, so hopefully that will be plain sailing and no problems with customs. We're all pawns in a petulant child's political games, but we've got to just keep going and try to make this stuff work.

I have also built some more Mini PET 40/80 Internal boards, since the Mini PET II is still in development but people keep asking, so here they are.



Patreon

You can support me via Patreon, and get access to advance previews of development logs on new projects like the Mini PET II and Mini VIC and other behind the scenes updates. This also includes access to my Patreon only Discord server for even more regular updates.

Sunday, 24 August 2025

Minimal ZX81 Compute and Display Code

Over on my Patreon Discord, we have been looking at several versions of Forth for the ZX81, including Husband Forth and Tree Forth.

Those (just about) work on the ZX81, but none of them work on the Minstrel 3. George Beckett is currently reverse engineering those to see how they work, and we think we know now why they aren't running on the Minstrel 3. Geroge's work in progress can be found here.

As part of that, George had isolated the display routines and I suggested the main loop could be replaced with a delay to give a minimal implementation of just the display, so we can analyse it further.

That turned out to be more complicated than I expected. More on that to follow another day.

Whilst that was going on, I thought it would be interesting to compare that to a similarly cut down ZX81 display routine.

So that's what I did.

I have got it down to under 200 bytes (plus the font), and it may be useful for anyone writing some stand alone code to run on ZX81 or Minstrel 3 hardware. Maybe as the basis for a self test ROM or something like that? a ROM based game?

This is based on 8K BASIC (and the incredibly useful annotated disassembly by Geoff Wearmouth). That ROM was supplied to run on the ZX80 and ZX81, but I have only implemented "slow mode" or "compute and display", which is only available on the ZX81 hardware. It will always be running user code in between drawing the screen.

It has simplified things not having to worry about supporting this and the "fast" mode where it is either just running code drawing the screen.

How does it work?

From the user code point of view, the flowchart looks something like this.

The system starts up, does a bit of initialisation and starts off the display. Then it jumps into the user code where it does it's own setup and finally enters the user code main loop and just keeps running around.

Somewhere in the background, the display is being generated, but the user code does not need to know or care about that (unless it is doing anything timing specific).

What actually happens is slightly different, the display code is actually in control and it keeps stopping and starting the user code as required.

The user code runs in 56 bursts of around 140 cycles during the top border and another identical set during the bottom border, giving a total of around 16,000 cycles per 20ms frame, or the equivalent of about one quarter speed, or 0.8 MHz.

You can see in this trace the two blocks in red at the start and end of the display cycle (left and right of the trace). This is where the user code is running. It is paused for the entire central section where the Z80 is occupied drawing the display - executing NOPs to clock through the display file as the display hardware is generating the display on the fly and sending that to the electron gun drawing the display on the CRT we are both pretending you are viewing it on.

The trace above shows time progressing from left to right over the course of a frame. On the screen, it moves from left to right each line, and from top to bottom over the frame. The computing happens in the borders, and the display happens in the middle, where it needs to be.

Compare that to the ZX80 and ZX81 in "fast" mode, where it can either run code all the time.

or it can only draw the display (and simply wastes time in the borders)

Let's look at the code

The code involved is actually quite short, so we can go through all of it here.

START

The Z80 starts at address $0000. The code here is brief, to leave space for RST handlers at $0008, $0010, etc. up to $0038. (If you aren't aware, those are the places for short, fast, common routines that can be called with a single byte instruction RST $08 etc.)

Those aren't used here, but the space has been left in case the final application needs to make use of them in future.

The first instruction turns off the NMI generator. When active, that will generate an NMI pulse when a hardware counter reaches 64µs at the end of a display line. It is turned off until we are ready.

The second instruction sets the stack pointer to the top of RAM, assuming 16K, but it could be adjusted or a RAM test routine added as required.

Then it jumps to the system init code...

INIT

The code here sets up the display file, an initial newline character, then 24 lines of 32 space characters with a newline at the end of each.

You could start with a collapsed display file, just 25 newline characters, but I don't think there is any reason not to use a full one, and I am thinking you might be updating the screen and until you have finished, you could have overwritten some newlines, but not added enough back to fill the screen.

The I register is set to the MSB of the address of the font ROM which is used by the display hardware to read the character bitmap data.

The INIT_DISPLAY routine is called, and then it continues on to the user code (well sort of).

INIT_DISPLAY

What INIT_DISPLAY actually does is effectively pause the main code path, pushing its registers onto the stack (the return address is also already on there as part of the CALL).

It then drops through to START_FRAME.

START_FRAME

This is the start of the display routine proper.

The frame starts with a vertical sync pulse. There is a slight delay before the pulse starts, then a longer delay before it finishes.

8K BASIC originally used a VSync pulse of 380µs, about 6 display lines. The composite video spec says it should be 8 lines, so I have adjusted the timing to match the spec of 8 x 64µs = 512µs. That takes the display from 310 lines as standard to 312, which is what it should be.

This is the place to do any keyboard scanning required. I have removed the code here to simplify things. A single IO read operation is required to start the VSync pulse, and here that is used to read bit 6 of the keyboard port, the NTSC jumper. It sets the number of lines in the top and bottom borders accordingly, 55 lines for a PAL system, 31 for NTSC. There is an extra transition line at the end of each border, so it is actually 56 and 32.

8 + 56 + (24x8) + 56 = 312 lines (two frames = 624 lines, close enough to the 625 specified)

8 + 32 + (24x8) + 32 = 264 lines (two frames = 528 lines, close enough to the 525 specified)

Any IO write ends the VSYNC pulse, then it is time to draw the display.

(I did consider using the hardware to time the remaining 6 or 7 lines after this code, rather than a delay, but I though that might add unnecessary complication, and would make it more complicated to add back in keyboard scanning code.)

The HL register pair is set to the start of the display file (a newline / halt instruction) and then setting bit 7 of the H register moves that to the echo in high RAM. (The display hardware detects instruction reads in the high RAM area and feeds the processor NOP instructions instead)

Then it's time to draw the top border.

DRAW_BORDER

When DRAW_BORDER is called, it pop's the return address off the stack and stores it in the IX register. This would be the instruction it would return to if it were to return now, but it has lots of other things to do before if finally returns to where it was called from.

Next it does a bit of manipulation with the number of border lines. The resultant value is set so that if you keep incrementing the A' register, it will hit zero when the appropriate number of lines has been drawn and the border is complete.

It then enables the NMI generator, which will generate an NMI interrupt at the end of each line.

Then the user mode registers are restored from when they were pushed on the stack way back in INIT_DISPLAY.

The RET instruction then returns from that call to INIT_DISPLAY, where it drops through to running the user code.

And then just as it gets started, the timer hits 64µs and a non-maskable interrupt occurs.

NMI

When the hardware counter reaches 208 cycles (64uS), the horizontal sync pulse beings to be generated. When the NMI Generator hardware is enabled (as it is now), that horizontal sync pulse also pulls the NMI pin low and creates a Non Maskable Interrupt. The Z80 pushes the address of the next instruction in User code land onto the stack, then jumps to the NMI handler at address $0066.

This increments the border line counter A' and checks to see if it has reached the end of the border. If it has not, it returns to user land and continues with the users code until the next NMI.

END_OF_BORDER

When it reaches the end of the border, it is time to pause the user code again, and registers are pushed onto the stack, the return address is already there from the call to the NMI handler.

It then sets up the pointer to the start of the high RAM mirror of the display file and stops the NMI generator. Finally it returns to the address we saved previously in IX.

AFTER_TOP_BORDER

This code continues setting up the counters and then calls the routine to draw the display. B is the row counter, 25 rows (one of which is the initial empty row), and C is the scan line counter, which is initialised to 1, ready to roll over on the first call.

DRAW_DISPLAY

For the first time here we enable maskable interrupts. The INT pin is hard wired to address line A6. The Z80 will be halted, so it will be internally running NOP instructions and the only external activity will be the refresh cycles. These were designed for dynamic RAM, which was larger and cheaper than the static RAM that the ZX81 used, but required to be accessed every 2ms to maintain the data. The Z80 could be set to automatically refresh a range of RAM when it was otherwise occupied, simplifying system design.

Here there is no DRAM, and the refresh counter is repurposed. It is preloaded with $F5, and that will count up with each 4 cycle instruction (4x 3.25MHz cycles = 8x 6.5MHz cycles = 1 character width on the screen). So after 11 cycles, it will clock around to $00 and A6 will go low and a maskable interrupt will occur.

The jump instruction goes to the first byte of the high RAM echo of the display file. This is a newline character, which is also the OP code for halt, so when it is executed, the Z80 halts.

This will push the return address onto the stack and call the maskable interrupt handler. The instruction after the initial newline / halt in the display file is the start of the first row of characters. The return address is now pointing to the start of this row (I hope you are still following this).

MASKABLE_INTERRUPT

Each row of characters produces eight lines on the display, one for each row of pixels in the character bitmaps.

When drawing the subsequent lines, the return address is the start of the next row of characters, that is thrown away and it is instead sent back to the previously stored start of the current row.

When the scanline counter reaches zero (which it will the first time through as it was pre-loaded with 1), the return address of the next row is used instead, and it will start on that row next time.

The refresh register is set to $DD, so it will trigger after 35 character widths. It will have been halted sometime before that count is reached, depending on the number of characters in the row. The shorter the row, the more time it spends halted, and it will always get the next interrupt at the same time at the end of each scanline.

When all the rows are complete, it returns to the previous address on the stack, the AFTER_DISPLAY function.

AFTER_DISPLAY

From there, it calls DRAW_BORDER again, and that loops around drawing the bottom border lines. Each line it jumps back to user code (remember that?) and is then interrupted by the NMI in the same way as the top border.

After the border is complete, it returns to AFTER_BOTTOM_BORDER, which jumps back to START_FRAME and it all begins again.

Meanwhile.....

USER_INIT

Throughout all of this, control has been returning to the user code during drawing of the borders.

The code here is just an example to put something onto the display.

This is filling the screen with a character set, offset each line to make it a little more interesting.

USER_LOOP

After initialisation, there is a loop which goes through the display file incrementing each character. It masks each off so that it will never go out of range. This gives a nice animated effect.

I did write a couple of faster versions, but it was a bit jarring to see it moving so fast, so I have stayed with the slower, more visually appealing version.

You could of course fill the remaining 7.5K of the ROM with whatever code you wanted.

Side notes

Timing is very important in code like this. A few cycles can make all the difference.

Here the top of the display is tearing to the left. This was due to one of the lines (the transition between the top border and the first display line) was short, clocking in at 60.6µs instead of 63.7µs like the rest. The TV takes 30 or 40 scan lines before it readjusts.

(if the line is too long, it will tear to the right)

The scanline counter used to index the character pixel data is in hardware (half of a 393 counter), and has to be duplicated in the Z80 (in the C register). These need to be in sync with each other or you can get effects like this where it is one line out, so you see bitmaps from lines 7,0,1,2,3,4,5,6 instead of 0,1,2,3,4,5,6,7 (see the graphics characters top left).

The counter is reset by the VSync pulse, so there needs to be a specific number of cycles between that and the line starting to keep them in sync with each other.

Here are all the timings if you are interested. See the previous post to find out how these were generated.

This differs slightly from the ZX81 in that it uses 312 lines and a 512µs VSync.

Collapsed display file

I did test a version with a collapsed display file, with an increasing number of characters per line. Using the "grey border" jumper on the Minstrel 3 you can see it is correctly halting at the end of the characters, and so the background is used for the rest of the line.

No newline / halt characters?

One thing I investigated was setting it up to run from a fixed block of 32x24 characters, rather than having to include an extra character at the end of each line.

It seems there are no easy answers there. I did try setting it up so the refresh counter would hit the end just after the 32nd character, but that forces the display hard to the right which doesn't work particularly well.

It seems HForth uses something similar, but also has shorter display lines to try to make those more central, which leads to some of the display problems we are seeing.

One way it could be done would be patching the display file on the fly. Read the 33rd character, store it, and then replace it with a newline. When it is time for the next line, restore that saved character and take out the 33rd character of the next line.

That _shouldn't_ affect user code as any changes should happen between the borders where no user code is running, so everything should have been put back as it was before control is returned to the user code in the bottom border. However, I am not sure there will be enough cycles in the maskable interrupt handler to deal with it.

Where's the source code?

The code for this, and a compiled binary demo ROM are available on my github. This might make the basis of a self test ROM or a utility ROM, a terminal emulator? or an 8K game maybe? If you do use it for anything, let me know, there is space in the Minstrel 3 ROM for more ROM images if anyone fancies having a go at something.


Adverts

The Minstrel 3 (with hardware support for compute and display mode) and lots of other things are available from my Tindie Store.


Patreon

You can support me via Patreon, and get access to advance previews of development logs on new projects like the Mini PET II and Mini VIC and other behind the scenes updates. New releases like this will be notified to Patreon first, if you want to be sure to get the latest things. This also includes access to my Patreon only Discord server for even more regular updates.

Sunday, 24 November 2024

Five years of the Minstrel 3

Five years ago to the day, I put up a blog post announcing a new kit for sale. The Minstrel 3, a Z80 based, ZX81 compatible computer kit.

Today it is back, and for sale on Tindie again, and there is 5% off all Minstrel kits for the next month.

Shipping is only going to get slower as we move into the holiday season, so the sooner the better if you want to be sure to get your order in time.

Remember 2019? Lots of things have happened in those five years.

In that time, I have tweaked the Minsterl 3 design a bit, and added things like the Minstrel Expansion Bus header, so you can now add a microSD disk drive via the Minstrel Micro ZXpand that plugs directly into the board.

I have brought it back with two PCB options, one of which is a single board design, with the integrated keyboard.

I still have the versions without the keyboard for use with a ZX81 membrane or other keyboard, in a ZX81 case or whatever you can dream up. Still ideal as a drop in replacement for a dead ZX81.

During that time, the Z80 has also been discontinued, but fear not, I have secured a lifetime supply of Z80 chips, so these kits will be available with some of the last genuine Z80 chips ever made, date codes shortly after the last time buy deadline.

As usual, I have built one up to test the new PCB.

Whilst doing that, an idea for a change has occurred to me.

(actually, it was shortly after I had soldered in the bit that needed to be changed, but lets not mention that)

Yay, significantly past the last minute update.

Although it is something I have tried to address several times before - loading from tape on a Minstrel 3 isn't always great.

It works fine with my modified TZXduino / master tape creator, and some of the time with my Sony TCM-818, but I know people have problems with PC soundcards and phone apps and cassette recorders with lower level outputs

The problem stems from the logic chips used on the input port. On the ZX80 (and Minstrel 2), this was a 74LS365, a hex tri-state buffer.

The ZX81 ULA implemented something similar internally.

This operates in two states:

  • Reading the port
  • Not reading the port

When the port is being read, the input signals are transferred to the CPU databus. When the port is not being read the chip disconnects from the CPU databus and lets other things drive it.

This is a 74LS series chip, which means the input voltage thresholds are as follows:

  • Logic 0: 0 V to 0.8 V
  • Logic 1: 2.0 V to 5.5 V

That means the tape signal needs to reach 2V to be considered a 1.

When I designed the Minstrel 3, I moved to 74HC series logic for all the chips, these are faster, lower power, cleaner signals etc. However, one problem is the input voltage thresholds are now higher:

  • Logic 0: 0 V to 1.5 V
  • Logic 1: 3.5 V to 5.5 V

That means the tape now needs to be over 3.5V to register as a 1.

I have looked at various options over the years, different ways for boosting or biasing the signal. Transistors, op-amps, comparators etc. but none of them were quite right. Most of them helped in some situations, but not all.

For the Minstrel 4D (still available from TFW8b - https://www.tfw8b.com/product/minstrel-4d-turbo-jupiter-ace-compatible-computer-kit/), I used a microcontroller with a built in op-amp, and comparator with configurable references, so I was able to add a menu option to select a threshold voltage to suit various inputs and that worked quite well. I would like to use something like that with the Minstrel 3, and maybe one day there will be a Minstrel 3D that can use similar technology.

Testing the problem

Revisiting this problem afresh with this update, I have been trying things out.

I setup a Minstrel 2 (also back with optional integrated keyboard), and a recently refurbished Sony TCM-818 cassette recorder and tried to load some tapes.

I chose a selection of tapes ancient and modern, and tested the ones that would work on a ZX80 with the 8K ROM and most of them loaded reliably at about 3/4 volume.

I then switched to a Minstrel 3 and found that most of them didn't load.

I have been testing out a new module for the Minstrel Expansion Bus, the Minstrel Input Monitor.

(that is something else that changed, I created the Minstrel Expansion Bus and started to add a series of modules, but it seems no one was interested in that, so I haven't listed those on Tindie yet. Anyone interested? - http://blog.tynemouthsoftware.co.uk/2024/05/minstrel-expansion-bus.html)

The new module, the Minstrel Input Monitor shows when a key is pressed or data is being loaded from tape on two LEDs and also optionally via a sounder.

On the Minstrel 2, I could clearly hear the data being loaded.

On the Minstrel 3, the data just wasn't getting through as well.

I tried with the TZXduino, and that was fine, as expected.

How can I fix it?

Well, this was something that worked with 74LS input levels, but not with 74HC input levels.

So, why don't I use a chip with 74LS style inputs, either actual 74LS serise chips or 74HCT.

The 74HCT series has 74LS style inputs, and 74HC style outputs, so should work?

Well, it is not a good idea to mix logic families, a 74LS output will not generate a high enough logic 1 output to drive a 74HC input. However, a 74HC output can drive a 74LS input.

So I need a 74HCT365?

Well not quite, the design evolved a bit.

In designing the Minstrel 3, I tried to reduce the chip count where I could, and I found a way to save a chip or two.

There are only two things which drive the CPU side of the databus directly. The 74LS365 input port, and two 74LS05 chips which form the NOP generator.

This forces the CPU side of databus to all zeroes so the Z80 executes a NOP instruction whilst the rest of the circuitry on the other side of the 1K resistors is generating the display.

The 74LS05 is an open collector inverter, so if the input is high, it pulls the output low. If the input is low, it does nothing. (if you want it to read as a logic 1, you need a pull up resistor, for example, the first 74LS05 gate on the left).

I need to consider three states here

  1. The input port is being read
  2. A NOP is being generated
  3. Everything else

When the input port is being read, the 74LS365 is driving the Z80 data bus with the input port of the tape and keyboard signals.

When the NOP is being generated, the 74LS05 chips are driving the bus low to mimic a NOP command op code ($00).

When "everything else " is happening, the 74LS365 outputs are high impedence and the 74LS05 outputs are off.

I didn't want to use the 74LS05 chips in the Minstrel 3 as there was not a 74HC05 chip I could use in it's place.

The 74LS05's did actually survive until version 3.5 of the design.

Version 3.5.1 went to a 74HC244 to replace the 74LS05s.

I thought since I was using that, I may as well use the same chip for the 74LS365 input port.

The 244s didn't last long, I don't like those as the outputs and inputs are on alternating pins which makes routing more complicated.

I had already tried a pair of 74HC245 tri-state buffers in an earlier version, as the inputs are all on one side and the outputs on the other, which is much neater.

That was the very first red V3.0 prototype which was still using 74LS logic, I went back to the 05's for V3.1.

After seeing that, I remembered I didn't like the row of 20 pin chips, they didn't seem quite right.

I already had 74HC257s in the design, so I wondered if I could use a pair of those to replace the pair of 74HC245 buffers?

The 74HC257 works in three modes

  1. Inputs A are connected to the output
  2. Inputs B are connected to the output
  3. The output is disconnected, high impedence.

That fits with the requirements of the input port and the NOP generator. I just need a "NOP or Input port" signal to control the output on or off, and a second signal to select between NOP and input port.

The result is two 74HC257s replacing the 74LS365 and two 74LS05s.

I looked at two options here, the logical move would be to replace those two 74HC257s with two 74HCT257s. Those have TTL level inputs, but output the same as the 74HC series.

However, I have decided to go for two 74LS257s instead.

The output stages are different. the HC and HCT series use two FETs to drive the output strongly high or low.

Where as the LS series have a strong drive low via a transistor, but the drive high is via a pullup resistor, in this case nominally 100Ω.

The way this is used in the overall design is this feeds the Z80 directly, whilst the ROM and RAM are being used to generate the video signals. The two sides are connected via 1KΩ bus isolation resistors.

ZX81 External Keyboards?

I was hoping this might help with the issue of external keyboards (http://blog.tynemouthsoftware.co.uk/2022/05/zx81-external-keyboards-and-the-minstrel-3.html).

The problem is external devices are connected to the isolated side of the databus. The ZX81 external keyboards rely on driving the bus at the same time as ZX81 ULA, so either can indicate a key is being pressed. They do not work on a ZX80, or the Minstrel 2 or 3.

On the ZX80 and the Minstrel 2, you end up with a situation something like this, the external keyboard on the left trying to influence the Z80 on the right.

When neither keyboard is pressing a key, you end up with the datasbus seeing a logic 1 due to the 100Ω pullup on the right. The one on the left is also pulling it high, but via the 1KΩ resistor, so you effectively end up with 1100Ω in parallel with 100Ω, which means the bus is pulled up by a bit less than 100Ω. (N.B. I am assuming ideal transistors here just to make things easier).

When the 257 drives the bus low due to the internal keyboard or NOP generator, no pullups are involved. It is directly driving the databus low, so it does not really matter about the 1100Ω combined pullup on the external keyboard side.

The problem is the reverse does not work.

When the external keyboard tries to drive the bus low, the 257 is trying to drive it high, so you end up with a potential divider, 1KΩ to 0V and 100Ω to 5V. That gives a voltage on the Z80 data pin of about 4.55V, which still very much counts as a high and the external key press does not register.

In order to register as a logic 0, the bus isolation resistor would need to be dropped to something like 50Ω, which does not sound like a good idea as that would put a load of 100mA for each bit on the bus.

In order to make this design work with an external keyboard needs an open collector drive, which is probably what the ZX81 ULA does. I have tried to find a way of doing that, ideally an open collector version of the 257, but I cannot find such a thing. It would either need a couple of 74LS07's or 74HC125s or maybe diodes on each of the drive signals between the 257.

It looks like changing to a 74HCT257 or 74LS257 will help with tape input, but neither will help with external keyboard situation unfortunately.

The control signals are both generated from 74HC outputs, those can drive LS style inputs, so that is OK.

The input port signals are from the keyboard, which is a matrix of the Z80 address lines, via diodes with pullup resistors. That should be fine. The tape input, as discussed, is better feeding a 74LS input.

The 365 is a hex buffer, so only drives bits D0-D4 (the keyboard) and D7 (the tape input).

There is also one extra pin which is cheated on the ZX80. If a diode is fitted, D6 reads as a zero to indicate NTSC, without the diode, it floats up to a 1 for PAL. That can be replaced by a 0V or 5V jumper to select PAL or NTSC.

Bit 5 is not used, so that is set to high, so that it could be overloaded externally if that were ever required.

The NOP generator inputs are just tied to 0V, so that's fine.

The outputs are wired direct to the Z80 databus, and that is the same Z80 chip as I use on the Minstrel 2, so it is fine with 74LS outputs. Nothing else drives the databus directly, so there is nothing to conflict with.

Sorted.

The extent of the changes required is updating the silkscreen from "257" to "LS257".

That was easy.

Let's give it a go.

And yes, it works perfectly.

OK, it works as well as the Minstrel 2 does. As well as a ZX80 would. And probably about as well as a ZX81 would do, since the ULA inputs would have been modeled on the 74LS TTL chips they were replacing.

The only ones I couldn't get to load were things like 3D Monster Maze, where you can clearly here the tape is worn out in places and is never going to load again. (blog post to follow.....)

I will continue testing, but I think that's a given now. I will leave the other 74HC257s as is. They need to remain as they are, so I will just need to be clear where the 74LS257s go on the board. The 74HC257s are marked "257", and the two non-HC chips are marked LS257.

The next batch of PCBs will have this marked, the last of the current ones will get a white paint dot on this two chips.


Advertisements

Minstrel 2 and 3 kits are available from my Tindie store, with worldwide shipping and 5% off for the next month. Order soon to beat the usual postal slow downs in December.

Versions are available for ZX81 case:

Or standalone with keyboard:

And also Minstrel 3 with ZXpand microSD card interface:

I am in the process of moving things over there from my SellMyRetro store, so if there is anything that you want, let me know and I'll add it.

I have recently added lots of PET repair and upgrade parts, more to follow.

Bluesky

For those interested in such things, I can now be found on Bluesky, and I expect to be posting more there.

Patreon

You can support me via Patreon, and get access to advance previews of posts like this and behind the scenes updates. These are often in more detail than I can fit in here, and some of these posts contain bits from several Patreon posts. This also includes access to my Patreon only Discord server for even more regular updates.