题目如下:
方法一:状态机的方法(注意match为时序逻辑,落后一个时钟周期)
状态的转换如下图所示:
代码如下:
注意:match是reg型变量,赋值时需要用时序逻辑进行赋值,或者将其改为wire型变量,然后用assign进行赋值。
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output reg match
);
reg [3:0]state,next_state;
wire match_reg;
parameter IDLE =4'd0,
ONE =4'd1,
TWO =4'd2,
THREE =4'd3,
FOUR =4'd4,
FIVE =4'd5,
SIX =4'd6,
SEVEN =4'd7,
EIGHT =4'd8;
always@(posedge clk or negedge rst_n)
if(rst_n==1'b0)
state<=IDLE;
else
state<=next_state;
always@(*)
case(state)
IDLE :next_state<=a?IDLE:ONE;
ONE :next_state<=a?TWO:ONE;
TWO :next_state<=a?THREE:ONE;
THREE :next_state<=a?FOUR:ONE;
FOUR :next_state<=a?IDLE:FIVE;
FIVE :next_state<=a?IDLE:SIX;
SIX :next_state<=a?IDLE:SEVEN;
SEVEN :next_state<=a?EIGHT:ONE;
default:next_state<=IDLE;
endcase
assign match_reg=(state==EIGHT);
always@(posedge clk or negedge rst_n)
if(rst_n==1'b0)
match<=1'b0;
else
match<=match_reg;
endmodule
方法二:移位寄存器的方法
一种非常简单,节约代码的方法。
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output reg match
);
reg [7:0] din;
always @(posedge clk or negedge rst_n) begin
if(~rst_n)
din <= 8'd0;
else
din <= {din[6:0],a};
end
always @(posedge clk or negedge rst_n) begin
if(~rst_n)
match <= 1'b0;
else if(din == 8'b0111_0001)
match <= 1'b1;
else
match <= 1'b0;
end
endmodule