# to generate a digital signal

Status
Not open for further replies.

#### pushpa

##### Newbie level 3
Hi,
I have two clks, Clk1 and Clk2. I want to generate an output signal X= 1 when Clk1 is ahead of Clk2 and X=0 when Clk1 is behind Clk2.

##### Full Member level 4
Hi pushpa,

Suppose the period of the 2 clk is same.

You can generate 2 edge detect signals(just xor the non-pipe version with piped version), clk1_edge, clk2_edge. Then,

always@(clk1_edge, clk2_edge)
if(clk1_edge && !clk2_edge)
X = 1;
else
x = 0;

### pushpa

points: 2

#### tarkyss

##### Full Member level 6
how to test which is ahead,
i am not sure i understand your question correcttly.
if clk1 is ahead of clk2, but for the next period of clk1, it maybe behind clk2
the frenquency of the two clock is the same?
maybe you can try as follow
always(@ posedge clk1)
if(clk2)
x<=1'b0;
else
x<=1'b1;
but before you decide to do as above, maybe you must use two flip-flop to synchronize clk2 with clk1

#### nand_gates

Its very simple you just need to sample one clock by the othere!
Here it is!!

Code:
timescale 1ns/1ps
module phase_comp(
// Outputs
x_out,
// Inputs
clk1, clk2
);
input clk1, clk2;
output      x_out;
reg         clk2_r, clk2_rr;

assign      x_out = clk2_rr;
always @(posedge clk1) begin
clk2_r <= clk2;
clk2_rr <= clk2_r;
end
endmodule // phase_comp

module test();
reg                  clk1;
reg                  clk2;
wire                 x_out;

phase_comp phase_comp(
// Outputs
.x_out         (x_out),
// Inputs
.clk1          (clk1),
.clk2          (clk2));
reg         clk;
reg [1:0]   count;
reg         sel;

always @(count or sel) begin
clk1 <= sel ? count[0] : count[1];
clk2 <= sel ? count[1] : count[0];
end

initial begin
$shm_open("WAVEFORM");$shm_probe(test, "AS");
count = 0;
sel = 0;
clk = 0;
#400;
sel = 1;
#400;
\$finish;
end // initial begin
always @(posedge clk) begin
count[0] <= count[1];
count[1] <= ~count[0];
end

always #5 clk = ~clk;
endmodule // test`
Here I am assuming that the clks are asynchronous hence the double flop
synchronizer.

#### jarodz

##### Full Member level 1
hi, nand_gates

Your assumption is that the two clock are the same in frequence and different in phase.

You use one clock to sample the other clock level.
Then it is to decise which clock is leading by the sampled level(0/1).

When the phase between two clocks is very small.
the result may wrong. In this situation, it is no matter to find which one is leading extractly.

But I still have a question that will the level of sample signal be high or low always?
Or it is changed in each one/two/three cycles(it is not stable)?

Sincerely,
Jarod

#### tarkyss

##### Full Member level 6
yes i think so
for clk1, clk2 is a asynchronism signal

#### beckchm

##### Banned
The frequency of the two clk must be comparable ,if not ,the question is meanless.

Status
Not open for further replies.