6.3 Verilog 状态机
深入剖析 Moore 与 Mealy 两类有限状态机(FSM)原理,以 2 元饮料自动售卖机为实例完整实现并对比三段式、两段式、一段式 Mealy 状态机及寄存/组合输出 Moore 状态机的时序、毛刺与可维护性。
学完这一章,你能够
- 深入剖析 Moore 与 Mealy 两类有限状态机(FSM)原理,以 2 元饮料自动售卖机为实例完整实现并对比三段式、两段式、一段式 Mealy 状态机及寄存/组合输出 Moore 状态机的时序、毛刺与可维护性。
有限状态机分类:Moore 型与 Mealy 型
有限状态机(Finite-State Machine,FSM)以有限个离散状态及状态间的转移与输出动作来建模同步时序控制逻辑,是数字系统控制通路最核心的设计范式。根据输出信号是否直接依赖当前输入,状态机分为 Moore 型与 Mealy 型两大类。
Moore 型状态机的输出仅取决于当前状态,与当前输入隔离,因此输出在整个时钟周期内天然稳定,输入变化需等待下一拍状态更新后才会反映到输出。Mealy 型状态机的输出同时取决于当前状态与当前输入,能比同功能的 Moore 状态机早一个时钟周期响应输入,但若直接采用组合逻辑输出则对异步输入毛刺敏感。工程设计通常先绘制状态转移图、标明状态与输入/输出,再优先采用三段式架构编码。
自动售卖机建模与三段式 Mealy 状态机(推荐)
以单价 2 元的自动售卖机为例:仅支持单次投入 0.5 元(`coin = 2'b01`)或 1 元(`coin = 2'b10`)硬币,满 2 元出货(`sell = 1`),若总计 2.5 元则同步找零 0.5 元(`change = 2'b01`),每轮交易结束后回到空闲态 `IDLE`。状态空间仅需 4 个状态:`IDLE`(0 元)、`GET05`(0.5 元)、`GET10`(1.0 元)和 `GET15`(1.5 元)。
推荐的三段式状态机结构清晰、时序优良:先以 `parameter` 定义可读状态编码(规模较大时也可采用独热码 one-hot 换取更快译码速度);第一段用时序 `always @(posedge clk or negedge rstn)` 非阻塞赋值完成 `st_cur <= st_next` 状态寄存;第二段用组合 `always @(*)` 阻塞赋值且覆盖全部 `default` 分支计算次态 `st_next`;第三段用时序 `always` 非阻塞赋值根据 `st_cur` 与 `coin` 寄存输出 `sell_r` 与 `change_r`。在 4 组投币场景(4×0.5 元、1+0.5+1 元、0.5+1+0.5 元、3×0.5+1 元)的验证中,出货与找零均精准触发且输出无组合毛刺。
两段式、一段式与 Moore 型状态机对比
将三段式的次态计算与输出逻辑合并至同一组合 `always @(*)` 块即构成两段式状态机。其组合输出较寄存输出提前一拍,但当外部输入 `coin` 未经同步而异步变化时,输出端会直接暴露毛刺尖峰,因此实际工程中对异步输入必须先做打拍同步,或优先采用三段式寄存输出。
将状态寄存、次态判断与输出驱动全部写入单个时序 `always` 块则形成一段式状态机。其仿真输出时序与三段式寄存输出一致,但当状态数和输出信号增多时,所有逻辑高度耦合在一起,难以阅读、审查和修改,仅在极简控制逻辑中慎用。
改用 Moore 型状态机描述同一售卖机时,必须额外增加 `GET20`(2.0 元出货无找零)与 `GET25`(2.5 元出货并找零)两个状态以将输出完全绑定到状态本身。若第三段仍采用时序非阻塞寄存输出,因进入 `GET20`/`GET25` 需耗费一拍,最终 `sell`/`change` 会比三段式 Mealy 晚 1 个时钟周期;而若将 Moore 第三段改为仅依赖已寄存状态 `st_cur` 的组合 `always @(*)` 输出(先赋初值 `0` 避免 Latch),既能与三段式 Mealy 同拍对齐,又因状态本身已同步而不受异步输入毛刺直穿干扰。来源工程压缩包已登记未联网抓取。
离线仿真自动售卖机三段/两段/一段 Mealy 与 Moore 状态机时序与编码
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
Moore 状态机必须先在时钟沿跳入新增的输出状态(`GET20`/`GET25`),再在下一拍由第三段触发器采样输出,故总延迟多 1 拍;将 Moore 第三段改为仅对已同步状态寄存器 `st_cur` 译码的组合逻辑(并赋默认值防 Latch),或直接采用三段式寄存输出 Mealy(并对输入先行同步),即可对齐响应周期并避免异步输入毛刺直穿。