Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

circuit/verilog for frequency comparision

Status
Not open for further replies.

vijay82

Member level 2
Joined
Jan 13, 2007
Messages
52
Helped
6
Reputation
12
Reaction score
7
Trophy points
1,288
Activity points
1,724
Could anybody give ideas for a circuit which finds out the higher frequency of two clocks - circuit should have 2 inputs, 1 output. Depending on the circuit, synchronization also should be taken care of. Verilog code is also fine.

Thanks for any help.
 

You could implement a PFD (phase frequency detector) such as used in PLL circuits. Only where in a PLL the chargepump would be, you do an up/down count followed by a threshold. The purpose of that is to add some hysteresis/dead band. The output of the threshold then is your "f1 < f2" output.

Hope that serves as some inspiration. :)
 

    vijay82

    Points: 2
    Helpful Answer Positive Rating
Thanks. At first sight, that sounds like some heavy analog stuff (at least to me) :D

This was an interview question for a RTL design position and hence I was thinking of a conceptually simpler idea using flip-flops, counters, gates and such like. Even so, your idea is interesting - I'll look into it more deeply.
 

No need for analog, the PFD can be done with gates + flipflops.

From the wiki (link is in my previous post): "A more complex digital PD uses a simple state machine to determine which of the two signals has a zero-crossing earlier or more often. This brings the PLL into lock even when it is off frequency and is known as a Phase Frequency Detector."

Think about it. If A has a zero crossing (or say a posedge) there is an upcount (A is ahead of B). If B has a zero crossing (or again, a posedge), there is a downcount (B is ahead of A).

When the counter is sufficiently high (overflow), A is definitely ahead, and this is the higher frequency. When the counter is sufficiently low (underflow), B is ahead and is the higher frequency.
 

I have an idea that i would like to share...
i know that a muxing clocks is not so easy.if it was meant for a FPGA i would have used BUFGMUX for glitch free switching...but for concept i will do following setup.


i request other experts to comment on its usability for given purpose.
[/img]
 

I have an idea that i would like to share...
i know that muxing clocks is not so easy.if it was meant for a FPGA i would have used BUFGMUX for glitch free switching...but for concept i will do following setup.


i request other experts to comment on its usability for given purpose.
 

Hi,
I dont like your Idea my friend. PFD needs a filter which at turns require capacitance to be used. Since you are using HDL tool it will be hard to simulate.
However I have a better Idea but has more area. Use two counters C1 and C2 one locked by CLK1 the second by CLK2. Each 8 cycles of CLK1 the C1's values is substracted from C2 value. So if the result is 1 this mean CLK2 is more speed than CLK1 and the inverse is true if the substruction is 0.

I hope you liked the Idea.

Advares.
 

I am not suggesting any use of PFD in my design...
please suggest where it will fail...
 

kvingle said:
I am not suggesting any use of PFD in my design...
please suggest where it will fail...

Hi kvingle,
Sorry, it was a reply for mrflibble's question.
Could you explain your solution ?
 

F1 and F2 are two input frequencies. two counters are clocked by them.CE is enable signal for counter. i.e. counter will work only when this signal is low.To the output of each counter a and gate is used to detect whether counter has reached max_value.(overflow)
this signal is used as enable for flip-flop(a flip-flop with enable is a flop with a 2:1 mux at its input. the CE is used as control for mux).
So when any of the counter overflows it latches '1' value to enable to corresponding tristate at the end.and this latched value in turn disables other counter.
 

kvingle said:
any input/suggestions from anybody..?
Hi kvingle,

Could you explain how your circuit wil work when you do the following:

1 - Apply F1= 1 kHz and F2 =2 kHz. Let it run for a few seconds.

2 - Apply F1= 5 kHz and F2 =2 kHz. Let it run for a few seconds.

Because as far as I can see in your current circuit, as soon as the F2 counter overflows you disable the F1 counter. And Fout = F2 in that case. So how is that F1 counter ever going to start counting again? Do you intend to periodically reset both counters? Maybe something I misunderstood about your circuit?

Added after 1 hours 5 minutes:

AdvaRes said:
Hi,
I dont like your Idea my friend. PFD needs a filter which at turns require capacitance to be used. Since you are using HDL tool it will be hard to simulate.
N. O. A PFD does not need a filter, nor does it require a capacitance, nor does a PFD have to be analog. As an example, straight from the ADF4107 datasheet I happened to be reading:

