老师留的作业,顺便贴出来给大家看看
FSM的优化写法
采用所谓"三段式"的状态机写法清晰而且可以有效的避免毛刺,列一例来体会.
module FSM ( nrst,clk, i1,i2, o1,o2, err ); input nrst,clk; input i1,i2; output o1,o2,err; reg o1,o2,err; reg [2:0] NS,CS; parameter [2:0] //one hot with zero idle"独热码" IDLE = 3'b000, S1 = 3'b001, S2 = 3'b010, ERROR = 3'b100; always @ (posedge clk or negedge nrst) if (!nrst) CS <= IDLE; else CS <=NS; always @ (nrst or CS or i1 or i2) begin NS = 3'bx; case (CS) IDLE: begin if (~i1) NS = IDLE; if (i1 && i2) NS = S1; if (i1 && ~i2) NS = ERROR; end S1: begin if (~i2) NS = S1; if (i2 && i1) NS = S2; if (i2 && (~i1)) NS = ERROR; end S2: begin if (i2) NS = S2; if (~i2 && i1) NS = IDLE; if (~i2 && (~i1)) NS = ERROR; end ERROR: begin if (i1) NS = ERROR; if (~i1) NS = IDLE; end endcase end always @ (posedge clk or negedge nrst) if (!nrst) {o1,o2,err} <= 3'b000; else begin {o1,o2,err} <= 3'b000; case (NS) IDLE: {o1,o2,err}<=3'b000; S1: {o1,o2,err}<=3'b100; S2: {o1,o2,err}<=3'b010; ERROR: {o1,o2,err}<=3'b111; endcase end endmodule//采用时序输出的方式可以减少毛刺 |