题解 | #输入序列不连续的序列检测#
输入序列不连续的序列检测
http://www.nowcoder.com/practice/f96d0e94ec604592b502b0f1800ed8aa
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input data,
input data_valid,
output reg match
);
reg [3:0]state;
reg [3:0]next_state;
parameter IDLE=4'd0,S1=4'd1,S2=4'd2,S3=4'd3,S4=4'd4;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)begin
state<=IDLE;
end
else begin
state<=next_state;
end
end
always@(*)begin
case(state)
IDLE:next_state=data_valid?(data?IDLE:S1):IDLE;
S1:next_state=data_valid?(data?S2:S1):S1;
S2:next_state=data_valid?(data?S3:S1):S2;
S3:next_state=data_valid?(data?IDLE:S4):S3;
S4:next_state=data_valid?(data?IDLE:S1):IDLE;
default:next_state=IDLE;
endcase
end
always@(state or negedge rst_n)begin
if(!rst_n)begin
match=1'b0;
end
else if(state==S4)begin
match=1'b1;
end
else begin
match=1'b0;
end
end
endmodule
module sequence_detect(
input clk,
input rst_n,
input data,
input data_valid,
output reg match
);
reg [3:0]state;
reg [3:0]next_state;
parameter IDLE=4'd0,S1=4'd1,S2=4'd2,S3=4'd3,S4=4'd4;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)begin
state<=IDLE;
end
else begin
state<=next_state;
end
end
always@(*)begin
case(state)
IDLE:next_state=data_valid?(data?IDLE:S1):IDLE;
S1:next_state=data_valid?(data?S2:S1):S1;
S2:next_state=data_valid?(data?S3:S1):S2;
S3:next_state=data_valid?(data?IDLE:S4):S3;
S4:next_state=data_valid?(data?IDLE:S1):IDLE;
default:next_state=IDLE;
endcase
end
always@(state or negedge rst_n)begin
if(!rst_n)begin
match=1'b0;
end
else if(state==S4)begin
match=1'b1;
end
else begin
match=1'b0;
end
end
endmodule