Q3a(Exams/2014 q3fsm)
代码如下:
module top_module (
input clk,
input reset, // Synchronous reset
input s,
input w,
output z
);
parameter A=2'd0 ,B=2'd1, DONE=2'd2 ;
reg [1:0] state ,next_state ;
//状态更新
always@(posedge clk) begin
if(reset) begin
state <= A ;
end else begin
state <= next_state ;
end
end
//状态转换
always@(*) begin
case(state)
A: next_state = s? B : A ;
B: next_state = (cnt==3)? DONE : B ;
DONE: next_state = B ;
default: next_state = state ;
endcase
end
//计数操作
reg [1:0] cnt ;
always@(posedge clk) begin
if(reset) begin
cnt <= 2'd0 ;
end else if(next_state == B) begin
cnt <= cnt + 2'd1 ;
end else if(next_state == A)begin
cnt <= 2'd0 ;
end else begin
cnt <= 2'd1 ;
end
end
//判断1的个数
reg [1:0] en ;
always@(posedge clk) begin
if(reset) begin
en <= 2'd0 ;
end else if(state == B)begin
if(w) begin
en <= en+2'd1 ;
end else begin
en <= en ;
end
end else if(state == DONE)begin
if(w) begin
en <= 2'd1 ;
end else begin
en <= 2'd0 ;
end
end else begin
en <= 2'd0 ;
end
end
//状态机输出
assign z= ((state == DONE) && (en == 2'd2));
endmodule
Q3b(Exams/2014 q3bfsm)
代码如下:
module top_module (
input clk,
input reset, // Synchronous reset
input x,
output z
);
parameter A =3'b000, B =3'b001, C =3'b010, D =3'b011, E =3'b100 ;
reg [2:0] state,next_state ;
always@(posedge clk) begin
if(reset) begin
state <= A ;
end else begin
state <= next_state ;
end
end
always@(*) begin
case(state)
A: next_state = x? B : A ;
B: next_state = x? E : B ;
C: next_state = x? B : C ;
D: next_state = x? C : B ;
E: next_state = x? E : D ;
default: next_state = state ;
endcase
end
assign z = ((state == D) || (state == E)) ;
endmodule
Q3c(Exams/2014 q3c)
代码如下:
module top_module (
input clk,
input [2:0] y,
input x,
output Y0,
output z
);
parameter A =3'b000, B =3'b001, C =3'b010, D =3'b011, E =3'b100 ;
reg [2:0] next_state ;
always@(*) begin
case(y)
A: next_state = x? B : A ;
B: next_state = x? E : B ;
C: next_state = x? B : C ;
D: next_state = x? C : B ;
E: next_state = x? E : D ;
default: next_state = A ;
endcase
end
assign z = ((y == D) || (y == E)) ;
assign Y0 = next_state[0] ;
endmodule