题解 | #不重叠序列检测#
不重叠序列检测
https://www.nowcoder.com/practice/9f91a38c74164f8dbdc5f953edcc49cc
踩了几个坑:
if elseif 后面的else忘记写了...属实是不该
原先match flag是在case逻辑里生成的,但是发现case逻辑需要在每个分支都写清楚flag的值才行,否则会报错。
状态图如下,且每6个cycle如果没有检测到match=1,则状态机重置到IDLE
`timescale 1ns/1ns module sequence_detect( input clk, input rst_n, input data, output reg match, output reg not_match ); reg[2:0] cur_st; reg[2:0] nxt_st; reg[2:0] cnt; wire match_flag; wire cnt_over; parameter IDLE = 3'h0, DATA1 = 3'h1, DATA2 = 3'h2, DATA3 = 3'h3, DATA4 = 3'h4, DATA5 = 3'h5, DATA6 = 3'h6; always@(posedge clk or negedge rst_n) begin if(~rst_n) begin cnt <= 0; end else if (cnt == 3'h5 ) begin cnt <= 0; end else begin cnt <= cnt+1; end end assign cnt_over = (cnt == 3'h5)? 1:0; always@(posedge clk or negedge rst_n) begin if(~rst_n) begin cur_st <= IDLE; end else if (cnt_over && ~match_flag) begin cur_st <= IDLE; end else begin cur_st <= nxt_st; end end always@(*) begin case(cur_st) IDLE: begin if(data == 0) begin nxt_st = DATA1; end else begin nxt_st = IDLE; end end DATA1: begin if(data == 1) begin nxt_st = DATA2; end else begin nxt_st = DATA1; end end DATA2: begin if(data == 1) begin nxt_st = DATA3; end else begin nxt_st = DATA1; end end DATA3: begin if(data == 1) begin nxt_st = DATA4; end else begin nxt_st = DATA1; end end DATA4: begin if(data == 0) begin nxt_st = DATA5; end else begin nxt_st = IDLE; end end DATA5: begin if(data == 0) begin nxt_st = DATA6; end else begin nxt_st = IDLE; end end DATA6: begin if(data == 0) begin nxt_st = DATA1; end else begin nxt_st = IDLE; end end endcase end assign match_flag = (nxt_st == DATA6); always@(posedge clk or negedge rst_n) begin if(~rst_n) begin match <= 1'b0; end else if (match_flag) begin match <= 1'b1; end else begin match <= 1'b0; end end always@(posedge clk or negedge rst_n) begin if(~rst_n) begin not_match <= 1'b0; end else if (cnt_over && ~match_flag) begin not_match <= 1'b1; end else begin not_match <= 1'b0; end end endmodule