题解 | #输入序列不连续的序列检测#

输入序列不连续的序列检测

https://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	[2:0]	state,next_state;

always@(*)begin
		case(state)
			0:		next_state = (data_valid)?(!data?1:0):0;
			1:		next_state = (data_valid)?( data?2:1):1;
			2:		next_state = (data_valid)?( data?3:1):2;
			3:		next_state = (data_valid)?(!data?4:0):3;
			4:		next_state = (data_valid)?(!data?1:0):0;
			default:next_state = 0;
		endcase
end

always@(posedge clk,negedge rst_n)begin
	if(!rst_n)begin
		state <= 0;
		match <= 0;
	end
	else begin
		state <= next_state;
	end
end

always@(*)begin
	match = state==4;
end
endmodule


`timescale  1ns / 1ps
module tb_sequence_detect;

// sequence_detect Parameters
parameter PERIOD  = 10;


// sequence_detect Inputs
reg   clk                                  = 0 ;
reg   rst_n                                = 0 ;
reg   data                                 = 0 ;
reg   data_valid                           = 0 ;

// sequence_detect Outputs
wire  match                                ;


initial
begin
    forever #(PERIOD/2)  clk=~clk;
end

initial
begin
    $dumpfile ("HDL_bit_wave.vcd");
    $dumpvars;
    #(PERIOD*2) rst_n  =  1;
end

sequence_detect  u_sequence_detect (
    .clk                     ( clk          ),
    .rst_n                   ( rst_n        ),
    .data                    ( data         ),
    .data_valid              ( data_valid   ),

    .match                   ( match        )
);

initial
begin
    #(PERIOD) data = 1;
    #(PERIOD) data = 1;
    #(PERIOD) data = 0;
    #(PERIOD) data = 0;
    #(PERIOD) data = 1;
    #(PERIOD) data = 1;
    #(PERIOD) data = 0;
    #(PERIOD) data = 0;
    #(PERIOD) data = 1;
    #(PERIOD) data = 1;
    #(PERIOD) data = 0;
    #(PERIOD) data = 0;
    #(PERIOD) data = 1;
    #(PERIOD) data = 1;
    #(PERIOD) data = 0;
    #(PERIOD) data = 0;
    #(PERIOD) data = 1;
    $finish;
end

initial begin
    #(PERIOD) data_valid = 0;
    #(PERIOD) data_valid = 0;
    #(PERIOD) data_valid = 1;
    #(PERIOD) data_valid = 1;
    #(PERIOD) data_valid = 1;
    #(PERIOD) data_valid = 1;
    #(PERIOD) data_valid = 0;
    #(PERIOD) data_valid = 1;
    #(PERIOD) data_valid = 0;
    #(PERIOD) data_valid = 1;
    #(PERIOD) data_valid = 1;
    #(PERIOD) data_valid = 0;
    #(PERIOD) data_valid = 0;
    #(PERIOD) data_valid = 1;
end

endmodule

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务