编写一个序列检测模块,检测输入信号a是否满足01110001序列,当信号满足该序列,给出指示信号match。
模块输入输出信号如图所示:
clk:系统时钟信号
rst_n :异步复位信号,低电平有效
a :单比特信号,传输待检测数据
程序如下:
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output match
);
reg [3:0]state,next_state;
always@(posedge clk or negedge rst_n)
begin
if(rst_n == 1’b0)
state <= 'd0;
else
state <= next_state;
end
always@(*)
begin
case(state)
4'd0:
begin
if(a==1'b0)
next_state = 4'd1;
else
next_state =4'd0;
end
4'd1: begin
if(a==1'b1)
next_state = 4'd2;
else
next_state = 4'd1;
end
4'd2:
begin
if(a==1'b1)
next_state = 4'd3;
else
next_state = 4'd1;
end
4'd3:
begin
if(a==1'b1)
next_state = 4'd4;
else
next_state = 4'd1;
end
4'd4:
begin
if(a==1'b0)
next_state = 4'd5;
else
next_state = 4'd0;
end
4'd5:
begin
if(a==1'b0)
next_state = 4'd6;
else
next_state = 4'd0;
end
4'd6:
begin
if(a==1'b0)
next_state = 4'd7;
else
next_state = 4'd0;
end
4'd7:
begin
if(a==1'b1)
next_state =4'd8;
else
next_state =4'd0;
end
4'd8:
next_state = 4'd1;
default:
next_state = 4'd0;
endcase
end
assign match = (next_state == 4'd8)?1:0;
endmodule
testbench 编写:
module tb;
reg clk,rst_n;
reg a;
wire match;
initial begin
rst_n = 0;
#100;
rst_n = 1;
#10 a = 0;
#10 a = 0;
#10 a = 1;
#10 a = 1;
#10 a = 1;
#10 a = 0;
#10 a = 0;
#10 a = 0;
#10 a = 1;
end
initial begin
clk = 0;
forever#5 clk = ~clk;
end
sequence_detect dut(
.clk(clk),
.rst_n(rst_n),
.a(a),
.match(match)
);
endmodule
仿真结果: