/*
 Sampling clock frequency counter

 Copyright (c) 2009 Dimtel, Inc., All Rights Reserved

 $Id: freq_cnt.v,v 1.1 2009/08/29 19:56:31 dim Exp $
 $Date: 2009/08/29 19:56:31 $
 $Author: dim $
 $Revision: 1.1 $
 $Log: freq_cnt.v,v $
 Revision 1.1  2009/08/29 19:56:31  dim
 Initial import


*/

module freq_cnt(
  input clk,			// Bus clock (48 MHz)
  output [31:0] dout,		// Read data
  
  input dspclk			// DSP clock (up to 144 MHz)
);
  reg [1:0] dsp_cnt = 2'b0, dsp_gray_cnt = 2'b0;
  reg [1:0] usb_gray = 2'b0, usb_gray1 = 2'b0, usb_cnt1 = 2'b0;
  reg [1:0] usb_cnt2 = 2'b0, delta = 2'b0;
  reg [26:0] accum = 27'b0, out = 27'b0;
  reg [25:0] cnt = 26'b1;
  
  // Gray-code counter
  always @(posedge dspclk) begin
    dsp_cnt <= dsp_cnt + 2'b1;
    dsp_gray_cnt <= dsp_cnt ^ {1'b0, dsp_cnt[1]};
  end
  
  always @(posedge clk) begin
    usb_gray  <= dsp_gray_cnt;
    usb_gray1 <= usb_gray;
    usb_cnt1  <= usb_gray1 ^ {1'b0, usb_gray1[1]};
    usb_cnt2  <= usb_cnt1;
    delta     <= usb_cnt1 - usb_cnt2;
    
    cnt       <= cnt[25] ? 26'b1 : cnt + 26'b1;
    accum     <= cnt[25] ? delta : accum + delta;
    if (cnt[25]) out <= accum;
  end
  
  assign dout = out;
  
endmodule // freq_cnt
