module top_module ( input clk, input reset, input data, output reg [3:0] count, output reg counting, output reg done, input ack ); reg [3:0] st = 0; reg shift_ena = 0; reg count_ena = 0; reg cnt_999_en = 0; reg [9:0] cnt = 0; //counting 1000 clocks always @ (posedge clk) if(~cnt_999_en) cnt <= 0; else //cnt_999_en is asserted begin if(cnt == 999) cnt <= 0; else cnt <= cnt + 1; end always @ (posedge clk) begin if(shift_ena) begin count <= {count[2:0],data}; end if(count_ena) begin count <= count -1; end end //main fsm always @ (posedge clk) if(reset) begin st <= 0; counting <= 0; done <= 0; shift_ena <= 0; count_ena <= 0; cnt_999_en <= 0; end else begin case(st) 0: //detect sequence 1101 if(data) st <= 1; 1: begin if(data) st <= 2; else st <= 0; end 2: begin if(~data) st <= 3; else st <= 2; end 3://detect sequence 1101 begin if(data) begin st <= 4; shift_ena <= 1; end else st <= 0; end 4://shift 4 more bits, and ack asserts st <= 5; 5: st <= 6; 6: st <= 7; 7: //start to count, count is ready begin shift_ena <= 0; count_ena <= 0; counting <= 1; if(count >= 0) begin cnt_999_en <= 1; //count 999 if(cnt == 998 ) begin cnt_999_en <= 0; count_ena <= 1; if(count == 0 ) begin st <= 8; count_ena <= 0; end end end end 8: begin cnt_999_en <= 0; counting <= 0; done <= 1; st <= 9; end 9: begin if(ack) begin done <= 0; st <= 0; end end default: st <= 0; endcase end endmodule