题解 | #输入序列连续的序列检测#
输入序列连续的序列检测
http://www.nowcoder.com/practice/d65c2204fae944d2a6d9a3b32aa37b39
状态机实现
由于原序列中存在连续0和1,因而可使用计数器减少状态数,最终使用了4个状态实现,进一步精简可仅使用3个状态,代码如下
`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output reg match
);
reg [1:0] state;
reg [1:0] cnt;
//状态转换
always @(posedge clk or negedge rst_n) begin
if(!rst_n)
state <= 0;
else begin
case(state)
0: begin //0
if(!a)
state <= 1;
else
state <= 0;
end
1: begin //01110
if(cnt == 3) begin
if(!a)
state <= 2;
else
state <= 0;
end
else
state <= 1;
end
2: begin //01110001
if(a) begin
if(cnt == 2)
state <= 3;
else
state <= 1;
end
else
state <= 2;
end
3: begin
state <= 0;
end
endcase
end
end
//计数器计数
always @(posedge clk or negedge rst_n) begin
if(!rst_n)
cnt <= 0;
else begin
case(state)
1: begin
if(a)
cnt <= cnt + 1;
else
cnt <= 0;
end
2: begin
if(!a)
cnt <= cnt + 1;
else //检测到a == 1必然切换至1或3,若转换至1则因已检测一个高电平故cnt <= 1
cnt <= 1;
end
default: cnt <= 0;
endcase
end
end
//输出
always @(posedge clk or negedge rst_n) begin
if(!rst_n)
match <= 0;
else if(state == 3)
match <= 1;
else
match <= 0;
end
endmodule