状态机写法
能够检测重叠部分
// 2022-1-30 verilog学习
// 检测序列1011 状态机写法
module seq_detect(
clk,
res,
en,
din,
match
);
input en,din,res,clk;
output match;
reg[2:0] state;
reg match;
always@(posedge clk or negedge res)
if(~res) begin
match<=0; state<=0;
end
else begin
case(state)
0: // 等待使能信号
begin
if(en)begin
state<=1;
end
else begin
state<=0;
end
end
1: //s_idle 等待首字节1011的“1”011
begin
match<=0;
if(din==1)begin
state<=2;
end
else begin
state<=1;
end
end
2: //s_1
begin
match<=0;
if(din==0)begin
state<=3;
end
else begin
state<=2;
end
end
3: //s_10
begin
match<=0;
if(din==1)begin
state<=4;
end
else begin
state<=1;
end
end
4: //s_101
begin
if(din==1)begin
state<=2;
match<=1; // 匹配1011
end
else begin
state<=3;
end
end
default: // 万一case>4
begin
state <= 0;
match<=0;
end
endcase
end
endmodule
//------testbench----
module seq_detect_tb;
reg clk,res,en;
reg[3:0] din_send; // 预存所有数据
wire din; // 已经预设好,不需要变化
wire match;
seq_detect seq_detect(
.clk(clk),
.res(res),
.en(en),
.din(din),
.match(match)
);
initial begin
clk<=0; res<=0; en<=1; din_send<=4'b1011;
#17 res<=1;
#200 $stop;
end
always #5 clk = ~clk;
always@(posedge clk)begin
din_send[3:0] <= {din_send[2:0], din_send[3]}; // 每次时钟上升沿,循环左移
end
assign din = din_send[3]; // 将最高位输入到序列检测器中
endmodule
寄存器写法:
// 2022-1-30 verilog学习
// 检测序列1011 非状态机写法 寄存器写法
module seq_detect_sf(
clk,
res,
en,
din,
match
);
input en,din,res,clk;
output match;
reg[2:0] sf_reg; // 移动寄存器 shift_reg
reg match;
always@(posedge clk or negedge res)
if(~res) begin
match<=0; sf_reg<=0;
end
else if(en) begin
sf_reg <= {sf_reg[1:0], din}; // 左移寄存器
if(sf_reg == 3'b101 && din==1) begin
match<=1;
end
else begin
match<=0;
end
end
endmodule
//------testbench----
module seq_detect_sf_tb;
reg clk,res,en;
reg[3:0] din_send;
wire din;
wire match;
seq_detect_sf seq_detect_sf(
.clk(clk),
.res(res),
.en(en),
.din(din),
.match(match)
);
initial begin
clk<=0; res<=0; en<=1; din_send<=4'b1011;
#17 res<=1;
#200 $stop;
end
always #5 clk = ~clk;
always@(posedge clk)begin
din_send[3:0] <= {din_send[2:0], din_send[3]}; // 每次时钟上升沿,循环左移
end
assign din = din_send[3]; // 将最高位输入到序列检测器中
endmodule