题解 | #不重叠序列检测#

不重叠序列检测

https://www.nowcoder.com/practice/9f91a38c74164f8dbdc5f953edcc49cc

`timescale 1ns/1ns
module sequence_detect(
	input clk,
	input rst_n,
	input data,
	output reg match,
	output reg not_match
	);

	parameter st0 = 3'd0;//开始状态
	parameter st1 = 3'd1;
	parameter st2 = 3'd2;
	parameter st3 = 3'd3;
	parameter st4 = 3'd4;
	parameter st5 = 3'd5;
	parameter st6 = 3'd6;
	parameter st7 = 3'd7;//等待状态,当数据不符合时进入此状态;当处于这个状态且计数器为6时,则可以判断下一组数据了,即进入st1状态

	reg [2:0] st_cur;
	reg [2:0] st_next;
	always@(posedge clk or negedge rst_n) begin
		if(!rst_n) begin
			st_cur <= 0;
			st_next <= 0;
		end
		else begin
			st_cur <= st_next;
		end
	end

	reg [2:0] cnt;
	always @(posedge clk or negedge rst_n) begin
		if (!rst_n) begin
			cnt <= 0;
		end
		else if(cnt >= 6) begin
			cnt <= 1;//状态机st1跳至st6只需要五个数,即cnt=0时仅表示开始的初始状态,所以在这之后可以从1开始加到6
		end
		else begin
			cnt <= cnt + 1'b1;
		end
	end

	always@(*) begin
		if (!rst_n) begin
			st_next = 0;
			not_match = 0;
		end
		else begin
			case(st_cur)
				st0: 
					case(data)
						0: st_next = st1;
						1: st_next = st7;
					endcase
				st1:
					case(data)
						1: st_next = st2;
						0: st_next = st7;
					endcase
				st2:
					case(data)
						1: st_next = st3;
						0: st_next = st7;
					endcase
				st3:
					case(data)
						1: st_next = st4;
						0: st_next = st7;
					endcase
				st4:
					case(data)
						0: st_next = st5;
						1: st_next = st7;
					endcase
				st5:
					case(data)
						0: st_next = st6;
						1: st_next = st7;
					endcase
				st6:
					case(data)
						0: st_next = st1;
						1: st_next = st7;
					endcase
				st7:
					case(data)
						0: 
						if(cnt == 6) begin
							st_next = st1;
						end
						else begin
							st_next = st7;
						end
						1: st_next = st7;
					endcase
			endcase
		end
	end

	always@(*) begin
		if(!rst_n) begin
			match = 0;
			not_match = 0;
		end
		else if(st_cur == st6 & cnt == 6) begin
			match = 1;
			not_match = 0;
		end
		else if(st_cur == st7 & cnt == 6) begin
			match = 0;
			not_match = 1;
		end
		else begin
			match = 0;
			not_match = 0;
		end
	end




					
	
endmodule

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务