Files
Basys3RiscV/tools/send-hex.py
T
brad ArantandClaude Opus 5.5 addf0157fc Monitor: wide 132x64 screen showing everything at once
On the 132x64 screen the monitor shows PC and all integer registers, all
float registers (hex and decimal) with FCSR decoded, mstatus/mepc/mcause/
mtval/cycle/instret and the breakpoint, 24 rows of disassembly beside the
stack, and 14 rows of memory, with changed registers highlighted; the 80x32
layout is unchanged. R takes float register names. The CPU's trap CSRs
start at 0, so reading them before the first trap no longer hangs the
simulated bus. send-hex accepts the prompt on any row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 00:00:43 -08:00

115 lines
4.1 KiB
Python
Executable File

#!/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 (row 30 on the 80x32
# screen, 64 on the 132x64 one); its message comes after the prompt, and the
# cursor is turned back on last
PROMPT = rb"\x1b\[\d+;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)