【归档】摩尔状态机和米莉状态机

Scroll Down

摩尔状态机检测序列10101

摩尔状态机

module fsm(Clk,key,rst_n,out
	);
	input Clk;
	input key;
	input rst_n;
	output out;
	reg Out=0;
	assign out=Out;
	reg [2:0]state=0;
	
	parameter 	S0 	=3'b000,
			S1	=3'b001,
			S2	=3'b010,
			S3	=3'b011,
			S4	=3'b100,
			S5	=3'b101;
	
	always@(posedge Clk or negedge rst_n )
	begin
		if(!rst_n)
		begin
			state<=S0;
			Out<=0;
		end
		else
		begin
			case(state)
			S0:	if(key)
				begin
					state<=S1;
					Out<=0;
				end
				else
				begin
					state<=S0;
					Out<=0;
				end
			S1:	if(!key)
				begin
					state<=S2;
					Out<=0;
				end
				else
				begin
					state<=S1;
					Out<=0;
				end
				S2:	if(key)
				begin//转过来格式太乱了不想改了,摸了
							state<=S3;
							Out<=0;
						end
						else
						begin
							state<=S0;
							Out<=0;
						end
				S3:	if(!key)
						begin
							state<=S4;
							Out<=0;
						end
						else
						begin
							state<=S1;
							Out<=0;
						end
				S4:	if(key)
						begin
							state<=S5;
							Out<=0;
						end
						else
						begin
							state<=S0;
							Out<=0;
						end
				S5:	begin
							Out<=1;
							#10 state<=S0;
						end	
			endcase
		end		
	end	
endmodule


Testbench

module sim_fsm(

    );
	reg Clk=0;
	wire out;
	reg	[7:0]key=8'b0111_0101;
	always	#2 Clk=~Clk;
	always@(negedge Clk)
		key=key<<1;
	
	fsm UUT(
					.Clk(Clk),
					.key(key[7]),
					.rst_n(1),
					.out(out));
endmodule

输出结果

摩尔结果

米莉状态机检测序列10101

米莉状态机

module Mealy_fsm(Clk,key,rst_n,out

    );
	input Clk;
	input key;
	input rst_n;
	output out;
	reg Out=0;
	assign out=Out;
	reg [2:0]state;
	
	parameter 	S0 	=3'b000,
						S1	=3'b001,
						S2	=3'b010,
						S3	=3'b011,
						S4	=3'b100;
	always@(posedge Clk)
	begin
		if(key&&state==4)
			Out<=1;
		else
			Out<=0;
	end
	always@(posedge Clk or negedge rst_n )
	begin
		if(!rst_n)
		begin
			state<=S0;
		end
		else
		begin
			case(state)
				S0:	if(key)
						begin
							state<=S1;	
						end
						else
						begin
							state<=S0;
						end
				S1:	if(!key)
						begin
							state<=S2;
						end
						else
						begin
							state<=S1;
						end
				S2:	if(key)
						begin
							state<=S3;
						end
						else
						begin
							state<=S0;
						end
				S3:	if(!key)
						begin
							state<=S4;
						end
						else
						begin
							state<=S1;
						end
				S4:	if(key)
						begin
							 state<=S1;
						end
						else
						begin
							state<=S0;
						end
				default state<=S0;				
			endcase
		end		
	end	
endmodule

Testbench

module sim_fsm(

    );
	reg Clk=0;
	wire out;
	reg	[7:0]key=8'b0111_0101;
	always	#2 Clk=~Clk;
	always@(negedge Clk)
		key=key<<1;
	
	Mealy_fsm UUT(
					.Clk(Clk),
					.key(key[7]),
					.rst_n(1),
					.out(out));
endmodule

输出结果

米莉结果