# How to change reg in two different always blocks?

How can I change/alter a register's value in two different always blocks for synthesizeability?

For example:

reg temp;

always @(posedge clk1) begin
if(...) temp = 0;
end

always @(posedge clk2) begin
if(...) temp = 1;
end

• – Dave Tweed Nov 10 '14 at 12:30

For synthesis, each always @(posedge clk) block needs to follow the pattern of a D flip-flop, otherwise the synthesis tool won't recognize it. So the problem becomes, you have two conditions where you need to change the value of the register (temp), but temp can only have one driver. This problem gets even worse when you have two different clock domains (as in your example, clk1 and clk2).

Fundamentally you can't have a flip-flop in two different clock domains, so the synthesis tool doesn't know if the temp flip-flop should be clocked by clk1 or clk2. That's why this code cannot be synthesized: there's no way to implement this design in hardware.

Crossing two different clock domains is tricky, in your example you would have to split temp into clk1_temp and clk2_temp,

// clock domain clk1
reg clk1_temp;
wire clk1_tempClear;
wire clk1_tempSet;

// clock domain clk2
reg clk2_temp;
wire clk2_tempClear;
wire clk2_tempSet;

// clock domain clk1
always @(posedge clk1) begin
if (clk1_tempClear) begin
clk1_temp <= 0;
end;
if (clk1_tempSet) begin
clk1_temp <= 1;
end;
end

// clock domain clk2
always @(posedge clk2) begin
if (clk2_tempClear) begin
clk2_temp <= 0;
end;
if (clk2_tempSet) begin
clk2_temp <= 1;
end;
end


Now you have two separate flip flops, one is clocked by clk1 and drives clk1_temp, the other flip-flop is clocked by clk2 and drives clk2_temp.

In practical use, there's usually many signals that have to cross from one clock domain into the other. See my answer about crossing clock domains: fpga verilog dual access

It's not possible to drive one output from two always blocks, and it's especially not possible to drive one output from two different clock domains.

What I would suggest doing is generating a 'set' signal in one domain and a 'reset' signal in the other domain, synchronizing these across the domains, and then instantiating some logic to control a flip-flop based on these signals. The 'set' and 'reset' signals could be encoded as a level in a short pulse, or as a transition in a signal that gets inverted on each event. The transition can be extracted back out as a pulse after synchronization.