Basys 3 ASCII terminal: VGA 80x30 text, USB keyboard, UART

- VGA 640x480@60 text display, 8x16 CP437 font ROM from Linux console fonts
- USB HID keyboard (PS/2 via onboard PIC24), scan code set 2 to ASCII
  with xterm sequences for cursor/editing keys
- UART RX/TX with switch-selectable baud, local echo option
- Terminal engine: control codes, deferred wrap, hardware scroll,
  VT100/ANSI subset (cursor moves, erase, reverse video, cursor hide)
- Vivado build/program/flash scripts and xsim whole-design testbench

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
barantandClaude Opus 5.5 committed 2026-11-17 10:26:13 -08:00
commit 0e95a14cfe
18 files changed
+5596

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
sim/work/
build/
.Xil/
*.jou
*.log
*_out.txt
+105
View File
@@ -0,0 +1,105 @@
# Basys 3 ASCII Terminal
Turns a Digilent Basys 3 (Artix-7 XC7A35T) into a stand-alone serial terminal:
- **Screen**: VGA port, 640x480 @ 60 Hz, 80 columns x 30 rows, 8x16 CP437 font
(box-drawing characters included), green/amber/white/cyan.
- **Keyboard**: a USB keyboard in the **USB HID host** port (J2). The board's
PIC24 presents it to the FPGA as a PS/2 keyboard.
- **Serial line**: the micro-USB **PROG/UART** port (the FTDI chip), 8N1. Bytes
received there are drawn on the screen. Keystrokes are sent out there.
Plug the micro-USB into a PC and open the serial port (`/dev/ttyUSB1` is usually
the UART; `ttyUSB0` is JTAG). For example:
```bash
picocom -b 115200 /dev/ttyUSB1
```
To get a Linux login on the terminal, run a getty on that port:
```bash
sudo systemctl start serial-getty@ttyUSB1.service
```
## Controls
| Control | Function |
|---|---|
| SW1:0 | Baud: `00` 115200, `01` 9600, `10` 19200, `11` 57600 |
| SW2 | Local echo |
| SW3 | Received LF also does CR (for hosts that send bare `\n`) |
| SW5:4 | Colour: `00` green, `01` amber, `10` white, `11` cyan |
| SW6 | Backspace sends DEL (`7F`) instead of BS (`08`) |
| SW7 | Enter sends CR LF instead of CR |
| BTNC | Reset (clears screen, shows banner) |
| BTNU | Clear screen |
| LED7:0 | Last byte received |
| LED12 / 13 / 14 / 15 | Bell / Caps Lock / UART RX activity / keyboard activity |
| 7-segment | Left: last keyboard scan code. Right: last byte sent. |
For a Linux getty, set SW6 on (Backspace = DEL).
## Terminal features
- Control characters: CR, LF, VT, FF (clear screen), BS, TAB (every 8 columns),
BEL (LED12).
- Auto-wrap at column 80 (deferred, like a VT100), and hardware scrolling.
- VT100/ANSI subset:
- Cursor movement `ESC[nA/B/C/D`, `ESC[r;cH`, `ESC[r;cf`, `ESC[nd`, `ESC[nG`
- Erasing with `ESC[nJ` and `ESC[nK`
- Reverse video with `ESC[7m`, `ESC[27m` and `ESC[0m`
- Show/hide cursor with `ESC[?25h` and `ESC[?25l`
- `ESC c`, `ESC D`, `ESC E`, `ESC M`, `ESC 7`, `ESC 8`
- Keyboard: Shift, Caps Lock, Ctrl (`^A`..`^Z`, `^[` etc.).
- The arrow keys, Home, End, Insert, Delete, PgUp and PgDn send xterm sequences.
- F1 to F4 send `ESC O P` to `ESC O S`.
- The keypad always types digits.
`TERM=vt100` is a good setting on the host. Colour SGR codes and scroll regions
are not implemented, so full-screen programs that need them may draw incorrectly.
## Build and program
Requires Vivado. The scripts use the newest install in `~/vivado/<version>/Vivado`;
set `VIVADO=/path/to/Vivado` to pick another. On this machine 2026.1 has no
license, so use 2025.2 (`export VIVADO=~/vivado/2025.2/Vivado`).
```bash
./scripts/build.sh # bitstream -> build/basys3_terminal.bit (+ .mcs)
```
```bash
./scripts/build.sh program # build and load into the FPGA (until power-off)
```
```bash
./scripts/build.sh flash # build and write QSPI flash; set JP1 to QSPI to boot from it
```
## Simulation
`sim/tb_terminal.v` covers the whole design. It types keys over PS/2 and checks
the bytes sent on the UART. It sends text and escape sequences into the UART
and prints the character buffer. It also checks VGA sync timing and saves one
frame as `sim/work/frame.png`.
```bash
VIVADO=~/vivado/2025.2/Vivado ./scripts/sim.sh
```
`scripts/vivado_env.sh` adds an ncurses 5 compatibility link under `build/`,
which Vivado needs on newer distros.
## Layout
| Path | Contents |
|---|---|
| `rtl/basys3_terminal.v` | Top level: reset, switches, FIFOs, banner, LEDs |
| `rtl/term_ctrl.v` | Terminal engine (control codes, ANSI parser, scrolling) |
| `rtl/text_display.v` | VGA timing, character RAM, font lookup |
| `rtl/ps2_keyboard.v` | PS/2 receiver and scan code set 2 to ASCII |
| `rtl/uart.v` | UART receiver and transmitter |
| `rtl/fifo.v`, `rtl/sevenseg.v` | Helpers |
| `font/font.mem` | 256x16 font ROM, made by `tools/psf2mem.py` from the Linux console fonts |
| `constraints/basys3.xdc` | Pin assignments |
+94
View File
@@ -0,0 +1,94 @@
## Basys 3 (XC7A35T-1CPG236C) pins for basys3_terminal
## 100 MHz clock
set_property -dict { PACKAGE_PIN W5 IOSTANDARD LVCMOS33 } [get_ports clk]
create_clock -add -name sys_clk_pin -period 10.00 -waveform {0 5} [get_ports clk]
## Switches
set_property -dict { PACKAGE_PIN V17 IOSTANDARD LVCMOS33 } [get_ports {sw[0]}]
set_property -dict { PACKAGE_PIN V16 IOSTANDARD LVCMOS33 } [get_ports {sw[1]}]
set_property -dict { PACKAGE_PIN W16 IOSTANDARD LVCMOS33 } [get_ports {sw[2]}]
set_property -dict { PACKAGE_PIN W17 IOSTANDARD LVCMOS33 } [get_ports {sw[3]}]
set_property -dict { PACKAGE_PIN W15 IOSTANDARD LVCMOS33 } [get_ports {sw[4]}]
set_property -dict { PACKAGE_PIN V15 IOSTANDARD LVCMOS33 } [get_ports {sw[5]}]
set_property -dict { PACKAGE_PIN W14 IOSTANDARD LVCMOS33 } [get_ports {sw[6]}]
set_property -dict { PACKAGE_PIN W13 IOSTANDARD LVCMOS33 } [get_ports {sw[7]}]
set_property -dict { PACKAGE_PIN V2 IOSTANDARD LVCMOS33 } [get_ports {sw[8]}]
set_property -dict { PACKAGE_PIN T3 IOSTANDARD LVCMOS33 } [get_ports {sw[9]}]
set_property -dict { PACKAGE_PIN T2 IOSTANDARD LVCMOS33 } [get_ports {sw[10]}]
set_property -dict { PACKAGE_PIN R3 IOSTANDARD LVCMOS33 } [get_ports {sw[11]}]
set_property -dict { PACKAGE_PIN W2 IOSTANDARD LVCMOS33 } [get_ports {sw[12]}]
set_property -dict { PACKAGE_PIN U1 IOSTANDARD LVCMOS33 } [get_ports {sw[13]}]
set_property -dict { PACKAGE_PIN T1 IOSTANDARD LVCMOS33 } [get_ports {sw[14]}]
set_property -dict { PACKAGE_PIN R2 IOSTANDARD LVCMOS33 } [get_ports {sw[15]}]
## LEDs
set_property -dict { PACKAGE_PIN U16 IOSTANDARD LVCMOS33 } [get_ports {led[0]}]
set_property -dict { PACKAGE_PIN E19 IOSTANDARD LVCMOS33 } [get_ports {led[1]}]
set_property -dict { PACKAGE_PIN U19 IOSTANDARD LVCMOS33 } [get_ports {led[2]}]
set_property -dict { PACKAGE_PIN V19 IOSTANDARD LVCMOS33 } [get_ports {led[3]}]
set_property -dict { PACKAGE_PIN W18 IOSTANDARD LVCMOS33 } [get_ports {led[4]}]
set_property -dict { PACKAGE_PIN U15 IOSTANDARD LVCMOS33 } [get_ports {led[5]}]
set_property -dict { PACKAGE_PIN U14 IOSTANDARD LVCMOS33 } [get_ports {led[6]}]
set_property -dict { PACKAGE_PIN V14 IOSTANDARD LVCMOS33 } [get_ports {led[7]}]
set_property -dict { PACKAGE_PIN V13 IOSTANDARD LVCMOS33 } [get_ports {led[8]}]
set_property -dict { PACKAGE_PIN V3 IOSTANDARD LVCMOS33 } [get_ports {led[9]}]
set_property -dict { PACKAGE_PIN W3 IOSTANDARD LVCMOS33 } [get_ports {led[10]}]
set_property -dict { PACKAGE_PIN U3 IOSTANDARD LVCMOS33 } [get_ports {led[11]}]
set_property -dict { PACKAGE_PIN P3 IOSTANDARD LVCMOS33 } [get_ports {led[12]}]
set_property -dict { PACKAGE_PIN N3 IOSTANDARD LVCMOS33 } [get_ports {led[13]}]
set_property -dict { PACKAGE_PIN P1 IOSTANDARD LVCMOS33 } [get_ports {led[14]}]
set_property -dict { PACKAGE_PIN L1 IOSTANDARD LVCMOS33 } [get_ports {led[15]}]
## 7-segment display
set_property -dict { PACKAGE_PIN W7 IOSTANDARD LVCMOS33 } [get_ports {seg[0]}]
set_property -dict { PACKAGE_PIN W6 IOSTANDARD LVCMOS33 } [get_ports {seg[1]}]
set_property -dict { PACKAGE_PIN U8 IOSTANDARD LVCMOS33 } [get_ports {seg[2]}]
set_property -dict { PACKAGE_PIN V8 IOSTANDARD LVCMOS33 } [get_ports {seg[3]}]
set_property -dict { PACKAGE_PIN U5 IOSTANDARD LVCMOS33 } [get_ports {seg[4]}]
set_property -dict { PACKAGE_PIN V5 IOSTANDARD LVCMOS33 } [get_ports {seg[5]}]
set_property -dict { PACKAGE_PIN U7 IOSTANDARD LVCMOS33 } [get_ports {seg[6]}]
set_property -dict { PACKAGE_PIN V7 IOSTANDARD LVCMOS33 } [get_ports dp]
set_property -dict { PACKAGE_PIN U2 IOSTANDARD LVCMOS33 } [get_ports {an[0]}]
set_property -dict { PACKAGE_PIN U4 IOSTANDARD LVCMOS33 } [get_ports {an[1]}]
set_property -dict { PACKAGE_PIN V4 IOSTANDARD LVCMOS33 } [get_ports {an[2]}]
set_property -dict { PACKAGE_PIN W4 IOSTANDARD LVCMOS33 } [get_ports {an[3]}]
## Buttons
set_property -dict { PACKAGE_PIN U18 IOSTANDARD LVCMOS33 } [get_ports btnC]
set_property -dict { PACKAGE_PIN T18 IOSTANDARD LVCMOS33 } [get_ports btnU]
## VGA
set_property -dict { PACKAGE_PIN G19 IOSTANDARD LVCMOS33 } [get_ports {vgaRed[0]}]
set_property -dict { PACKAGE_PIN H19 IOSTANDARD LVCMOS33 } [get_ports {vgaRed[1]}]
set_property -dict { PACKAGE_PIN J19 IOSTANDARD LVCMOS33 } [get_ports {vgaRed[2]}]
set_property -dict { PACKAGE_PIN N19 IOSTANDARD LVCMOS33 } [get_ports {vgaRed[3]}]
set_property -dict { PACKAGE_PIN N18 IOSTANDARD LVCMOS33 } [get_ports {vgaBlue[0]}]
set_property -dict { PACKAGE_PIN L18 IOSTANDARD LVCMOS33 } [get_ports {vgaBlue[1]}]
set_property -dict { PACKAGE_PIN K18 IOSTANDARD LVCMOS33 } [get_ports {vgaBlue[2]}]
set_property -dict { PACKAGE_PIN J18 IOSTANDARD LVCMOS33 } [get_ports {vgaBlue[3]}]
set_property -dict { PACKAGE_PIN J17 IOSTANDARD LVCMOS33 } [get_ports {vgaGreen[0]}]
set_property -dict { PACKAGE_PIN H17 IOSTANDARD LVCMOS33 } [get_ports {vgaGreen[1]}]
set_property -dict { PACKAGE_PIN G17 IOSTANDARD LVCMOS33 } [get_ports {vgaGreen[2]}]
set_property -dict { PACKAGE_PIN D17 IOSTANDARD LVCMOS33 } [get_ports {vgaGreen[3]}]
set_property -dict { PACKAGE_PIN P19 IOSTANDARD LVCMOS33 } [get_ports Hsync]
set_property -dict { PACKAGE_PIN R19 IOSTANDARD LVCMOS33 } [get_ports Vsync]
## USB-UART (FTDI), named from the FPGA's point of view
set_property -dict { PACKAGE_PIN B18 IOSTANDARD LVCMOS33 } [get_ports RsRx]
set_property -dict { PACKAGE_PIN A18 IOSTANDARD LVCMOS33 } [get_ports RsTx]
## USB HID host (PIC24) - keyboard as PS/2
set_property -dict { PACKAGE_PIN C17 IOSTANDARD LVCMOS33 PULLUP true } [get_ports PS2Clk]
set_property -dict { PACKAGE_PIN B17 IOSTANDARD LVCMOS33 PULLUP true } [get_ports PS2Data]
## Asynchronous / human-speed I/O
set_false_path -from [get_ports {btnC btnU sw[*] RsRx PS2Clk PS2Data}]
set_false_path -to [get_ports {led[*] seg[*] dp an[*] RsTx}]
## Configuration
set_property CONFIG_VOLTAGE 3.3 [current_design]
set_property CFGBVS VCCO [current_design]
set_property BITSTREAM.GENERAL.COMPRESS TRUE [current_design]
set_property BITSTREAM.CONFIG.SPI_BUSWIDTH 4 [current_design]
set_property CONFIG_MODE SPIx4 [current_design]
+4097
View File
File diff suppressed because it is too large. Load diff
+228
View File
@@ -0,0 +1,228 @@
`timescale 1ns / 1ps
// Basys 3 ASCII terminal.
// Keyboard (USB HID port) -> UART TX (USB-UART port)
// UART RX -> 80x30 text on VGA
//
// SW1:0 baud rate: 00 115200, 01 9600, 10 19200, 11 57600 (8N1)
// SW2 local echo
// SW3 received LF also does CR
// SW5:4 colour: 00 green, 01 amber, 10 white, 11 cyan
// SW6 Backspace sends DEL (7F) instead of BS (08)
// SW7 Enter sends CR LF instead of CR
// BTNC reset BTNU clear screen
// LED7:0 last byte received LED12 bell LED13 Caps Lock
// LED14 UART RX activity LED15 keyboard activity
// 7-seg last scan code (left), last byte sent (right)
module basys3_terminal #(
parameter FONT_FILE = "font.mem",
parameter CLK_HZ = 100_000_000
) (
input clk,
input btnC,
input btnU,
input [15:0] sw,
output [15:0] led,
output [6:0] seg,
output dp,
output [3:0] an,
output [3:0] vgaRed,
output [3:0] vgaGreen,
output [3:0] vgaBlue,
output Hsync,
output Vsync,
input RsRx,
output RsTx,
input PS2Clk,
input PS2Data
);
// ---------------------------------------------------------------- reset
reg [1:0] btn_sync;
reg [15:0] por = 16'd0;
reg rst = 1'b1;
always @(posedge clk) begin
btn_sync <= {btn_sync[0], btnC};
if (btn_sync[1]) por <= 16'd0;
else if (!por[15]) por <= por + 1'b1;
rst <= !por[15];
end
reg [7:0] sw_r;
reg [1:0] clr_sync;
always @(posedge clk) begin
sw_r <= sw[7:0];
clr_sync <= {clr_sync[0], btnU};
end
reg [13:0] baud_div;
always @(posedge clk)
case (sw_r[1:0])
2'b00: baud_div <= CLK_HZ / 115200;
2'b01: baud_div <= CLK_HZ / 9600;
2'b10: baud_div <= CLK_HZ / 19200;
2'b11: baud_div <= CLK_HZ / 57600;
endcase
// ------------------------------------------------------------- keyboard
wire [7:0] scan;
wire scan_valid;
wire [7:0] key;
wire key_valid;
wire caps;
ps2_rx kbd_rx (
.clk(clk), .rst(rst), .ps2_clk(PS2Clk), .ps2_data(PS2Data),
.code(scan), .valid(scan_valid)
);
ps2_keymap kbd_map (
.clk(clk), .rst(rst), .code(scan), .code_valid(scan_valid),
.bs_del(sw_r[6]), .enter_crlf(sw_r[7]),
.ascii(key), .ascii_valid(key_valid), .caps(caps)
);
// ------------------------------------------------------------- transmit
wire [7:0] kq;
wire kq_empty;
wire tx_busy;
reg tx_start;
reg [7:0] tx_byte;
fifo #(.W(8), .A(4)) key_fifo (
.clk(clk), .rst(rst), .din(key), .wr(key_valid),
.rd(tx_start), .dout(kq), .empty(kq_empty), .full()
);
always @(posedge clk) begin
tx_start <= 1'b0;
if (!kq_empty && !tx_busy && !tx_start && !rst) begin
tx_start <= 1'b1;
tx_byte <= kq;
end
end
uart_tx utx (
.clk(clk), .rst(rst), .div(baud_div), .data(tx_byte),
.start(tx_start), .tx(RsTx), .busy(tx_busy)
);
// -------------------------------------------------------------- receive
wire [7:0] rx_byte;
wire rx_valid;
uart_rx urx (
.clk(clk), .rst(rst), .div(baud_div), .rx(RsRx),
.data(rx_byte), .valid(rx_valid)
);
// Start-up banner, fed in like received text. Bytes are read from the
// high end of the string; the unused high bytes are zero and skipped.
localparam [8*160-1:0] BANNER = {
"Basys 3 ASCII Terminal 80x30\015\012",
"UART RX -> screen, keyboard -> UART TX\015\012",
"SW1:0 baud 00=115200 01=9600 10=19200 11=57600 SW2 echo\015\012\012"};
reg [7:0] ban_i;
wire [7:0] ban_c = BANNER[ban_i*8 +: 8];
// terminal input: received bytes, local echo, banner (in that priority)
reg echo_pend;
reg [7:0] echo_byte;
reg [7:0] tin;
reg tin_wr;
wire tin_full;
always @(posedge clk) begin
tin_wr <= 1'b0;
if (tx_start && sw_r[2]) begin
echo_pend <= 1'b1;
echo_byte <= kq;
end
if (rst) begin
echo_pend <= 1'b0;
ban_i <= 8'd159;
end else if (rx_valid) begin
tin <= rx_byte;
tin_wr <= 1'b1;
end else if (echo_pend && !tin_full) begin
tin <= echo_byte;
tin_wr <= 1'b1;
echo_pend <= tx_start && sw_r[2];
end else if (ban_i != 8'hFF && !tin_full && !tin_wr) begin
ban_i <= ban_i - 1'b1;
if (ban_c != 0) begin
tin <= ban_c;
tin_wr <= 1'b1;
end
end
end
wire [7:0] tq;
wire tq_empty;
wire tq_rd;
fifo #(.W(8), .A(6)) term_fifo (
.clk(clk), .rst(rst), .din(tin), .wr(tin_wr),
.rd(tq_rd), .dout(tq), .empty(tq_empty), .full(tin_full)
);
// ------------------------------------------------------------- terminal
wire we;
wire [11:0] waddr;
wire [8:0] wdata;
wire [4:0] top, cur_row;
wire [6:0] cur_col;
wire cur_vis;
wire bell;
term_ctrl term (
.clk(clk), .rst(rst), .in_byte(tq), .in_empty(tq_empty), .in_rd(tq_rd),
.lf_cr(sw_r[3]), .clear_req(clr_sync[1]),
.we(we), .waddr(waddr), .wdata(wdata),
.top(top), .row(cur_row), .col(cur_col), .cur_vis(cur_vis), .bell(bell)
);
wire [11:0] raddr;
wire [8:0] rdata;
char_ram screen (
.clk(clk), .we(we), .waddr(waddr), .wdata(wdata),
.raddr(raddr), .rdata(rdata)
);
reg [11:0] fg;
always @(posedge clk)
case (sw_r[5:4])
2'b00: fg <= 12'h3F3; // green
2'b01: fg <= 12'hFA0; // amber
2'b10: fg <= 12'hDDD; // white
2'b11: fg <= 12'h0EF; // cyan
endcase
text_display #(.FONT_FILE(FONT_FILE)) video (
.clk(clk), .rst(rst), .top(top), .cur_row(cur_row), .cur_col(cur_col),
.cur_vis(cur_vis), .fg(fg), .bg(12'h000),
.ram_addr(raddr), .ram_data(rdata),
.red(vgaRed), .green(vgaGreen), .blue(vgaBlue), .hsync(Hsync), .vsync(Vsync)
);
// ----------------------------------------------------- status displays
reg [7:0] last_rx;
reg [7:0] last_scan;
reg [7:0] last_tx;
reg [22:0] rx_led, kb_led, bell_led; // ~84 ms pulse stretchers
always @(posedge clk) begin
if (rx_valid) last_rx <= rx_byte;
if (scan_valid) last_scan <= scan;
if (tx_start) last_tx <= kq;
rx_led <= rx_valid ? 23'h7FFFFF : rx_led - (rx_led != 0);
kb_led <= scan_valid ? 23'h7FFFFF : kb_led - (kb_led != 0);
bell_led <= bell ? 23'h7FFFFF : bell_led - (bell_led != 0);
end
assign led = {kb_led != 0, rx_led != 0, caps, bell_led != 0, 4'b0000, last_rx};
assign dp = 1'b1;
sevenseg digits (.clk(clk), .value({last_scan, last_tx}), .seg(seg), .an(an));
endmodule
+36
View File
@@ -0,0 +1,36 @@
`timescale 1ns / 1ps
// Small synchronous first-word-fall-through FIFO (dout is valid while !empty).
module fifo #(
parameter W = 8,
parameter A = 4 // depth = 2**A
) (
input clk,
input rst,
input [W-1:0] din,
input wr,
input rd,
output [W-1:0] dout,
output empty,
output full
);
reg [W-1:0] mem [0:(1<<A)-1];
reg [A:0] wp, rp;
assign empty = wp == rp;
assign full = wp[A] != rp[A] && wp[A-1:0] == rp[A-1:0];
assign dout = mem[rp[A-1:0]];
always @(posedge clk)
if (wr && !full) mem[wp[A-1:0]] <= din;
always @(posedge clk) begin
if (rst) begin
wp <= 0;
rp <= 0;
end else begin
if (wr && !full) wp <= wp + 1'b1;
if (rd && !empty) rp <= rp + 1'b1;
end
end
endmodule
+196
View File
@@ -0,0 +1,196 @@
`timescale 1ns / 1ps
// USB keyboard input. The Basys 3's PIC24 USB host turns a USB keyboard into a
// PS/2 device (scan code set 2) on PS2Clk/PS2Data; this decodes that to ASCII.
module ps2_rx (
input clk,
input rst,
input ps2_clk,
input ps2_data,
output reg [7:0] code,
output reg valid
);
reg [2:0] cs = 3'b111, ds = 3'b111;
reg [5:0] fcnt;
reg fclk = 1'b1, fclk_d = 1'b1;
reg [10:0] sh;
reg [3:0] n;
reg [17:0] idle;
always @(posedge clk) begin
cs <= {cs[1:0], ps2_clk};
ds <= {ds[1:0], ps2_data};
// the clock only changes after 64 stable samples, which filters glitches
if (cs[2] == fclk)
fcnt <= 6'd0;
else begin
fcnt <= fcnt + 1'b1;
if (&fcnt) fclk <= cs[2];
end
fclk_d <= fclk;
end
wire fall = fclk_d & ~fclk;
wire [10:0] frame = {ds[2], sh[10:1]};
always @(posedge clk) begin
valid <= 1'b0;
if (rst) begin
n <= 4'd0;
idle <= 18'd0;
end else if (fall) begin
sh <= frame;
idle <= 18'd0;
if (n == 4'd10) begin
n <= 4'd0;
// start 0, stop 1, odd parity over data + parity bit
if (!frame[0] && frame[10] && ^frame[9:1]) begin
code <= frame[8:1];
valid <= 1'b1;
end
end else
n <= n + 1'b1;
end else if (n != 0) begin
idle <= idle + 1'b1;
if (&idle) n <= 4'd0; // ~2.6 ms without a clock: resync
end
end
endmodule
// Turns scan codes into ASCII bytes. Cursor and editing keys send VT100/xterm
// escape sequences; F1-F4 send ESC O P..S.
module ps2_keymap (
input clk,
input rst,
input [7:0] code,
input code_valid,
input bs_del, // Backspace sends DEL (7F) instead of BS (08)
input enter_crlf, // Enter sends CR LF instead of CR
output reg [7:0] ascii,
output reg ascii_valid,
output reg caps
);
localparam [7:0] ESC = 8'h1B;
reg e0, f0;
reg [2:0] skip;
reg lsh, rsh, lct, rct;
reg [7:0] s0, s1, s2, s3;
reg [2:0] cnt;
// {unshifted, shifted}
function [15:0] keymap(input [7:0] c);
case (c)
8'h0E: keymap = "`~"; 8'h16: keymap = "1!"; 8'h1E: keymap = "2@";
8'h26: keymap = "3#"; 8'h25: keymap = "4$"; 8'h2E: keymap = "5%";
8'h36: keymap = "6^"; 8'h3D: keymap = "7&"; 8'h3E: keymap = "8*";
8'h46: keymap = "9("; 8'h45: keymap = "0)"; 8'h4E: keymap = "-_";
8'h55: keymap = "=+"; 8'h0D: keymap = {8'h09, 8'h09};
8'h15: keymap = "qQ"; 8'h1D: keymap = "wW"; 8'h24: keymap = "eE";
8'h2D: keymap = "rR"; 8'h2C: keymap = "tT"; 8'h35: keymap = "yY";
8'h3C: keymap = "uU"; 8'h43: keymap = "iI"; 8'h44: keymap = "oO";
8'h4D: keymap = "pP"; 8'h54: keymap = "[{"; 8'h5B: keymap = "]}";
8'h5D: keymap = "\\|";
8'h1C: keymap = "aA"; 8'h1B: keymap = "sS"; 8'h23: keymap = "dD";
8'h2B: keymap = "fF"; 8'h34: keymap = "gG"; 8'h33: keymap = "hH";
8'h3B: keymap = "jJ"; 8'h42: keymap = "kK"; 8'h4B: keymap = "lL";
8'h4C: keymap = ";:"; 8'h52: keymap = "'\"";
8'h1A: keymap = "zZ"; 8'h22: keymap = "xX"; 8'h21: keymap = "cC";
8'h2A: keymap = "vV"; 8'h32: keymap = "bB"; 8'h31: keymap = "nN";
8'h3A: keymap = "mM"; 8'h41: keymap = ",<"; 8'h49: keymap = ".>";
8'h4A: keymap = "/?"; 8'h29: keymap = " "; 8'h76: keymap = {ESC, ESC};
// keypad, always as if Num Lock were on
8'h70: keymap = "00"; 8'h69: keymap = "11"; 8'h72: keymap = "22";
8'h7A: keymap = "33"; 8'h6B: keymap = "44"; 8'h73: keymap = "55";
8'h74: keymap = "66"; 8'h6C: keymap = "77"; 8'h75: keymap = "88";
8'h7D: keymap = "99"; 8'h71: keymap = ".."; 8'h7C: keymap = "**";
8'h7B: keymap = "--"; 8'h79: keymap = "++";
default: keymap = 16'h0000;
endcase
endfunction
wire shift = lsh | rsh;
wire ctrl = lct | rct;
wire [15:0] km = keymap(code);
wire letter = km[15:8] >= "a" && km[15:8] <= "z";
wire [7:0] ch = (letter ? shift ^ caps : shift) ? km[7:0] : km[15:8];
// bytes a key press produces
reg [2:0] k_len;
reg [7:0] k0, k1, k2, k3;
always @* begin
{k_len, k0, k1, k2, k3} = 35'd0;
if (e0) case (code)
8'h75: {k_len, k0, k1, k2} = {3'd3, ESC, "[A"}; // up
8'h72: {k_len, k0, k1, k2} = {3'd3, ESC, "[B"}; // down
8'h74: {k_len, k0, k1, k2} = {3'd3, ESC, "[C"}; // right
8'h6B: {k_len, k0, k1, k2} = {3'd3, ESC, "[D"}; // left
8'h6C: {k_len, k0, k1, k2} = {3'd3, ESC, "[H"}; // home
8'h69: {k_len, k0, k1, k2} = {3'd3, ESC, "[F"}; // end
8'h70: {k_len, k0, k1, k2, k3} = {3'd4, ESC, "[2~"}; // insert
8'h71: {k_len, k0, k1, k2, k3} = {3'd4, ESC, "[3~"}; // delete
8'h7D: {k_len, k0, k1, k2, k3} = {3'd4, ESC, "[5~"}; // page up
8'h7A: {k_len, k0, k1, k2, k3} = {3'd4, ESC, "[6~"}; // page down
8'h4A: {k_len, k0} = {3'd1, "/"}; // keypad /
8'h5A: {k_len, k0, k1} = enter_crlf ? {3'd2, 8'h0D, 8'h0A} : {3'd1, 8'h0D, 8'h00};
default: ;
endcase
else case (code)
8'h66: {k_len, k0} = {3'd1, bs_del ? 8'h7F : 8'h08};
8'h5A: {k_len, k0, k1} = enter_crlf ? {3'd2, 8'h0D, 8'h0A} : {3'd1, 8'h0D, 8'h00};
8'h05: {k_len, k0, k1, k2} = {3'd3, ESC, "OP"}; // F1
8'h06: {k_len, k0, k1, k2} = {3'd3, ESC, "OQ"}; // F2
8'h04: {k_len, k0, k1, k2} = {3'd3, ESC, "OR"}; // F3
8'h0C: {k_len, k0, k1, k2} = {3'd3, ESC, "OS"}; // F4
default:
if (ch != 0) begin
k_len = 3'd1;
if (!ctrl) k0 = ch;
else if (ch == " ") k0 = 8'h00;
else if (ch >= 8'h40) k0 = ch & 8'h1F; // ^A..^Z, ^[ ^\ ^] ^^ ^_
else k0 = ch;
end
endcase
end
always @(posedge clk) begin
ascii_valid <= 1'b0;
if (rst) begin
{e0, f0, lsh, rsh, lct, rct, caps} <= 7'd0;
skip <= 3'd0;
cnt <= 3'd0;
end else begin
if (cnt != 0) begin
ascii <= s0;
ascii_valid <= 1'b1;
{s0, s1, s2} <= {s1, s2, s3};
cnt <= cnt - 1'b1;
end
if (code_valid) begin
if (skip != 0)
skip <= skip - 1'b1;
else if (code == 8'hE1)
skip <= 3'd7; // Pause: E1 14 77 E1 F0 14 F0 77
else if (code == 8'hE0)
e0 <= 1'b1;
else if (code == 8'hF0)
f0 <= 1'b1;
else begin
e0 <= 1'b0;
f0 <= 1'b0;
if (code == 8'h12 && !e0) lsh <= !f0; // E0 12 / E0 59 are fake shifts
else if (code == 8'h59 && !e0) rsh <= !f0;
else if (code == 8'h14) begin
if (e0) rct <= !f0; else lct <= !f0;
end else if (code == 8'h58 && !e0) begin
if (!f0) caps <= !caps;
end else if (!f0 && k_len != 0) begin
{s0, s1, s2, s3} <= {k0, k1, k2, k3};
cnt <= k_len;
end
end
end
end
end
endmodule
+29
View File
@@ -0,0 +1,29 @@
`timescale 1ns / 1ps
// Four-digit hex display, digit 3 (left) = value[15:12]. Segments active low.
module sevenseg (
input clk,
input [15:0] value,
output reg [6:0] seg,
output reg [3:0] an
);
reg [17:0] cnt;
always @(posedge clk) cnt <= cnt + 1'b1;
wire [1:0] d = cnt[17:16];
wire [3:0] x = value[d*4 +: 4];
always @(posedge clk) begin
an <= ~(4'b0001 << d);
case (x) // gfedcba
4'h0: seg <= 7'b1000000; 4'h1: seg <= 7'b1111001;
4'h2: seg <= 7'b0100100; 4'h3: seg <= 7'b0110000;
4'h4: seg <= 7'b0011001; 4'h5: seg <= 7'b0010010;
4'h6: seg <= 7'b0000010; 4'h7: seg <= 7'b1111000;
4'h8: seg <= 7'b0000000; 4'h9: seg <= 7'b0010000;
4'hA: seg <= 7'b0001000; 4'hB: seg <= 7'b0000011;
4'hC: seg <= 7'b1000110; 4'hD: seg <= 7'b0100001;
4'hE: seg <= 7'b0000110; 4'hF: seg <= 7'b0001110;
endcase
end
endmodule
+242
View File
@@ -0,0 +1,242 @@
`timescale 1ns / 1ps
// Terminal engine: consumes received bytes and updates the 80x30 character
// buffer. Supports CR LF BS TAB BEL FF, deferred auto-wrap, hardware scrolling
// (the buffer is a ring of rows; `top` is the physical row shown first) and a
// VT100/ANSI subset:
// ESC [ n A/B/C/D cursor up/down/right/left ESC [ r;c H / f position
// ESC [ n d / G row / column absolute ESC [ n J / K erase
// ESC [ n m 0 normal, 7 reverse, 27 not reverse
// ESC [ ? 25 h/l show/hide cursor
// ESC c reset ESC D index ESC E next line ESC M reverse index ESC 7/8 save/restore
// Cell format in the buffer: {reverse, CP437 code}.
module term_ctrl (
input clk,
input rst,
input [7:0] in_byte,
input in_empty,
output reg in_rd,
input lf_cr, // LF also returns the carriage
input clear_req,
output reg we,
output reg [11:0] waddr,
output reg [8:0] wdata,
output reg [4:0] top,
output reg [4:0] row,
output reg [6:0] col,
output reg cur_vis,
output reg bell
);
localparam LAST_ROW = 5'd29, LAST_COL = 7'd79;
localparam S_IDLE = 2'd0, S_DISP = 2'd1, S_FILL = 2'd2;
localparam P_NORM = 2'd0, P_ESC = 2'd1, P_CSI = 2'd2;
reg [1:0] st, ret_st, ps;
reg [7:0] c;
reg pend; // a character went in the last column
reg rev;
reg [7:0] p0, p1;
reg [1:0] pidx;
reg priv;
reg [4:0] sv_row;
reg [6:0] sv_col;
reg [4:0] fr, er; // fill range, in screen coordinates
reg [6:0] fc, ec;
function [11:0] phys(input [4:0] r, input [6:0] cc, input [4:0] t);
reg [5:0] s;
reg [4:0] pr;
begin
s = r + t;
pr = (s >= 6'd30) ? s - 6'd30 : s;
phys = {1'b0, pr, 6'b0} + {3'b0, pr, 4'b0} + {5'b0, cc}; // pr*80 + cc
end
endfunction
// CSI parameter accumulate, saturating at 255
function [7:0] acc(input [7:0] p, input [7:0] d);
reg [11:0] v;
begin
v = p * 10 + (d - "0");
acc = v > 255 ? 8'd255 : v[7:0];
end
endfunction
wire [7:0] n0 = p0 == 0 ? 8'd1 : p0;
wire [8:0] row_dn = row + n0;
wire [8:0] col_rt = col + n0;
wire [4:0] row_p0 = p0 == 0 ? 5'd0 : p0 > 30 ? LAST_ROW : p0 - 1'b1;
wire [6:0] col_p0 = p0 == 0 ? 7'd0 : p0 > 80 ? LAST_COL : p0 - 1'b1;
wire [6:0] col_p1 = p1 == 0 ? 7'd0 : p1 > 80 ? LAST_COL : p1 - 1'b1;
task fill(input [4:0] r0, input [6:0] c0, input [4:0] r1, input [6:0] c1, input [1:0] rs);
begin
fr <= r0; fc <= c0; er <= r1; ec <= c1;
ret_st <= rs;
st <= S_FILL;
end
endtask
// line feed; scrolls by advancing `top` and blanking the new bottom row
task line_feed(input [1:0] rs);
begin
if (row == LAST_ROW) begin
top <= top == LAST_ROW ? 5'd0 : top + 1'b1;
fill(LAST_ROW, 0, LAST_ROW, LAST_COL, rs);
end else begin
row <= row + 1'b1;
st <= rs;
end
end
endtask
reg r_sgr;
always @(posedge clk) begin
in_rd <= 1'b0;
we <= 1'b0;
bell <= 1'b0;
if (rst) begin
ps <= P_NORM;
{top, row, col, sv_row, sv_col} <= 0;
{pend, rev} <= 2'b00;
cur_vis <= 1'b1;
fill(0, 0, LAST_ROW, LAST_COL, S_IDLE);
end else case (st)
S_IDLE:
if (clear_req) begin
{row, col, pend} <= 0;
fill(0, 0, LAST_ROW, LAST_COL, S_IDLE);
end else if (!in_empty && !in_rd) begin
c <= in_byte;
in_rd <= 1'b1;
st <= S_DISP;
end
S_FILL: begin
we <= 1'b1;
waddr <= phys(fr, fc, top);
wdata <= 9'h020;
if (fr == er && fc == ec)
st <= ret_st;
else if (fc == LAST_COL) begin
fc <= 7'd0;
fr <= fr + 1'b1;
end else
fc <= fc + 1'b1;
end
S_DISP: begin
st <= S_IDLE;
case (ps)
P_NORM:
if (c >= 8'h20 && c != 8'h7F) begin
if (pend) begin
// wrap first, then come back to print this byte
pend <= 1'b0;
col <= 7'd0;
line_feed(S_DISP);
end else begin
we <= 1'b1;
waddr <= phys(row, col, top);
wdata <= {rev, c};
if (col == LAST_COL) pend <= 1'b1;
else col <= col + 1'b1;
end
end else case (c)
8'h07: bell <= 1'b1;
8'h08: begin pend <= 1'b0; if (col != 0) col <= col - 1'b1; end
8'h09: begin pend <= 1'b0; col <= col >= 7'd72 ? LAST_COL : (col | 7'd7) + 1'b1; end
8'h0A, 8'h0B: begin
pend <= 1'b0;
if (lf_cr) col <= 7'd0;
line_feed(S_IDLE);
end
8'h0C: begin
{row, col, pend} <= 0;
fill(0, 0, LAST_ROW, LAST_COL, S_IDLE);
end
8'h0D: begin pend <= 1'b0; col <= 7'd0; end
8'h1B: ps <= P_ESC;
default: ;
endcase
P_ESC: begin
ps <= P_NORM;
case (c)
"[": begin
ps <= P_CSI;
{p0, p1, pidx, priv} <= 0;
end
"c": begin
{row, col, pend, rev} <= 0;
cur_vis <= 1'b1;
fill(0, 0, LAST_ROW, LAST_COL, S_IDLE);
end
"D": begin pend <= 1'b0; line_feed(S_IDLE); end
"E": begin pend <= 1'b0; col <= 7'd0; line_feed(S_IDLE); end
"M": begin pend <= 1'b0; if (row != 0) row <= row - 1'b1; end
"7": begin sv_row <= row; sv_col <= col; end
"8": begin pend <= 1'b0; row <= sv_row; col <= sv_col; end
8'h1B: ps <= P_ESC;
default: ;
endcase
end
P_CSI:
if (c >= "0" && c <= "9") begin
if (pidx == 0) p0 <= acc(p0, c);
else if (pidx == 1) p1 <= acc(p1, c);
end else if (c == ";") begin
if (pidx != 2'd3) pidx <= pidx + 1'b1;
end else if (c == "?") begin
priv <= 1'b1;
end else if (c == 8'h18 || c == 8'h1A) begin
ps <= P_NORM; // CAN / SUB abort the sequence
end else if (c >= 8'h40 && c <= 8'h7E) begin
ps <= P_NORM;
if (priv) begin
if (p0 == 25 && c == "h") cur_vis <= 1'b1;
if (p0 == 25 && c == "l") cur_vis <= 1'b0;
end else case (c)
"A": begin pend <= 1'b0; row <= row > n0 ? row - n0 : 5'd0; end
"B": begin pend <= 1'b0; row <= row_dn > LAST_ROW ? LAST_ROW : row_dn[4:0]; end
"C": begin pend <= 1'b0; col <= col_rt > LAST_COL ? LAST_COL : col_rt[6:0]; end
"D": begin pend <= 1'b0; col <= col > n0 ? col - n0 : 7'd0; end
"H", "f": begin pend <= 1'b0; row <= row_p0; col <= col_p1; end
"d": begin pend <= 1'b0; row <= row_p0; end
"G", "`": begin pend <= 1'b0; col <= col_p0; end
"J": case (p0)
8'd0: fill(row, col, LAST_ROW, LAST_COL, S_IDLE);
8'd1: fill(0, 0, row, col, S_IDLE);
8'd2, 8'd3: fill(0, 0, LAST_ROW, LAST_COL, S_IDLE);
default: ;
endcase
"K": case (p0)
8'd0: fill(row, col, row, LAST_COL, S_IDLE);
8'd1: fill(row, 0, row, col, S_IDLE);
8'd2: fill(row, 0, row, LAST_COL, S_IDLE);
default: ;
endcase
"m": begin
r_sgr = rev;
if (p0 == 0 || p0 == 27) r_sgr = 1'b0;
else if (p0 == 7) r_sgr = 1'b1;
if (pidx != 0) begin
if (p1 == 0 || p1 == 27) r_sgr = 1'b0;
else if (p1 == 7) r_sgr = 1'b1;
end
rev <= r_sgr;
end
default: ;
endcase
end
default: ps <= P_NORM;
endcase
end
default: st <= S_IDLE;
endcase
end
endmodule
+94
View File
@@ -0,0 +1,94 @@
`timescale 1ns / 1ps
// 640x480 @ 60 Hz VGA text display: 80x30 cells of 8x16 pixels.
// Runs on the 100 MHz clock with a 25 MHz pixel enable; the character RAM
// and font ROM reads finish well inside the four clocks of each pixel.
module text_display #(
parameter FONT_FILE = "font.mem"
) (
input clk,
input rst,
input [4:0] top, // physical row shown at the top of the screen
input [4:0] cur_row,
input [6:0] cur_col,
input cur_vis,
input [11:0] fg, // 4:4:4 RGB
input [11:0] bg,
output [11:0] ram_addr,
input [8:0] ram_data, // {reverse, code}, one clock after ram_addr
output reg [3:0] red,
output reg [3:0] green,
output reg [3:0] blue,
output reg hsync,
output reg vsync
);
localparam H_VIS = 640, H_FP = 16, H_SYNC = 96, H_TOTAL = 800;
localparam V_VIS = 480, V_FP = 10, V_SYNC = 2, V_TOTAL = 525;
reg [1:0] div = 2'd0;
reg [9:0] h, v;
reg [5:0] frame = 6'd0;
wire tick = div == 2'd3;
always @(posedge clk) begin
div <= rst ? 2'd0 : div + 1'b1;
if (rst) begin
h <= 0;
v <= 0;
end else if (tick) begin
if (h == H_TOTAL - 1) begin
h <= 0;
if (v == V_TOTAL - 1) begin
v <= 0;
frame <= frame + 1'b1;
end else
v <= v + 1'b1;
end else
h <= h + 1'b1;
end
end
// character cell under the beam
wire [6:0] tcol = h[9:3];
wire [4:0] trow = v[8:4];
wire [5:0] psum = trow + top;
wire [4:0] prow = psum >= 6'd30 ? psum - 6'd30 : psum;
assign ram_addr = {1'b0, prow, 6'b0} + {3'b0, prow, 4'b0} + {5'b0, tcol};
reg [7:0] font [0:4095];
reg [7:0] glyph;
initial $readmemh(FONT_FILE, font);
always @(posedge clk) glyph <= font[{ram_data[7:0], v[3:0]}];
wire visible = h < H_VIS && v < V_VIS;
wire cursor = cur_vis && frame[5] && tcol == cur_col && trow == cur_row;
wire on = glyph[~h[2:0]] ^ ram_data[8] ^ cursor;
always @(posedge clk) begin
if (tick) begin
{red, green, blue} <= !visible ? 12'h000 : on ? fg : bg;
hsync <= !(h >= H_VIS + H_FP && h < H_VIS + H_FP + H_SYNC);
vsync <= !(v >= V_VIS + V_FP && v < V_VIS + V_FP + V_SYNC);
end
end
endmodule
// 2400-cell character buffer: write port for the terminal, read port for video.
module char_ram (
input clk,
input we,
input [11:0] waddr,
input [8:0] wdata,
input [11:0] raddr,
output reg [8:0] rdata
);
(* ram_style = "block" *) reg [8:0] mem [0:4095];
integer i;
initial for (i = 0; i < 4096; i = i + 1) mem[i] = 9'h020;
always @(posedge clk) begin
if (we) mem[waddr] <= wdata;
rdata <= mem[raddr];
end
endmodule
+106
View File
@@ -0,0 +1,106 @@
`timescale 1ns / 1ps
// 8N1 UART receiver and transmitter. div = clock frequency / baud rate.
module uart_rx (
input clk,
input rst,
input [13:0] div,
input rx,
output reg [7:0] data,
output reg valid
);
localparam IDLE = 3'd0, START = 3'd1, DATA = 3'd2, STOP = 3'd3, BREAK = 3'd4;
reg [2:0] sync = 3'b111;
reg [2:0] st;
reg [13:0] cnt;
reg [2:0] bitn;
reg [7:0] sh;
wire rxs = sync[2];
always @(posedge clk) sync <= {sync[1:0], rx};
always @(posedge clk) begin
valid <= 1'b0;
if (rst) begin
st <= IDLE;
end else case (st)
IDLE:
if (!rxs) begin
st <= START;
cnt <= {1'b0, div[13:1]}; // sample mid-bit
end
START:
if (cnt == 0) begin
if (!rxs) begin
st <= DATA;
cnt <= div - 1'b1;
bitn <= 3'd0;
end else
st <= IDLE; // glitch, not a start bit
end else
cnt <= cnt - 1'b1;
DATA:
if (cnt == 0) begin
sh <= {rxs, sh[7:1]};
cnt <= div - 1'b1;
bitn <= bitn + 1'b1;
if (bitn == 3'd7) st <= STOP;
end else
cnt <= cnt - 1'b1;
STOP:
if (cnt == 0) begin
if (rxs) begin
data <= sh;
valid <= 1'b1;
st <= IDLE;
end else
st <= BREAK; // bad stop bit: drop it
end else
cnt <= cnt - 1'b1;
BREAK:
if (rxs) st <= IDLE; // wait for the line to go idle
default:
st <= IDLE;
endcase
end
endmodule
module uart_tx (
input clk,
input rst,
input [13:0] div,
input [7:0] data,
input start,
output reg tx = 1'b1,
output reg busy
);
reg [9:0] sh;
reg [3:0] n;
reg [13:0] cnt;
always @(posedge clk) begin
if (rst) begin
tx <= 1'b1;
busy <= 1'b0;
end else if (!busy) begin
if (start) begin
sh <= {1'b1, data, 1'b0};
n <= 4'd0;
cnt <= 14'd0;
busy <= 1'b1;
end
end else if (cnt == 0) begin
if (n == 4'd10)
busy <= 1'b0;
else begin
tx <= sh[0];
sh <= {1'b1, sh[9:1]};
n <= n + 1'b1;
cnt <= div - 1'b1;
end
end else
cnt <= cnt - 1'b1;
end
endmodule
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
# Build the bitstream; add "program" or "flash" to load it onto a connected board.
set -e
cd "$(dirname "$0")/.."
source scripts/vivado_env.sh
mkdir -p build
cd build
vivado -mode batch -nojournal -log build.log -source ../scripts/build.tcl
case "$1" in
program) vivado -mode batch -nojournal -log program.log -source ../scripts/program.tcl ;;
flash) vivado -mode batch -nojournal -log program.log -source ../scripts/program.tcl -tclargs flash ;;
esac
+23
View File
@@ -0,0 +1,23 @@
# Non-project Vivado build: vivado -mode batch -source scripts/build.tcl
set root [file normalize [file dirname [info script]]/..]
set out $root/build
file mkdir $out
read_verilog [glob $root/rtl/*.v]
read_mem $root/font/font.mem
read_xdc $root/constraints/basys3.xdc
synth_design -top basys3_terminal -part xc7a35tcpg236-1
opt_design
place_design
route_design
report_utilization -file $out/utilization.rpt
report_timing_summary -file $out/timing.rpt
write_bitstream -force $out/basys3_terminal.bit
write_cfgmem -force -format mcs -interface SPIx4 -size 4 \
-loadbit "up 0x0 $out/basys3_terminal.bit" $out/basys3_terminal.mcs
set wns [get_property SLACK [get_timing_paths -max_paths 1 -setup]]
puts "Worst setup slack: $wns ns"
if {$wns < 0} { error "timing not met" }
+31
View File
@@ -0,0 +1,31 @@
# Program the Basys 3 over its USB-JTAG port.
# vivado -mode batch -source scripts/program.tcl (SRAM, lost at power-off)
# vivado -mode batch -source scripts/program.tcl -tclargs flash (QSPI flash, survives power-off)
set root [file normalize [file dirname [info script]]/..]
set mode [expr {[llength $argv] > 0 ? [lindex $argv 0] : "sram"}]
open_hw_manager
connect_hw_server
open_hw_target
set dev [lindex [get_hw_devices xc7a35t*] 0]
current_hw_device $dev
refresh_hw_device -update_hw_probes false $dev
if {$mode eq "flash"} {
create_hw_cfgmem -hw_device $dev [lindex [get_cfgmem_parts {s25fl032p-spi-x1_x2_x4}] 0]
set mem [get_property PROGRAM.HW_CFGMEM $dev]
set_property PROGRAM.FILES [list $root/build/basys3_terminal.mcs] $mem
set_property PROGRAM.ADDRESS_RANGE use_file $mem
set_property PROGRAM.ERASE 1 $mem
set_property PROGRAM.CFG_PROGRAM 1 $mem
set_property PROGRAM.VERIFY 1 $mem
create_hw_bitstream -hw_device $dev [get_property PROGRAM.HW_CFGMEM_BITFILE $dev]
program_hw_devices $dev
program_hw_cfgmem -hw_cfgmem $mem
puts "Flash programmed; set JP1 to QSPI and power-cycle (or press PROG)."
} else {
set_property PROGRAM.FILE $root/build/basys3_terminal.bit $dev
program_hw_devices $dev
puts "FPGA configured."
}
close_hw_manager
Executable
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
# Run the testbench in Vivado's simulator; output lands in sim/work.
set -e
cd "$(dirname "$0")/.."
ROOT=$(pwd)
source scripts/vivado_env.sh
mkdir -p sim/work
cd sim/work
xvlog -d FONT_FILE="\"$ROOT/font/font.mem\"" "$ROOT"/rtl/*.v "$ROOT"/sim/tb_terminal.v
xelab -debug off tb_terminal -s tb_terminal
xsim tb_terminal -R
if command -v python3 >/dev/null; then
python3 -c "from PIL import Image; Image.open('frame.ppm').save('frame.png')" && echo "wrote sim/work/frame.png"
fi
+14
View File
@@ -0,0 +1,14 @@
# Sourced by build.sh and sim.sh: sets up Vivado's environment.
# VIVADO picks the install; default is the newest in ~/vivado/<version>/Vivado.
VIVADO=${VIVADO:-$(ls -d "$HOME"/vivado/*/Vivado 2>/dev/null | sort -V | tail -1)}
source "$VIVADO/settings64.sh"
# Vivado still links against ncurses 5; newer distros only ship 6, which works.
COMPAT_LIB="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/build/compat-lib"
mkdir -p "$COMPAT_LIB"
for l in ncurses tinfo; do
if ! ldconfig -p | grep -q "lib$l.so.5" && [ -e /usr/lib/x86_64-linux-gnu/lib$l.so.6 ]; then
ln -sf /usr/lib/x86_64-linux-gnu/lib$l.so.6 "$COMPAT_LIB/lib$l.so.5"
fi
done
export LD_LIBRARY_PATH="$COMPAT_LIB${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
+161
View File
@@ -0,0 +1,161 @@
`timescale 1ns / 1ps
// Whole-design test: keystrokes on PS/2 -> UART TX bytes, UART RX text ->
// screen buffer (printed as text) and one VGA frame (written as frame.ppm).
module tb_terminal;
reg clk = 0;
always #5 clk = ~clk;
reg [15:0] sw = 16'h0004; // 115200 baud, local echo on
reg btnC = 0, btnU = 0;
reg rsrx = 1;
reg ps2c = 1, ps2d = 1;
wire rstx, hs, vs;
wire [3:0] r, g, b;
wire [15:0] led;
basys3_terminal #(.FONT_FILE(`FONT_FILE)) dut (
.clk(clk), .btnC(btnC), .btnU(btnU), .sw(sw), .led(led), .seg(), .dp(), .an(),
.vgaRed(r), .vgaGreen(g), .vgaBlue(b), .Hsync(hs), .Vsync(vs),
.RsRx(rsrx), .RsTx(rstx), .PS2Clk(ps2c), .PS2Data(ps2d)
);
localparam BIT_NS = 1_000_000_000 / 115200;
task uart_send(input [7:0] d);
integer i;
begin
rsrx = 0; #(BIT_NS);
for (i = 0; i < 8; i = i + 1) begin rsrx = d[i]; #(BIT_NS); end
rsrx = 1; #(BIT_NS);
end
endtask
task uart_str(input [8*160-1:0] s);
integer i;
begin
for (i = 159; i >= 0; i = i - 1)
if (s[i*8 +: 8] != 0) uart_send(s[i*8 +: 8]);
end
endtask
task ps2_send(input [7:0] d);
integer i;
reg [10:0] f;
begin
f = {1'b1, ~^d, d, 1'b0};
for (i = 0; i < 11; i = i + 1) begin
ps2d = f[i]; #10000;
ps2c = 0; #20000;
ps2c = 1; #10000;
end
#100000;
end
endtask
// decode what the terminal transmits
reg [8*16-1:0] tx_log = 0;
integer tx_n = 0;
initial forever begin : txmon
integer i;
reg [7:0] d;
@(negedge rstx);
#(BIT_NS / 2);
for (i = 0; i < 8; i = i + 1) begin #(BIT_NS); d[i] = rstx; end
#(BIT_NS);
if (!rstx) $display("TX framing error");
$display("%t TX %02h", $time, d);
tx_log = {tx_log[8*15-1:0], d};
tx_n = tx_n + 1;
end
task dump_screen;
integer rr, cc, p;
reg [8*80-1:0] line;
reg [8:0] cv;
begin
$display("+--------------------------------------------------------------------------------+");
for (rr = 0; rr < 30; rr = rr + 1) begin
p = (rr + dut.term.top) % 30;
for (cc = 0; cc < 80; cc = cc + 1) begin
cv = dut.screen.mem[p * 80 + cc];
line[(79 - cc) * 8 +: 8] = cv[8] ? (cv[7:0] == " " ? "#" : cv[7:0]) : cv[7:0];
end
$display("|%s| %0d", line, rr);
end
$display("+--------------------------------------------------------------------------------+");
$display("cursor row %0d col %0d, top %0d", dut.term.row, dut.term.col, dut.term.top);
end
endtask
// capture one frame
reg [11:0] fb [0:640*480-1];
reg cap = 0, smp = 0;
reg [9:0] hh, vv;
always @(posedge clk) if (dut.video.tick) begin hh <= dut.video.h; vv <= dut.video.v; smp <= cap; end
always @(negedge clk) if (smp && hh < 640 && vv < 480) begin
fb[vv * 640 + hh] = {r, g, b};
smp = 0;
end
task capture_frame;
integer fd, i;
begin
@(negedge vs);
@(posedge vs);
cap = 1;
@(negedge vs);
cap = 0;
fd = $fopen("frame.ppm", "w");
$fwrite(fd, "P3\n640 480\n15\n");
for (i = 0; i < 640 * 480; i = i + 1)
$fwrite(fd, "%0d %0d %0d\n", fb[i][11:8], fb[i][7:4], fb[i][3:0]);
$fclose(fd);
$display("wrote frame.ppm");
end
endtask
// check VGA timing on the outputs
realtime t_hs = 0, t_vs = 0;
always @(negedge hs) begin
if (t_hs != 0 && ($realtime - t_hs) != 32000) $display("HSYNC period %0t", $realtime - t_hs);
t_hs = $realtime;
end
always @(negedge vs) begin
if (t_vs != 0 && ($realtime - t_vs) != 16800000) $display("VSYNC period %0t", $realtime - t_vs);
t_vs = $realtime;
end
integer k;
initial begin
#2_000_000; // reset, clear, banner
// keyboard: a, shift+b, Enter, up arrow, ctrl+c
ps2_send(8'h1C); ps2_send(8'hF0); ps2_send(8'h1C);
ps2_send(8'h12); ps2_send(8'h32); ps2_send(8'hF0); ps2_send(8'h32); ps2_send(8'hF0); ps2_send(8'h12);
ps2_send(8'h5A); ps2_send(8'hF0); ps2_send(8'h5A);
ps2_send(8'hE0); ps2_send(8'h75); ps2_send(8'hE0); ps2_send(8'hF0); ps2_send(8'h75);
ps2_send(8'h14); ps2_send(8'h21); ps2_send(8'hF0); ps2_send(8'h21); ps2_send(8'hF0); ps2_send(8'h14);
#200_000;
if (tx_n == 7 && tx_log[8*7-1:0] == {8'h61, 8'h42, 8'h0D, 8'h1B, "[A", 8'h03})
$display("PASS keyboard -> UART: 61 42 0D 1B 5B 41 03");
else
$display("FAIL keyboard -> UART: %0d bytes %h", tx_n, tx_log);
uart_str("\033[2J\033[HHello, world!\015\012");
uart_str("tab\tstop\tX\015\012abc\010Z \033[7m reverse \033[0m normal\015\012");
uart_str("erase-to-end: KEEP\033[4DXXXX\033[4D\033[K\015\012");
for (k = 0; k < 20; k = k + 1) begin
uart_str("line ");
uart_send("0" + k / 10);
uart_send("0" + k % 10);
uart_str("\015\012");
end
uart_str("\033[12;30H\033[7m+------------------+\033[13;30H| ANSI positioning |\033[14;30H+------------------+\033[0m");
uart_str("\033[30;1H\033[?25lwrap test: 0123456789012345678901234567890123456789012345678901234567890123456789");
#100_000;
dump_screen;
capture_frame;
$finish;
end
endmodule
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Convert a Linux console PSF font (8x16) into a CP437-ordered font ROM.
Output is a $readmemh file with 4096 lines: byte (code*16 + row), MSB = leftmost pixel.
usage: psf2mem.py [font.psf.gz[,fallback.psf.gz...]] [out.mem] [preview.png]
Glyphs missing from the first font are taken from the fallbacks in order.
"""
import gzip
import struct
import sys
CP437_LOW = ("\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼")
DEFAULT_FONTS = ",".join("/usr/share/consolefonts/%s.psf.gz" % f for f in
("Uni2-VGA16", "FullGreek-VGA16", "Vietnamese-TerminusBoldVGA16"))
# Fonts often carry the triangle pointers under their newer code points.
CP437_ALT = {"►": "▶", "◄": "◀"}
def cp437(code):
if code < 0x20:
return CP437_LOW[code]
if code == 0x7F:
return "⌂"
return bytes([code]).decode("cp437")
def load_psf(path):
raw = gzip.open(path).read() if path.endswith(".gz") else open(path, "rb").read()
if raw[:2] == b"\x36\x04":
mode, charsize = raw[2], raw[3]
count = 512 if mode & 1 else 256
width, height, hdr = 8, charsize, 4
has_table = bool(mode & 6)
glyphs = [raw[hdr + i * charsize: hdr + (i + 1) * charsize] for i in range(count)]
table = {}
if has_table:
pos, g = hdr + count * charsize, 0
while g < count and pos + 1 < len(raw):
(u,) = struct.unpack_from("<H", raw, pos)
pos += 2
if u == 0xFFFF:
g += 1
elif u != 0xFFFE:
table.setdefault(chr(u), g)
return glyphs, table, width, height
if raw[:4] == b"\x72\xb5\x4a\x86":
_, hdr, flags, count, charsize, height, width = struct.unpack_from("<7I", raw, 4)
glyphs = [raw[hdr + i * charsize: hdr + (i + 1) * charsize] for i in range(count)]
table = {}
if flags & 1:
data = raw[hdr + count * charsize:]
for g, entry in enumerate(data.split(b"\xff")[:count]):
for seq in entry.split(b"\xfe")[:1]:
for ch in seq.decode("utf-8", "ignore"):
table.setdefault(ch, g)
return glyphs, table, width, height
raise SystemExit("not a PSF font: " + path)
def main():
src = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] else DEFAULT_FONTS
out = sys.argv[2] if len(sys.argv) > 2 else "font.mem"
fonts = []
for path in src.split(","):
glyphs, table, width, height = load_psf(path)
if width != 8 or height != 16:
raise SystemExit(f"{path}: need an 8x16 font, got {width}x{height}")
fonts.append((glyphs, table))
missing = []
rom = []
for code in range(256):
ch = cp437(code)
glyph = None
if code not in (0, 0x20):
for glyphs, table in fonts:
g = table.get(ch, code if not table else None)
if g is None and ch in CP437_ALT:
g = table.get(CP437_ALT[ch])
if g is not None:
glyph = glyphs[g][:16]
break
if glyph is None:
missing.append(f"{code:02X}")
rom.extend(glyph or [0] * 16)
with open(out, "w") as f:
f.write("// CP437 order, 256 glyphs x 16 rows, from: %s\n"
% ", ".join(p.split("/")[-1] for p in src.split(",")))
for b in rom:
f.write(f"{b:02x}\n")
print(f"wrote {out}; glyphs missing: {' '.join(missing) or 'none'}")
if len(sys.argv) > 3:
from PIL import Image
img = Image.new("1", (32 * 9, 8 * 17), 0)
for code in range(256):
ox, oy = (code % 32) * 9, (code // 32) * 17
for r in range(16):
for c in range(8):
if rom[code * 16 + r] & (0x80 >> c):
img.putpixel((ox + c, oy + r), 1)
img.save(sys.argv[3])
if __name__ == "__main__":
main()