"The ADF4107 frequency synthesizer can be used to implement local oscillators in the up-conversion and down-conversion sections of wireless receivers and transmitters. It consists of a low-noise digital PFD (phase frequency detector), a precision charge pump, ..."

Maybe the confusion stems from the fact that a PFD is associated with a PLL, which in turn is associated with a loop filter (which does contain capacitance) or something?

The PFD as I meant it, is nothing more and nothing less than a state machine that compares clock edges of two input clocks, and based on that comparison does something. With a PLL like the ADF4107 above this "does something" is to let the charge pump squeeze out a little charge, which will be integrated by the external capacitance containing loop filter. In our case for the frequency comparator there is no charge pump. Instead there is a simple counter that counts up or down, depending on which of the two inputs is the one with the higher frequency.

Lets take an example with clock inputs A and B. We will use a 4 bit counter.

If input A is going faster, the counter will count up to 15 (and NOT overflow, but remain limited to 15).

If input B is going faster, the counter will count down (and NOT underflow, but remain limited to 0).

When the counter value is 15, you know that A is going faster and change the output accordingly. When the counter value is 0, you know that B is going faster. Values 1 - 14 serve to add some hysteresis, so your output will still be stable when you are comparing frequencies that are almost but not quite the same.


AdvaRes said:
However I have a better Idea but has more area. Use two counters C1 and C2 one locked by CLK1 the second by CLK2. Each 8 cycles of CLK1 the C1's values is substracted from C2 value. So if the result is 1 this mean CLK2 is more speed than CLK1 and the inverse is true if the substruction is 0.

Unfortunately, that idea is worse. Counter C1 is clocked by CLK1, and counter C2 is clocked by CLK2. Sooooo, C1 and C2 are counters in two entirely different clock domains. And then you propose to substract these two counters. Good luck with that!

To make matters even more interesting you then proceed to do the substraction every 8 cycles of CLK1. So what happens when CLK1 = 0.001 Hz and CLK2 = 10 kHz? Do I have to wait a thousand seconds of my life before I get an output? Or say if CLK1 = 0 Hz, shall I wait forever more? :cry:

"Aha!" you say, "I simply do the substraction of C1 and C2 every 8 cycles of my main fpga clock (for example 50 MHz) and everything is cool! Right?". Well, now you have a C1 counter in one clock domain, a C2 counter in another clock domain, and do the substraction in YET ANOTHER clock domain. Doubleplus good luck with that!

But since my mother always taught me "Code or GTFO!" I will post some verilog in a bit to show what I mean.
 

Hi mrflibble,
A PDF alone is useless. Such a divice indicates the more speed clock and is reset by the less speed clock.

Anyway, I gave you only the Idea and you are talking about details in the general condition. Of course you 'll face some contrains. But to overcome them the problem can be simplified by looking carefully to your requirements. This let you simpifying the implementation of the mechanism.

If you target to find a solution to the worst case you have not to wait until Counter overflow.

Second as I told you the choice of the number of cycles to wait for the next comparaison cycle and the speed of incrementing depend on your application.

This has no sens but even If CLK1 is 0 Hz it work if counter is clocked by CLK2.

"C1 counter in one clock domain, a C2 counter in another clock domain, and do the substraction in YET ANOTHER clock domain. Doubleplus good luck with that!"

Use simple synchronizers.

Dont turn around the world to go from Paris to Berlin.
 

Heya AdvaRes,

AdvaRes said:
Hi mrflibble,
A PDF alone is useless. Such a divice indicates the more speed clock and is reset by the less speed clock.

I am not quite sure I understand what you mean here. Such a device is what now?

AdvaRes said:
Anyway, I gave you only the Idea and you are talking about details in the general condition. Of course you 'll face some contrains. But to overcome them the problem can be simplified by looking carefully to your requirements. This let you simpifying the implementation of the mechanism.

Exactly! Simplify the implementation! Not to dis your proposed solution, but using 2 full counters for the sole purpose of finding out what the highest frequency is out of a set of 2 signals ... well, that is overkill. And I recognize the fact that you said "I have a solution, but it will use more area (as in resources)", but one has to draw the line somewhere. If you don't another solution is: "buy 2 frequency counters with rs-232 interface, get the readings and compare". That is not cheap in terms of resources expended, but will in all probability do the job. It however will not earn you any prizes for "Most Elegant/Efficient Solution Evar".

