`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 14:39:51 04/09/2013
// Design Name:
// Module Name: counter_1
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module counter_1(clk,rst,data,Gap);
input clk,rst;
input [15:0] data;
output reg [3:0] Gap;
reg [3:0] temp;
reg [3:0] k;
reg Bit;
reg incr_temp,incr_k,flush_temp,store_temp;
reg [1:0] state,next_state;
parameter s_0=2'b00,s_1=2'b01,s_2=2'b10,s_done=2'b11;
always@(posedge clk) begin
if(rst)begin
incr_temp<=0;incr_k<=0;flush_temp<=0;store_temp<=0;
state<=s_0;
end
else begin state<=next_state;end
end
always@(state or Bit or k) begin
Bit<=data[k];
next_state<=state;
incr_temp<=0;incr_k<=0;flush_temp<=0;store_temp<=0;
case (state)
s_0:if(k==15)begin next_state<=s_done;end
else if(Bit==0) begin incr_k<=1;next_state<=s_0;end
else begin incr_k<=1;next_state<=s_1;end
s_1:if(k==15)begin next_state<=s_done;end
else if(Bit==1) begin incr_k<=1;next_state<=s_1;end
else begin incr_k<=1;incr_temp<=1;end
s_2:if(k==15)begin
if(Bit==1) begin
if(temp>Gap) begin next_state<=s_done;store_temp<=1;end
else begin
next_state<=s_done;end
end
else if(Bit==0) begin
next_state<=s_2;end
else if(temp>Gap) begin
incr_k<=1;
flush_temp<=0;
next_state<=s_1;store_temp<=1;
end
else begin
incr_k<=1;
flush_temp<=0;
next_state<=s_1;end
end
s_done:begin store_temp<=1;next_state<=s_done;end
default:begin next_state<=s_0;end
endcase
end
always@(posedge clk)begin
if(rst) begin
k<=0;Gap<=0;temp<=0;end
else if(incr_k) begin
k<=k+1;end
else if(incr_temp) begin
temp<=temp+1;end
else if(store_temp) begin
Gap<=temp;end
else if(flush_temp) begin
temp<=0;end
else temp<=temp;
end
endmodule