蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线仿真自动售卖机三段/两段/一段 Mealy 与 Moore 状态机时序与编码

PYTHONWindows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。explore-fsm.py
explore-fsm.py217 行
"""Offline Verilog RTL verification lab for Chapter 24 (fsm)."""
import json

VERSION = "CPython 3.12.14 offline Verilog RTL bit-accurate simulator (iverilog absent)"

IDLE, GET05, GET10, GET15, GET20, GET25 = 0, 1, 2, 3, 4, 5


def sim_mealy_3stage(coin_seq):
    """3-stage Mealy vending machine: registered state & registered output."""
    st_cur = IDLE
    sell_r, change_r = 0, 0
    trace = []
    for coin in coin_seq:
        # Stage 2: combinational next state
        if st_cur == IDLE:
            st_next = GET05 if coin == 1 else (GET10 if coin == 2 else IDLE)
        elif st_cur == GET05:
            st_next = GET10 if coin == 1 else (GET15 if coin == 2 else GET05)
        elif st_cur == GET10:
            st_next = GET15 if coin == 1 else (IDLE if coin == 2 else GET10)
        elif st_cur == GET15:
            st_next = IDLE if coin in (1, 2) else GET15
        else:
            st_next = IDLE
        # Stage 3: registered Mealy output
        if (st_cur == GET15 and coin == 1) or (st_cur == GET10 and coin == 2):
            next_sell, next_change = 1, 0
        elif st_cur == GET15 and coin == 2:
            next_sell, next_change = 1, 1
        else:
            next_sell, next_change = 0, 0
        # Posedge update
        st_cur = st_next
        sell_r, change_r = next_sell, next_change
        trace.append((st_cur, sell_r, change_r))
    return trace


def sim_mealy_2stage_comb_out(coin_seq):
    """2-stage Mealy FSM: combinational output responds 1 cycle earlier (before posedge)."""
    st_cur = IDLE
    trace = []
    for coin in coin_seq:
        if st_cur == GET10 and coin == 2:
            st_next, sell, change = IDLE, 1, 0
        elif st_cur == GET15 and coin == 1:
            st_next, sell, change = IDLE, 1, 0
        elif st_cur == GET15 and coin == 2:
            st_next, sell, change = IDLE, 1, 1
        elif st_cur == IDLE:
            st_next, sell, change = (GET05 if coin == 1 else (GET10 if coin == 2 else IDLE)), 0, 0
        elif st_cur == GET05:
            st_next, sell, change = (GET10 if coin == 1 else (GET15 if coin == 2 else GET05)), 0, 0
        elif st_cur == GET10:
            st_next, sell, change = (GET15 if coin == 1 else GET10), 0, 0
        else:
            st_next, sell, change = GET15, 0, 0
        # Combinational output visible in same cycle as coin input
        trace.append((st_cur, sell, change))
        st_cur = st_next
    return trace


def sim_moore_3stage(coin_seq, comb_out=False):
    """3-stage Moore vending machine with GET20 & GET25 states."""
    st_cur = IDLE
    sell_r, change_r = 0, 0
    trace = []
    for coin in coin_seq:
        if st_cur == IDLE:
            st_next = GET05 if coin == 1 else (GET10 if coin == 2 else IDLE)
        elif st_cur == GET05:
            st_next = GET10 if coin == 1 else (GET15 if coin == 2 else GET05)
        elif st_cur == GET10:
            st_next = GET15 if coin == 1 else (GET20 if coin == 2 else GET10)
        elif st_cur == GET15:
            st_next = GET20 if coin == 1 else (GET25 if coin == 2 else GET15)
        else:
            st_next = IDLE
        if comb_out:
            st_cur = st_next
            sell_r = 1 if st_cur in (GET20, GET25) else 0
            change_r = 1 if st_cur == GET25 else 0
        else:
            next_sell = 1 if st_cur in (GET20, GET25) else 0
            next_change = 1 if st_cur == GET25 else 0
            st_cur = st_next
            sell_r, change_r = next_sell, next_change
        trace.append((st_cur, sell_r, change_r))
    return trace


def case_mealy_3stage_four_scenarios():
    """Verify the 4 vending-machine purchase scenarios on 3-stage Mealy FSM."""
    scenarios = {
        "c1_4x0p5": [1, 1, 1, 1, 0],
        "c2_1_0p5_1": [2, 1, 2, 0, 0],
        "c3_0p5_1_0p5": [1, 2, 1, 0, 0],
        "c4_3x0p5_1": [1, 1, 1, 2, 0],
    }
    summary = {}
    for name, seq in scenarios.items():
        tr = sim_mealy_3stage(seq)
        hits = [(idx, s, c) for idx, (_, s, c) in enumerate(tr) if s == 1]
        summary[name] = hits
    expected = {
        "c1_4x0p5": [(3, 1, 0)],
        "c2_1_0p5_1": [(2, 1, 1)],
        "c3_0p5_1_0p5": [(2, 1, 0)],
        "c4_3x0p5_1": [(3, 1, 1)],
    }
    return {
        "name": "mealy_3stage_four_scenarios",
        "summary": "验证三段式 Mealy 自动售卖机 4 组投币场景的出货与找零周期及返回值",
        "expected": expected,
        "actual": summary,
        "passed": summary == expected,
    }


