# VexHDL Design Examples

These illustrative designs connect hardware interfaces, state transitions, and
verification cases. The FIFO is an executable software reference model; the
UART and bus examples explain the corresponding hardware protocols.

---

## 1. FIFO (First-In, First-Out) Buffer

This is a language-independent reference model for a synchronous FIFO. It is **not** VexHDL syntax or a synthesis-ready circuit. The FIFO accepts requests from the occupancy at the start of the clock edge:

| Starting state | Write and read both requested | Accepted transfers |
| --- | --- | --- |
| Empty | Both | Write only; there is no same-cycle bypass |
| Partially occupied | Both | One write and one read |
| Full | Both | Read only; the newly freed slot is not reused on that edge |

Reset takes priority over requests and clears the pointers and count; it does not have to clear the stored bits. Data returned by a read is valid only when that read is accepted. Each pointer wraps explicitly at `depth - 1`, including non-powers of two. A hardware implementation needs `max(1, ceil(log2(depth)))` pointer bits and `max(1, ceil(log2(depth + 1)))` count bits for `depth >= 1`. The one-bit minimum avoids zero-width hardware fields, including at depth 1.

```python [fifo-model.py]
class Fifo:
    def __init__(self, depth):
        if depth < 1:
            raise ValueError("depth must be at least 1")
        self.depth = depth
        self.mem = [None] * depth
        self.wr_ptr = self.rd_ptr = self.count = 0

    def step(self, reset, wr_en, rd_en, data):
        """Advance one edge; return (write accepted, read accepted, read data)."""
        if reset:
            self.wr_ptr = self.rd_ptr = self.count = 0
            return False, False, None

        write = bool(wr_en and self.count < self.depth)
        read = bool(rd_en and self.count > 0)
        value = self.mem[self.rd_ptr] if read else None
        if write:
            self.mem[self.wr_ptr] = data
            self.wr_ptr = (self.wr_ptr + 1) % self.depth
        if read:
            self.rd_ptr = (self.rd_ptr + 1) % self.depth
        self.count += int(write) - int(read)
        return write, read, value

    @property
    def empty(self):
        return self.count == 0

    @property
    def full(self):
        return self.count == self.depth
```

For an actual circuit, decide whether memory supports this read behavior and what it returns during an unaccepted read; these choices depend on the memory primitive. Do not expose the stale contents as valid data when `empty` is true. The model does not establish VexHDL parser, simulator, synthesis, or device support. The documentation's `test:fifo-model` compares this exact model against a separate queue across depths 1, 2, 16, 17, and 32, including reset, full and empty simultaneous requests, and pointer wrap.

---

## 2. UART TX Controller

This illustrative transmitter sends an 8-bit word least-significant bit first,
with one start bit, one stop bit and no parity. A request is accepted only in
`IDLE`; requests while active are ignored. Keep `tx_data` stable at the accepting
clock edge, and use `tx_done`/`tx_active` in the producer protocol.

The integer divider requires `BAUD_RATE > 0` and
`1 <= CLK_FREQ / BAUD_RATE <= 65536` for the shown 16-bit counter. Actual baud
is `CLK_FREQ / CLKS_PER_BIT`, so check its relative error against the receiver's
tolerance. For the defaults, the divider is 434, not an exact fractional baud
generator. Reset aborts an in-flight frame and restores idle-high output.

This is a state-machine sketch, not a device-qualified UART core:

```vexhdl
export enum TxState {
    IDLE,
    START_BIT,
    DATA_BITS,
    STOP_BIT,
}

export graph uart_tx #(
    CLK_FREQ: Param<U32> = 50_000_000,
    BAUD_RATE: Param<U32> = 115_200,
)(
    clk: In,
    rst: In,
    tx_start: In,
    tx_data: In<U<8>>,
    tx_active: Out,
    tx_out: Out,
    tx_done: Out,
) {
    param CLKS_PER_BIT: U32 = CLK_FREQ / BAUD_RATE;

    let! state: TxState = TxState::IDLE;
    let! clk_count: U<16> = 0;
    let! bit_index: U<3> = 0;
    let! data_reg: U<8> = 0;
    let! r_tx_out: Bool = true;
    let! r_active: Bool = false;
    let! r_done: Bool = false;

    on(PosEdge(clk), PosEdge(rst)) {
        if rst {
            state     <- TxState::IDLE;
            clk_count <- 0;
            bit_index <- 0;
            r_tx_out  <- true;
            r_active  <- false;
            r_done    <- false;
        } else {
            match (state) {
                TxState::IDLE => {
                    r_tx_out <- true;
                    r_done   <- false;
                    clk_count <- 0;
                    bit_index <- 0;

                    if tx_start {
                        data_reg <- tx_data;
                        r_active <- true;
                        state    <- TxState::START_BIT;
                    } else {
                        r_active <- false;
                    }
                }
                TxState::START_BIT => {
                    r_tx_out <- false; // Start bit is low

                    if (clk_count < CLKS_PER_BIT - 1) {
                        clk_count <- clk_count + 1;
                    } else {
                        clk_count <- 0;
                        state     <- TxState::DATA_BITS;
                    }
                }
                TxState::DATA_BITS => {
                    r_tx_out <- data_reg[bit_index];

                    if (clk_count < CLKS_PER_BIT - 1) {
                        clk_count <- clk_count + 1;
                    } else {
                        clk_count <- 0;
                        if (bit_index < 7) {
                            bit_index <- bit_index + 1;
                        } else {
                            bit_index <- 0;
                            state     <- TxState::STOP_BIT;
                        }
                    }
                }
                TxState::STOP_BIT => {
                    r_tx_out <- true; // Stop bit is high

                    if (clk_count < CLKS_PER_BIT - 1) {
                        clk_count <- clk_count + 1;
                    } else {
                        clk_count <- 0;
                        r_done    <- true;
                        r_active  <- false;
                        state     <- TxState::IDLE;
                    }
                }
            }
        }
    }

    tx_out    = r_tx_out;
    tx_active = r_active;
    tx_done   = r_done;
}
```

---

## 3. AXI-Lite Slave Interface

A register-bank design must preserve independent channel handshakes. The old
example wrote on simultaneous `AWVALID`/`WVALID` and could overwrite a stalled
response; that is not a correct reusable peripheral.

A transfer occurs only at an edge where a channel's `VALID` and `READY` are
both asserted. Address and data can arrive in either order. A response must
remain valid, with stable payload, until accepted. These requirements come
from the [Arm AMBA AXI specification, A3 and B1](https://developer.arm.com/-/media/Arm%20Developer%20Community/PDF/IHI0022H_amba_axi_protocol_spec.pdf).

For a conservative one-outstanding-write design, use separate address and data
holding slots. Capture each only on its handshake. Once both are full and the
response slot is free, perform one write, consume the slots and publish the
response. Stop accepting new work when storage is occupied. Apply byte write
strobes, validate address decoding and return the appropriate response status.
For reads, retain the selected data and response while `RVALID && !RREADY`.

This is a proposed architecture to implement in the chosen HDL, not a tested
VexHDL module. Its acceptance tests should include:

| Scenario | Expected result |
| --- | --- |
| Address arrives before data, and vice versa | Exactly one write after both accepted |
| Response consumer stalls | Stable response; no lost or repeated transaction |
| Partial byte strobe | Only selected bytes change |
| Invalid register address | Defined error response; unrelated registers unchanged |
| Reset during a transaction | State follows the specified reset/recovery protocol |

Retain waveforms and assertions for these cases before synthesis. A successful
compile does not establish bus-protocol correctness.
