解法一:最容易想到的casex
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output reg match
);
reg [8:0] val;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)begin
val <= 0;
end
else begin
val <= {val[7:0],a};
end
end
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
match <= 0;
else begin
casex(val)
9'b011xxx110 : match <= 1'b1;
default : match <= 1'b0;
endcase
end
end
endmodule
解法二:移位方式
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output reg match
);
reg [8:0] val;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)begin
val <= 0;
end
else begin
val <= {val[7:0],a};
end
end
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
match <= 1'b0;
else
match <= (val[2:0] == 3'b110) && (val[8:6] == 3'b011);
end
endmodule
解法三:三段式状态机
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output reg match
);
parameter s0 = 4'd0,
s1 = 4'd1,
s2 = 4'd2,
s3 = 4'd3,
s4 = 4'd4,
s5 = 4'd5,
s6 = 4'd6,
s7 = 4'd7,
s8 = 4'd8,
s9 = 4'd9;
reg [3:0] curr_state,next_state;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
curr_state <= s0;
else
curr_state <= next_state;
end
always@(*)begin
case(curr_state)
s0:next_state = a ? s0 : s1;
s1:next_state = a ? s2 : s1;
s2:next_state = a ? s3 : s1;
s3:next_state = s4;
s4:next_state = s5;
s5:next_state = s6;
s6:next_state = a ? s7 : s1;
s7:next_state = a ? s8 : s1;
s8:next_state = a ? s0 : s9;
s9:next_state = a ? s0 : s1;
default:next_state = s0;
endcase
end
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
match <= 0;
else
match <= curr_state == s9;
end
endmodule