Using 2 full counters is useful when you are interested in the absolute frequency value of both signals. For example when you are building a frequency counter, you would sure want to know the absolute count. But the question here was to only find out which one of 2 signals has the higher frequency, in which case you are only interested in the relative frequency. As in: "what is the frequency of signal A compared to that of signal B". And to make things even simpler we don't even need to know "frequency of signal A" minus "frequency of signal B". All we need to know is ... "frequency of signal A" < "frequency of signal B".


AdvaRes said:
This has no sens but even If CLK1 is 0 Hz it work if counter is clocked by CLK2.

"C1 counter in one clock domain, a C2 counter in another clock domain, and do the substraction in YET ANOTHER clock domain. Doubleplus good luck with that!"

Use simple synchronizers.


Ah, the refreshing magic of words. :)

person #1: "I hate pointless wars!"
person #2: "Simply implement World Peace. ^_^"

Which is another way of saying "I was with you all the way up to 'simple' ". Of course you can use simple synchronizers. Except that sometimes with counter synchronization there is nothing simple about it. Is it a regular binary counter? Gray counter? Ripple counter? Why were you using a counter again? Do you really need an absolute counter? Or is this too specific? I can be generic. Me being generic is saying "make it so. fix it. problem solved". Me being specific is going into the details and solving the specific problems.

But most of all, we can happily disagree on the specifics since there is room in this world for more than 1 solution to a specific problem. The more appropriate solutions, the merrier. There is always going to be some guy out there that is going to want to use your specific solution because it happens to fit his specific requirements. :)

Dont turn around the world to go from Paris to Berlin.
Now there we can agree! Besides, I prefer Berlin to Paris. Berlin has better clubs IMO. :p
 

mrflibble said:
Because as far as I can see in your current circuit, as soon as the F2 counter overflows you disable the F1 counter. And Fout = F2 in that case. So how is that F1 counter ever going to start counting again? Do you intend to periodically reset both counters? Maybe something I misunderstood about your circuit?

Yes. I am expecting that whole circuit will be reset if user intend to apply a different set of input frequency ...
I have taken 32 bit counter arbitrarily. If we constrain the range of frequencies then it can be reduced.
Now what do you say....friend?Any suggestions?
:?:
 

Hi again mrflibble,

I am not quite sure I understand what you mean here. Such a device is what now?
It was a typing error I meant the PFD.

And to make things even simpler we don't even need to know "frequency of signal A" minus "frequency of signal B". All we need to know is ... "frequency of signal A" < "frequency of signal B".
I know that very well and that's the issue. You are not in a position to choose. In term of resources this do not need a lot of resources/area/power (Let say less than 20 flip flop).

Compared to PFD this seem big but as I said PFD is useless alone.

Why not discuss your solution and after that we compare our Ideas ?
Could you please explain how you exploit your PFD for frequency comparaison ?
 

Hi AdvaRes,

AdvaRes said:
I am not quite sure I understand what you mean here. Such a device is what now?
It was a typing error I meant the PFD.
I understood the typo's just fine. :) It was the "Such a divice indicates the more speed clock and is reset by the less speed clock." I did not understand. Such a device what?


AdvaRes said:
Why not discuss your solution and after that we compare our Ideas ?
Could you please explain how you exploit your PFD for frequency comparaison ?

Sure. Here's some verilog:

Code:
module frequency_comparator(
    input clk_sys,
    input clk_a,
    input clk_b,
    input rst_n,
    output a_is_faster
    );

reg [2:0] rsync_clk_a;
reg [2:0] rsync_clk_b;

// Resynchronize clk_a and clk_b inputs to the main clock domain.
always @(posedge clk_sys or negedge rst_n) begin
    if (~rst_n) begin
        rsync_clk_a <= 3'b000;
        rsync_clk_b <= 3'b000;
	 end else begin
        rsync_clk_a <= {rsync_clk_a[1:0], clk_a};
        rsync_clk_b <= {rsync_clk_b[1:0], clk_b};
    end
end

// Find the rising edges of clk_a and ckl_b.
// On a rising edge, edge_detected goes high for 1 main clock period.
wire edge_detected_a = (rsync_clk_a[2]) & (~rsync_clk_a[1]);
wire edge_detected_b = (rsync_clk_b[2]) & (~rsync_clk_b[1]);

