module StateMachine(Dir, Count, A, B, RST, CLK); output reg Dir; output reg Count; input A; input B; input RST; input CLK; reg [1:0]PS, NS; parameter [1:0] ST_NORM = 'b00, ST_A = 'b01, ST_B = 'b11, ST_C = 'b10; initial begin PS <= ST_NORM; Count = 0; end always @(negedge RST or posedge CLK) if (!RST) PS <= ST_NORM; else if (CLK) PS <= NS; always @(A or B) begin case (PS) ST_NORM: if (A & !B) begin Dir = 0; Count = 1; NS = ST_A; end else if (!A & B) begin Dir = 1; Count = 1; NS = ST_C; end else NS = ST_NORM; ST_A: if (A & B) begin Dir = 0; Count = 0; NS = ST_B; end else if (!A & !B) begin Dir = 1; Count = 0; NS = ST_NORM; end else NS = ST_A; ST_B: if (!A & B) begin Dir = 0; Count = 1; NS = ST_C; end else if (A & !B) begin Dir = 1; Count = 1; NS = ST_A; end else NS = ST_B; ST_C: if (!A & !B) begin Dir = 0; Count = 0; NS = ST_NORM; end else if (A & B) begin Dir = 1; Count = 0; NS = ST_B; end else NS = ST_C; endcase end endmodule