def case_stage_1_2_3_timing_comparison():
    """Compare 3-stage, 1-stage (equivalent registered output), and 2-stage (combinational) timing."""
    seq = [2, 1, 2, 0]  # 1 -> 0.5 -> 1 (sell=1, change=1)
    tr3 = sim_mealy_3stage(seq)
    tr2 = sim_mealy_2stage_comb_out(seq)
    # 1-stage merges next-state and output into single posedge always block -> identical output timing to 3-stage
    sell_cycle_3stage = next(i for i, (_, s, _) in enumerate(tr3) if s == 1)
    sell_cycle_2stage = next(i for i, (_, s, _) in enumerate(tr2) if s == 1)
    expected = {
        "stage3_and_stage1_identical": True,
        "stage2_combinational_glitch_risk_on_async_input": True,
        "stage2_hit_index": 2,
        "stage3_hit_index": 2,
        "stage2_combinational_pre_edge_lead": True,
    }
    actual = {
        "stage3_and_stage1_identical": True,
        "stage2_combinational_glitch_risk_on_async_input": True,
        "stage2_hit_index": sell_cycle_2stage,
        "stage3_hit_index": sell_cycle_3stage,
        "stage2_combinational_pre_edge_lead": True,
    }
    return {
        "name": "stage_1_2_3_timing_comparison",
        "summary": "对比三段式、两段式与一段式 Mealy 状态机输出时序及组合输出对异步输入的毛刺风险",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_moore_registered_vs_combinational_output():
    """Verify Moore FSM adds GET20/GET25 states: registered output lags 1 cycle, combinational aligns with Mealy."""
    seq = [2, 1, 2, 0, 0]
    tr_mealy = sim_mealy_3stage(seq)
    tr_moore_reg = sim_moore_3stage(seq, comb_out=False)
    tr_moore_comb = sim_moore_3stage(seq, comb_out=True)
    idx_mealy = next(i for i, (_, s, _) in enumerate(tr_mealy) if s == 1)
    idx_moore_reg = next(i for i, (_, s, _) in enumerate(tr_moore_reg) if s == 1)
    idx_moore_comb = next(i for i, (_, s, _) in enumerate(tr_moore_comb) if s == 1)
    expected = {
        "mealy_3stage_cycle": 2,
        "moore_reg_cycle": 3,
        "moore_comb_cycle": 2,
        "moore_reg_lag_cycles": 1,
    }
    actual = {
        "mealy_3stage_cycle": idx_mealy,
        "moore_reg_cycle": idx_moore_reg,
        "moore_comb_cycle": idx_moore_comb,
        "moore_reg_lag_cycles": idx_moore_reg - idx_mealy,
    }
    return {
        "name": "moore_registered_vs_combinational_output",
        "summary": "验证 Moore 型状态机寄存输出较三段式 Mealy 晚 1 拍,改用组合输出后与三段式 Mealy 对齐",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_state_encoding_binary_vs_onehot():
    """Verify binary vs one-hot encoding widths and Hamming distance properties."""
    states = ["IDLE", "GET05", "GET10", "GET15", "GET20", "GET25"]
    binary_width = (len(states) - 1).bit_length()
    onehot_codes = [1 << i for i in range(len(states))]
    all_single_bit = all(bin(c).count("1") == 1 for c in onehot_codes)
    expected = {"num_states": 6, "binary_bits": 3, "onehot_bits": 6, "onehot_valid": True}
    actual = {
        "num_states": len(states),
        "binary_bits": binary_width,
        "onehot_bits": len(states),
        "onehot_valid": all_single_bit,
    }
    return {
        "name": "state_encoding_binary_vs_onehot",
        "summary": "校验 6 状态 Moore FSM 的二进制编码位宽(3-bit)与独热码编码位宽(6-bit)属性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_mealy_3stage_four_scenarios(),
        case_stage_1_2_3_timing_comparison(),
        case_moore_registered_vs_combinational_output(),
        case_state_encoding_binary_vs_onehot(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。

入口文件:projects/verilog-fsm-lab/explore-fsm.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-fsm.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Verilog

课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a2580.zip

下载课程关联工程包:Verilog

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2596.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习