这里最大的问题是:
always @(*)
和 always @(posedge clk or negedge rst_n)
的区别
always @(*)
在当前时钟内会变化
always @(posedge clk or negedge rst_n)
由时钟驱动,所以会在下一个时钟才发生变化
代码
module sequence_detect(
input clk,
input rst_n,
input data,
output reg match,
output reg not_match
);
parameter zero=0,one=1,two=2,three=3,four=4,five=5,six=6,fail=7;
reg [2:0] current_stage,next_stage;
reg [2:0] cnt;
always @(posedge clk or negedge rst_n) begin
if(~rst_n)begin
cnt <= 3'b0 ;
end
else begin
cnt <= (cnt == 3'd6) ? 3'b1: cnt+ 3'b1 ;
end
end
always @(posedge clk or negedge rst_n) begin
if(~rst_n)begin
current_stage <= zero;
end
else begin
current_stage <= next_stage;
end
end
always @(*) begin
if(~rst_n)begin
next_stage <= zero;
end
else begin
case(current_stage)
zero : next_stage = data==1'b0 ? one : fail;
one : next_stage = data==1'b1 ? two : fail;
two : next_stage = data==1'b1 ? three: fail;
three : next_stage = data==1'b1 ? four : fail;
four : next_stage = data==1'b0 ? five : fail;
five : next_stage = data==1'b0 ? six : fail;
six : next_stage = data==1'b0 ? one : fail;
fail : next_stage = (cnt == 6 && data == 1'b0) ? one : fail ;
default : next_stage = zero;
endcase
end
end
always @(*) begin
if(~rst_n)begin
match <= 1'b0 ;
not_match <= 1'b0;
end
else begin
match <= (cnt == 6 && current_stage == six) ;
not_match <= (cnt == 6 && current_stage == fail);
end
end
endmodule
testbench
module testbench_sequence_detect;
reg clk, rst_n, data;
wire match, not_match;
// Instantiate the Unit Under Test (UUT)
sequence_detect uut (
.clk(clk),
.rst_n(rst_n),
.data(data),
.match(match),
.not_match(not_match)
);
// Clock generation
initial begin
clk = 1;
forever #(5) clk = ~clk; // Generate a 10ns period clock signal
end
// Test stimulus
initial begin
rst_n = 0;
// data = 0;
#10;
// Reset the module
rst_n = 1;
data = 0;
#10;
// Send a sequence that does not match the expected pattern
// data = 1'b0; #10;
data = 1'b1; #10;
data = 1'b1; #10;
data = 1'b1; #10;
data = 1'b0; #10;
data = 1'b0; #10;
data = 1'b0; #10;
// Check if not_match is asserted
if (not_match) begin
$display("Sequence did not match at time %t", $time);
end else begin
$display("Test failed: not_match was not asserted when expected");
// $finish;
end
// // Reset the state
// #10;
// rst_n = 0;
// #10;
// rst_n = 1;
// Send the correct sequence
data = 1'b0; #10;
data = 1'b1; #10;
data = 1'b1; #10;
data = 1'b1; #10;
data = 1'b0; #10;
data = 1'b0; #10;
data = 1'b0; #10;
// Check if match is asserted
if (match) begin
$display("Sequence matched at time %t", $time);
end else begin
$display("Test failed: match was not asserted when expected");
// $finish;
end
// Finish the simulation
$finish;
end
endmodule