题解 | #输入序列连续的序列检测#
输入序列连续的序列检测
https://www.nowcoder.com/practice/d65c2204fae944d2a6d9a3b32aa37b39
思路:既然是8位数据的序列检测,所以很自然地想到定义状态机来完成:S0_IDLE处于等待状态,当检测到a = 0时转到S1,如果为1则继续在S0处等待。在S1状态下检测是否满足a ==1,是则转到下一状态S2。这里有个关键点:!!!如果不满足,由于当前a==2'b00,末尾的0满足了数据帧01110001首位的要求,所以让其继续在S1状态等待,而不是跳回到S0处。之后的状态依次类推,由于match信号在满足要求的情况下延迟一拍输出,所以这里定义了S8状态用于打一拍,并且输出,代码如下;
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output reg match
);
parameter S0 = 4'b0000,
S1 = 4'b0001,
S2 = 4'b0010,
S3 = 4'b0011,
S4 = 4'b0100,
S5 = 4'b0101,
S6 = 4'b0110,
S7 = 4'b0111,
S8 = 4'b1000;
reg[3:0] state;
always @(posedge clk or negedge rst_n) begin
if(!rst_n) begin
match <= 1'b0;
state <= S0;
end
else begin
case(state)
S0:begin
if(a == 0) begin
state <= S1;
match <= 1'b0;
end
else begin
state <= S0;
match <= 1'b0;
end
end
S1:begin
if(a == 1)
state <= S2;
else
state <= S1;
end
S2:begin
if(a == 1)
state <= S3;
else
state <= S1;
end
S3:begin
if(a == 1)
state <= S4;
else
state <= S1;
end
S4:begin
if(a == 0)
state <= S5;
else
state <= S0;
end
S5:begin
if(a == 0)
state <= S6;
else
state <= S2;
end
S6:begin
if(a == 0)
state <= S7;
else
state <= S2;
end
S7:begin
if(a == 1) begin
state <= S8;
end
else
state <= S1;
end
S8:begin
state <= S0;
match <= 1'b1;
end
endcase
end
end
endmodule