Files
Basys3RiscV/tools/send-hex.py
T
brad ArantandClaude Opus 5.5 5930b958b4 Basys 3 RISC-V computer
The Basys 3 Z-80 computer with the Z-80 replaced by an RV32IM processor
written from scratch (rtl/rv32_cpu.v): multi-cycle, 90 MHz, CSRs and
traps, interrupts, two hardware triggers and a resumable NMI for the
monitor. Passes riscv-tests rv32ui/um/mi.

rv32_system.v keeps all the Z-80 machine's peripherals, with I/O port N
at FFFFFF00h + N, 80 KB of RAM with BASIC preloaded, and a 32 KB monitor
ROM. BASIC, the five games and the monitor (with an RV32 disassembler,
assembler, breakpoints and single step) are ported to RISC-V GCC. Python
emulator and tests in tools/; full-system simulation in sim/.

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

114 lines
4.0 KiB
Python

#!/usr/bin/env python3
"""Load an Intel HEX file (as objcopy -O ihex writes it) into the Basys 3 RISC-V
computer'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 0A000h 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))
ap.add_argument("--no-date", action="store_true", help="don't set BASIC's clock (which dates the file)")
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)
if not a.no_date: # the file gets the PC's date
send(time.strftime('DATE "%Y-%m-%d %H:%M:%S"\r'))
wait_for(rb"READY\r\n")
send("MONITOR\r")
wait_for(rb"RISC-V 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]{5})-([0-9A-F]{5})", 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)