解题思路
此题按照状态转移图描写状态机就可以,但注意一个细节:
我刚开始使用的时序逻辑输出,因为一般三段式都是时序逻辑输出,代码如下:
always@(posedge clk or negedge rst_n) begin
if (~rst_n)
Y <= 1'b0;
else if(((state == ST2) && C) || (state == ST3))
Y <= 1'b1;
else
Y <= 1'b0;
end
发现答案过不了,波形如下:
明显看出,我的Y比参考答案延后了一个时钟周期,因为时序逻辑会延后一个时钟周期,根据波形逆推,所以采用了组合逻辑,代码如下:
always@(*) begin
if(((state == ST2) && C) || (state == ST3))
Y = 1'b1;
else
Y = 1'b0;
end
完整代码实现
`timescale 1ns/1ns
module seq_circuit(
input wire clk ,
input wire rst_n,
input wire C ,
output reg Y
);
reg [1:0] state, next_state;
parameter ST0 = 2'd0;
parameter ST1 = 2'd1;
parameter ST2 = 2'd2;
parameter ST3 = 2'd3;
always@(posedge clk or negedge rst_n) begin
if (~rst_n)
state <= 2'd0;
else
state <= next_state;
end
always@(*) begin
case(state)
ST0: next_state = C ? ST1 : ST0;
ST1: next_state = C ? ST1 : ST3;
ST2: next_state = C ? ST2 : ST0;
ST3: next_state = C ? ST2 : ST3;
default: next_state = ST0;
endcase
end
always@(*) begin
if(((state == ST2) && C) || (state == ST3))
Y = 1'b1;
else
Y = 1'b0;
end
endmodule