1 module review2015_fancytimer ( 2 input clk, 3 input reset, // Synchronous reset 4 input data, 5 output [3:0] count, 6 output counting, 7 output done, 8 input ack 9 ); 10 11 parameter S = 0, S1 = 1, S11 = 2, S110 = 3, B0 = 4, B1 = 5, B2 = 6, B3 = 7, Count = 8, Wait = 9; 12 reg [4:0] state, next_state; 13 reg [ 3:0] d; 14 reg [14:0] cnt; 15 always @(*) begin 16 case (state) 17 S: next_state = data ? S1 : S; 18 S1: next_state = data ? S11 : S; 19 S11: next_state = data ? S11 : S110; 20 S110: next_state = data ? B0 : S; 21 B0: next_state = B1; 22 B1: next_state = B2; 23 B2: next_state = B3; 24 B3: next_state = Count; 25 Count: next_state = cnt == 0 ? Wait : Count; 26 Wait: next_state = ack ? S : Wait; 27 default: next_state = S; 28 endcase 29 end 30 //fsm 31 always @(posedge clk) begin 32 if (reset) begin 33 state <= S; 34 end else begin 35 state <= next_state; 36 end 37 end 38 39 always @(posedge clk) begin 40 case (state) 41 B0: d = {d[2:0], data}; 42 B1: d = {d[2:0], data}; 43 B2: d = {d[2:0], data}; 44 B3: begin 45 d = {d[2:0], data}; 46 cnt = d * 1000 + 999; 47 end 48 Count: cnt <= cnt - 1'b1; 49 default: cnt = 999; 50 endcase 51 end 52 53 assign count = cnt / 1000; 54 assign counting = state == Count; 55 assign done = state == Wait; 56 57 58 endmodule
借鉴:https://blog.csdn.net/NJUzzf98/article/details/124216781
反思:协议相关的程序该用状态机还是状态机,逻辑清晰且不会产生什么差错;计数器直接用多位一次实现,最好不要互相嵌套。