Files
Basys3Terminal/tools/send-hex.py
T
brad ArantandClaude Opus 5.5 743071cff3 The Iron Keep: a top-down escape game, held-key ports, monitor HEX loader
games/keep: an original game in C for the Z-80 using the sprites - twelve
rooms, guards that patrol, see along rows and columns and shoot, keys and
locked doors, gold, ammunition and a crown to steal. gen.py holds the art
and castle map and checks reachability; test-keep.py runs it in z80emu on
a model of the board's ports, takes screenshots and has a bot play it
through. keep.bas loads KEEPGAME at 8600h and CALLs it.

Ports 88h/89h read keys held down (ps2_keystate), the monitor writes
Intel HEX records typed at its prompt, and tools/send-hex.py sends a
whole file and saves it as a memory file. Testbench covers both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 09:21:02 -08:00

109 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Load an Intel HEX file (as SDCC writes it) into the Basys 3 Z-80's memory
through the monitor, and optionally save it as a memory file in flash.
The board needs SW15 and SW14 up and BASIC at READY; nothing else may be
using the serial port, and the baud rate must match SW1:0. The tool types
MONITOR, sends every record (the monitor writes each one into memory),
saves the loaded range if asked, and leaves the monitor again.
tools/send-hex.py games/keep/keep.ihx --save KEEPGAME --baud 3000000
Code must go at 8000h or above. Memory files are loaded back with BLOAD in
BASIC or LOAD in the monitor.
"""
import argparse
import os
import re
import select
import termios
import time
BAUDS = {9600: termios.B9600, 115200: termios.B115200, 921600: termios.B921600,
3000000: termios.B3000000}
ap = argparse.ArgumentParser()
ap.add_argument("file", help="Intel HEX file")
ap.add_argument("--save", metavar="NAME", help="save the loaded bytes in flash under this name")
ap.add_argument("--port", default="/dev/ttyUSB1")
ap.add_argument("--baud", type=int, default=115200, choices=sorted(BAUDS))
a = ap.parse_args()
records = [l.strip() for l in open(a.file) if l.startswith(":")]
if not records or not records[-1].upper().startswith(":00000001"):
records.append(":00000001FF")
for r in records:
if len(r) > 79:
raise SystemExit("record too long for the monitor (79 characters): " + r[:20])
if a.save and not re.fullmatch(r"[A-Za-z][A-Za-z0-9]{0,7}", a.save):
raise SystemExit("a file name is 1-8 letters and digits, starting with a letter")
fd = os.open(a.port, os.O_RDWR | os.O_NOCTTY)
t = termios.tcgetattr(fd)
t[0] = termios.IXON
t[1] = 0
t[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
t[3] = 0
t[4] = t[5] = BAUDS[a.baud]
t[6][termios.VMIN] = 0
t[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, t)
termios.tcflush(fd, termios.TCIFLUSH)
buf = b""
def send(s):
os.write(fd, s.encode("ascii"))
def wait_for(pattern, timeout=10.0):
"""Read until the output since the last call matches; return it."""
global buf
end = time.time() + timeout
while time.time() < end:
m = re.search(pattern, buf, re.S)
if m:
out, buf = buf[:m.end()], buf[m.end():]
return out
r, _, _ = select.select([fd], [], [], 0.05)
if r:
buf += os.read(fd, 65536)
raise SystemExit("no answer from the board (waiting for %r); last output: %r" % (pattern, buf[-200:]))
# the monitor's command line, redrawn after each command; its message comes
# after the prompt, and the cursor is turned back on last
PROMPT = rb"\x1b\[30;1H> .*?\x1b\[\?25h"
send("\r")
time.sleep(0.3)
send("MONITOR\r")
wait_for(rb"Z-80 MONITOR")
wait_for(PROMPT)
n = 0
for r in records:
send(r.upper() + "\r")
out = wait_for(PROMPT)
if re.search(rb"BAD HEX|CHECKSUM|ROM: NOT|NO HEX", out):
send("X\r")
raise SystemExit("the monitor refused record %d: %s" % (n + 1, r))
n += 1
if n % 50 == 0:
print("\r%d/%d records" % (n, len(records)), end="", flush=True)
m = re.search(rb"HEX LOADED ([0-9A-F]{4})-([0-9A-F]{4})", out)
if not m:
send("X\r")
raise SystemExit("the monitor did not report the loaded range")
lo, hi = m.group(1).decode(), m.group(2).decode()
print("\rloaded %s-%s (%d bytes) from %d records" % (lo, hi, int(hi, 16) - int(lo, 16) + 1, len(records)))
if a.save:
send('SAVE "%s" %s %s\r' % (a.save.upper(), lo, hi))
out = wait_for(PROMPT, 30)
if b"SAVED" not in out:
send("X\r")
raise SystemExit("saving failed: %r" % out[-120:])
print('saved as "%s"; BLOAD "%s" in BASIC loads it at %sh' % (a.save.upper(), a.save.upper(), lo))
send("X\r")
wait_for(rb"\x1b\[\?47l", 5) # the monitor's screen goes away
os.close(fd)