写的比较繁琐,后面有时间再看看怎么优化一下,有好的方法可以评论区讨论呀
Consider a finite state machine that is used to control some type of motor. The FSM has inputs x and y, which come from the motor, and produces outputs f and g, which control the motor. There is also a clock input called clk and a reset input called resetn.
The FSM has to work as follows. As long as the reset input is asserted, the FSM stays in a beginning state, called state A. When the reset signal is de-asserted, then after the next clock edge the FSM has to set the output f to 1 for one clock cycle. Then, the FSM has to monitor the x input. When x has produced the values 1, 0, 1 in three successive clock cycles, then g should be set to 1 on the following clock cycle. While maintaining g = 1 the FSM has to monitor the y input. If y has the value 1 within at most two clock cycles, then the FSM should maintain g = 1 permanently (that is, until reset). But if y does not become 1 within two clock cycles, then the FSM should set g = 0 permanently (until reset).
(The original exam question asked for a state diagram only. But here, implement the FSM.)
题目分析:考虑用有限状态机来控制某种电机。根据输入x和y,输出f和g来控制电机。
复位时,state ==A;复位信号释放后一周期,output f 赋值1(1cycle);然后check x在连续的三个周期内是101序列,那么给output g赋值1,同时在接下来的两个周期check y是不是有等于1的时候,有的话g就永久为1直到复位;否则g就永久为0直到复位。
我当时想用cnt来计数两周期,但是总有点问题,哈哈最后放弃了,并增加了状态机数量来数两周期check y值-_-~~
我的代码:
module top_module (
input clk,
input resetn, // active-low synchronous reset
input x,
input y,
output f,
output g
);
parameter A = 3'b000,
B = 3'b001,
C = 3'b011,
D = 3'b010,
E = 3'b110,
F = 3'b100,
G = 3'b101;
reg [2:0] state,next_state;
reg [2:0] tmp_data1;
reg [1:0] cnt;
reg flag;
//monitor input x
always@(posedge clk)begin
if(!resetn)begin
tmp_data1 <= 0;
end
else if(state==C)
tmp_data1 <= {tmp_data1[1:0],x};
end
///timing logic, state transmit
always@(posedge clk)begin
if(!resetn)
state <= A;
else state <= next_state;
end
///combination logic, state transmit condition
always@(*)begin
case(state)
A:
next_state = resetn?B:A;
B:
next_state = C;
C:
next_state = (tmp_data1[1:0]==2'b10&&x)?D:C;
D:
next_state = y?F:E;
E:
next_state = y?F:G;
F:
next_state = F;
G:
next_state = G;
endcase
end
assign g = state == D || state == E || state == F;
assign f = state == B;
endmodule