thats_no_pfd thats_no_pfd(
  .clk(clk_sys),
  .rst_n(rst_n),
  .edge_detected_a(edge_detected_a),
  .edge_detected_b(edge_detected_b),
  .a_is_faster(a_is_faster)
  );

endmodule // frequency_comparator

Code:
module thats_no_pfd(
    input clk,
    input rst_n,
    input edge_detected_a,
    input edge_detected_b,
    output reg a_is_faster
    );

reg [1:0] count;
// If a is faster, this counts up. If b is faster this counts down.
// With a 2-bit counter it takes 4 sustained counts in either
// direction before the "a_is_faster" output will change. It takes 4 times edge_detected_a
// before "a_is_faster" goes high, or 4 times edge_detected_b before "a_is_faster" goes
// low. Change counter size to adjust for preferred level of hysteresis.

wire count_max =  (& count);
wire count_min = ~(| count);

always @(posedge clk or negedge rst_n) begin
    if (~rst_n) begin
        a_is_faster <= 1'b0;
        count <= 0;
    end else begin
      case({edge_detected_a, edge_detected_b})
        2'b00: ; // nothing happening...
        2'b11: ; // a and b both changed, so no DIFFERENCE count
        2'b10: begin // a faster
                 if (count_max)
                      a_is_faster <= 1'b1;
                 else
                      count <= count + 1; 
              end
        2'b01: begin // b faster
                 if (count_min)
                     a_is_faster <= 1'b0;
                 else
                     count <= count - 1;
               end
        default: ;
        endcase
    end
end

endmodule // thats_no_pfd

And here's a testbench to take it for a spin:
Code:
module bench_frequency_comparator;

	// Inputs
	reg clk_sys;
	reg clk_a;
	reg clk_b;
	reg rst_n;

	// Outputs
	wire a_is_faster;

   // Helper signals
	reg swap_clocks;
	wire swapped_clk_a = (swap_clocks == 1'b1) ? (clk_b) : (clk_a);
	wire swapped_clk_b = (swap_clocks == 1'b1) ? (clk_a) : (clk_b);

	// Instantiate the Unit Under Test (UUT)
	frequency_comparator uut (
		.clk_sys(clk_sys), 
		.clk_a(swapped_clk_a), 
		.clk_b(swapped_clk_b), 
		.rst_n(rst_n), 
		.a_is_faster(a_is_faster)
	);

	initial begin
		// Initialize Inputs
		clk_sys = 0;
		clk_a = 0;
		clk_b = 0;
		rst_n = 0;
		swap_clocks = 0;

		// Wait 100 ns for global reset to finish
		#100;
		rst_n = 1;
	end

        // 50 MHz main clock
        always begin
            # 10 clk_sys = !clk_sys;
        end

        // 24.390 MHz clock A
        always begin
            # 41 clk_a = !clk_a;
        end

        // 23.810 MHz clock B
        always begin
            # 42 clk_b = !clk_b;
        end

        // every 10 us swap the test clocks around to see how the output recovers
        always begin
            # 10000 swap_clocks = !swap_clocks;
        end

      
endmodule // bench_frequency_comparator

Hope that clarifies what I tried to communicate in an earlier post:
mrflibble said:
No need for analog, the PFD can be done with gates + flipflops.

From the wiki (link is in my previous post): "A more complex digital PD uses a simple state machine to determine which of the two signals has a zero-crossing earlier or more often. This brings the PLL into lock even when it is off frequency and is known as a Phase Frequency Detector."

You can change the testbench to see how it handles DC or higher frequency as well as when the 2 input frequencies are close together. I hope this clarifies things somewhat. :)
 
  • Like
Reactions: JHEnt

    JHEnt

    Points: 2
    Helpful Answer Positive Rating
Aha !
So that's what you call a PFD.

It was the "Such a divice indicates the more speed clock and is reset by the less speed clock." I did not understand. Such a device what?

The figure below shows a typical PFD. I guess you understant what I mean now.


You are thinking HDL that's why you didn't get my reply.
Actually If you synthesis and look at the result you'll note that your circuits is too complex compared that I'm proposing. Your circuit will also have synchronizers.
In addition you used an FSM, many registers, at least one counter and one comparator, and many Multiplexors.
Imagine the area and the power needed to do that.
Further more datapath is huge so the compared frequency is limited by the delay in the datapath.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top