freq_meter.v 2.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*!
 * <b>Module:</b>freq_meter
 * @file freq_meter.v
 * @date 2016-02-13  
 * @author Andrey Filippov     
 *
 * @brief Measure device clock frequency to set the local clock
 *
 * @copyright Copyright (c) 2016 Elphel, Inc .
 *
 * <b>License:</b>
12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * freq_meter.v is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  freq_meter.v is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/> .
25
 */
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
`timescale 1ns/1ps

module  freq_meter#(
    parameter WIDTH =    12, // width of the result
    parameter PRESCALE = 1 // 0 same frequency, +1 - xclk is tvice faster, -1 - twice slower
)(
    input                     rst,
    input                     clk,
    input                    xclk,
    output reg [WIDTH - 1:0] dout
);
    localparam TIMER_WIDTH = WIDTH - PRESCALE;
    reg [TIMER_WIDTH - 1 :0] timer;
    reg       [WIDTH - 1 :0] counter;
    
    wire                     restart;
    reg                [3:0] run_xclk;
    
    always @ (posedge clk) begin
        if      (rst || restart)          timer <= 0;
        else if (!timer[TIMER_WIDTH - 1]) timer <= timer + 1;
        
        if (restart) dout <= counter; // it is stopped before copying
        
    end
    always @ (posedge xclk) begin
        run_xclk <= {run_xclk[2:0], ~timer[TIMER_WIDTH - 1] & ~rst};
        
        if      (run_xclk[2]) counter <= counter + 1;
        else if (run_xclk[1]) counter <= 0;
        
    end
    
    pulse_cross_clock #(
        .EXTRA_DLY(0)
    ) xclk2clk_i (
        .rst       (rst),                         // input
        .src_clk   (xclk),                        // input
        .dst_clk   (clk),                         // input
        .in_pulse  (!run_xclk[2] && run_xclk[3]), // input
        .out_pulse (restart),                     // output
        .busy      ()                             // output
    );
    
    
endmodule