牛客Verilog题目(3)——输入序列连续的序列检测

1.题目

牛客Verilog题目(3)——输入序列连续的序列检测_第1张图片

2.解法

这题思路很简单,一个M位(这里是8)移位器,然后再将移位器的8位数和要求序列对比。
这里对比条件是否需要延迟一个时钟,通过题目的实例看出:是需要延迟的。所以正确代码:

`timescale 1ns / 1ns
module test2(
	input clk,
	input rst_n,
	input a,
	output reg match,
	reg [7:0] adata
	);
	
	always@(posedge clk or negedge rst_n) begin
	   if(!rst_n) begin
	       adata <= 8'b0; 
	       end
	    else begin
	       adata <= {adata[6:0],a}; 
	       end
	    end
	    
	 always@(posedge clk or negedge rst_n) 
         if(!rst_n) begin
              match <= 1'b0;
              end
          else if(adata == 8'b01110001) begin
              match <= 1'b1; 
              end
           else begin
              match <= 1'b0;
              end
endmodule

testbench为:

`timescale 1ns / 1ns
module testbench(

    );
    reg clk=0,rst_n;
    reg a;
    reg Q2,Q1;
    wire match;
    wire [7:0] adata;
    always #5 clk = ~clk;
    always@(posedge clk or negedge rst_n) begin
        if(!rst_n) begin
            a <= 0;
            Q1 <= 0;
            Q2 <= 0;          
            end
        else begin
            Q2 <= Q1;
            Q1 <= a;
            a <= ~Q2&~a | ~Q2&Q1 | Q2&~Q1&a;
            end
            end
     initial begin
        rst_n=0;
        #1 rst_n = 1;
        #150 $finish;
        end  
            
    test2 dut(
        .clk(clk),
        .rst_n(rst_n),
        .a(a),
        .match(match),
        .adata(adata)
    );
endmodule

RTL分析:
牛客Verilog题目(3)——输入序列连续的序列检测_第2张图片
而判定模块为组合模块时,代码为:

`timescale 1ns / 1ns
module test2(
	input clk,
	input rst_n,
	input a,
	output reg match,
	reg [7:0] adata
	);
	
	always@(posedge clk or negedge rst_n) begin
	   if(!rst_n) begin
	       adata <= 8'b0; 
	       end
	    else begin
	       adata <= {adata[6:0],a}; 
	       end
	    end
	    
//	 always@(posedge clk or negedge rst_n) 
    always@ *
         if(!rst_n) begin
              match = 1'b0;
              end
          else if(adata == 8'b01110001) begin
              match = 1'b1; 
              end
           else begin
              match = 1'b0;
              end
endmodule

RTL分析:(把寄存器换成了二位选择器)
牛客Verilog题目(3)——输入序列连续的序列检测_第3张图片
从图中也可以看出,出现01110001后的下一时钟,match就变成了1.
牛客Verilog题目(3)——输入序列连续的序列检测_第4张图片

你可能感兴趣的:(fpga开发)