题目:
给定一个输入序列01101001101101101找出序列为1101并统计其个数。请用有限状态机(FSM)实现。
解题:
代码:
bash
module sequence_detector(
input wire clk, // 时钟信号
input wire reset, // 复位信号
input wire seq_in, // 输入序列
output reg [3:0] count // 计数器
);
// 状态编码
parameter S0 = 4'b0000, // 初始状态
S1 = 4'b0001, // 检测到 '1'
S11 = 4'b0011, // 检测到 '11'
S110 = 4'b0110, // 检测到 '110'
S1101 = 4'b1101; // 检测到 '1101'
reg [3:0] current_state, next_state;
// 状态转移:根据时钟上升沿或复位信号进行状态转移
always @(posedge clk or posedge reset) begin
if (reset) begin
current_state <= S0;
count <= 0;
end else begin
current_state <= next_state;
end
end
// 下一个状态逻辑:根据当前状态和输入序列计算下一个状态
always @(*) begin
case (current_state)
S0: begin
if (seq_in == 1)
next_state = S1;
else
next_state = S0;
end
S1: begin
if (seq_in == 1)
next_state = S11;
else
next_state = S0;
end
S11: begin
if (seq_in == 0)
next_state = S110;
else
next_state = S11;
end
S110: begin
if (seq_in == 1)
next_state = S1101;
else
next_state = S0;
end
S1101: begin
if (seq_in == 1)
next_state = S11;
else
next_state = S0;
end
default: next_state = S0;
endcase
end
// 输出逻辑:当达到状态S1101时增加计数器
always @(posedge clk or posedge reset) begin
if (reset) begin
count <= 0;
end else if (current_state == S1101) begin
count <= count + 1;
end
end
endmodule
仿真模块:
bash
// 测试模块
module tb_sequence_detector;
// 测试信号
reg clk;
reg reset;
reg seq_in;
wire [3:0] count;
// 实例化序列检测器
sequence_detector uut (
.clk(clk),
.reset(reset),
.seq_in(seq_in),
.count(count)
);
// 时钟信号生成
always #5 clk = ~clk;
initial begin
// 初始化信号
clk = 0;
reset = 0;
seq_in = 0;
// 复位
reset = 1;
#10;
reset = 0;
// 提供输入序列 01101001101101101
seq_in = 0; #10;
seq_in = 1; #10;
seq_in = 1; #10;
seq_in = 0; #10;
seq_in = 1; #10;
seq_in = 0; #10;
seq_in = 0; #10;
seq_in = 1; #10;
seq_in = 1; #10;
seq_in = 0; #10;
seq_in = 1; #10;
seq_in = 1; #10;
seq_in = 1; #10;
seq_in = 0; #10;
seq_in = 1; #10;
seq_in = 1; #10;
seq_in = 0; #10;
seq_in = 1; #10;
// 结束仿真
#50;
$finish;
end
endmodule
结果正确:
解析:
1、状态定义:
定义FSM的不同状态来表示已经检测到的序列部分。
S0:初始状态
S1:检测到一个1
S11:检测到11
S110:检测到110
S1101:检测到1101(目标序列)
2、状态转移:根据输入位和当前状态确定下一个状态。
3、计数逻辑:每当FSM到达目标状态S1101时,增加计数器。