Why using two flip-flops instead of one in this Verilog HDL code? - verilog

This code is a button debouncer.
But I can't understand why there are two flips flops :
reg PB_sync_0; always #(posedge clk) PB_sync_0 <= ~PB; // invert PB to make PB_sync_0 active high
reg PB_sync_1; always #(posedge clk) PB_sync_1 <= PB_sync_0;
Why the autor of this code did not write this ?
reg PB_sync_1; always #(posedge clk) PB_sync_1 <= ~PB;
Here is the full code:
module PushButton_Debouncer(
input clk,
input PB, // "PB" is the glitchy, asynchronous to clk, active low push-button signal
// from which we make three outputs, all synchronous to the clock
output reg PB_state, // 1 as long as the push-button is active (down)
output PB_down, // 1 for one clock cycle when the push-button goes down (i.e. just pushed)
output PB_up // 1 for one clock cycle when the push-button goes up (i.e. just released)
);
// First use two flip-flops to synchronize the PB signal the "clk" clock domain
reg PB_sync_0; always #(posedge clk) PB_sync_0 <= ~PB; // invert PB to make PB_sync_0 active high
reg PB_sync_1; always #(posedge clk) PB_sync_1 <= PB_sync_0;
// Next declare a 16-bits counter
reg [15:0] PB_cnt;
// When the push-button is pushed or released, we increment the counter
// The counter has to be maxed out before we decide that the push-button state has changed
wire PB_idle = (PB_state==PB_sync_1);
wire PB_cnt_max = &PB_cnt; // true when all bits of PB_cnt are 1's
always #(posedge clk)
if(PB_idle)
PB_cnt <= 0; // nothing's going on
else
begin
PB_cnt <= PB_cnt + 16'd1; // something's going on, increment the counter
if(PB_cnt_max) PB_state <= ~PB_state; // if the counter is maxed out, PB changed!
end
assign PB_down = ~PB_idle & PB_cnt_max & ~PB_state;
assign PB_up = ~PB_idle & PB_cnt_max & PB_state;
endmodule
Thanks !

The autor of this code uses 2 flip-flops in order to synchronize PB signal into clk domain.
As he mentioned in a comment "PB" is the glitchy, asynchronous to clk.
Not synchronizing a signal on a clock domain transition may cause metastability in the system, as toolic referenced en.wikipedia.org/wiki/Metastability_in_electronics

Related

Trouble understanding simulation/module behavior

I implemented a very simple counter with preset functionality (code reproduced below).
module counter
#(
parameter mod = 4
) (
input wire clk,
input wire rst,
input wire pst,
input wire en,
input wire [mod - 1:0] data,
output reg [mod - 1:0] out,
output reg rco
);
parameter max = (2 ** mod) - 1;
always #* begin
if(out == max) begin
rco = 1;
end else begin
rco = 0;
end
end
always #(posedge clk) begin
if(rst) begin
out <= 0;
end else if(pst) begin
out <= data;
end else if(en) begin
out <= out + 1;
end else begin
out <= out;
end
end
endmodule
I am having trouble understanding the following simulation result. With pst asserted and data set to 7 on a rising clock edge, the counter's out is set to data, as expected (first image below. out is the last signal, data is the signal just above, and above that is pst.). On the next rising edge, I kept preset asserted and set data to 0. However, out does not follow data this time. What is the cause of this behavior?
My thoughts
On the rising clock edge where I set data to 0, I notice that out stays at 7, and doesn't increment to 8. So I believe that the counter is presetting, but with the value 7, not 0. If I move the data transition from 7 to 0 up in time, out gets set to 0 as expected (image below). Am I encountering a race condition?
Testbenches
My initial testbench code that produced the first image is reproduced below. I show the changes I made to get coherent results as comments.
parameter mod = 4;
// ...
reg pst;
reg [mod - 1:0] data;
// ...
#(posedge clk); // ==> #(negedge clk)
data = 7;
pst = 1;
#(posedge clk); // ==> #(negedge clk)
data 0;
pst = 1;
#(posedge clk); // ==> #(negedge clk)
pst = 0;
#(posedge clk);
// ...
You have a race condition test bench. The Verilog scheduler is allowed to evaluate any # triggered in the time step in any order it chooses. All code after the granted # will execute until it hits another time blocking statement. In your waveform it looks like data and pst from the from the test bench are sometimes being assigned before the design samples them and sometimes after.
The solution is simple, use non-blocking assignments (<=). Refer to What is the difference between = and <= in Verilog?
#(posedge clk);
data <= 7;
pst <= 1;
#(posedge clk);
data <= 0;
pst <= 1;
#(posedge clk);
pst <= 0;
#(posedge clk);
I am able to obtain correct, predictable behavior if I modify my testbench to only modify input signals to my counter on falling clock edges rather than on rising clock edges (as it should be anyways). My best guess as to why the above behavior was occurring is that changing input signals at the same time the counter module is programmed to sample its inputs leads to undefined simulator behavior.

4 bit countetr using verilog not incrementing

Sir,
I have done a 4 bit up counter using verilog. but it was not incrementing during simulation. A frequency divider circuit is used to provide necessory clock to the counter.please help me to solve this. The code is given below
module my_upcount(
input clk,
input clr,
output [3:0] y
);
reg [26:0] temp1;
wire clk_1;
always #(posedge clk or posedge clr)
begin
temp1 <= ( (clr) ? 4'b0 : temp1 + 1'b1 );
end
assign clk_1 = temp1[26];
reg [3:0] temp;
always #(posedge clk_1 or posedge clr)
begin
temp <= ( (clr) ? 4'b0 : temp + 1'b1 );
end
assign y = temp;
endmodule
Did you run your simulation for at least (2^27) / 2 + 1 iterations? If not then your clk_1 signal will never rise to 1, and your counter will never increment. Try using 4 bits for the divisor counter so you won't have to run the simulation for so long. Also, the clk_1 signal should activate when divisor counter reaches its max value, not when the MSB bit is one.
Apart from that, there are couple of other issues with your code:
Drive all registers with a single clock - Using different clocks within a single hardware module is a very bad idea as it violates the principles of synchronous design. All registers should be driven by the same clock signal otherwise you're looking for trouble.
Separate current and next register value - It is a good practice to separate current register value from the next register value. The next register value will then be assigned in a combinational portion of the circuit (not driven by the clock) and stored in the register on the beginning of the next clock cycle (check code below for example). This makes the code much more clear and understandable and minimises the probability of race conditions and unwanted inferred memory.
Define all signals at the beginning of the module - All signals should be defined at the beginning of the module. This helps to keep the module logic as clean as possible.
Here's you example rewritten according to my suggestions:
module my_counter
(
input wire clk, clr,
output [3:0] y
);
reg [3:0] dvsr_reg, counter_reg;
wire [3:0] dvsr_next, counter_next;
wire dvsr_tick;
always #(posedge clk, posedge clr)
if (clr)
begin
counter_reg <= 4'b0000;
dvsr_reg <= 4'b0000;
end
else
begin
counter_reg <= counter_next;
dvsr_reg <= dvsr_next;
end
/// Combinational next-state logic
assign dvsr_next = dvsr_reg + 4'b0001;
assign counter_next = (dvsr_reg == 4'b1111) ? counter_reg + 4'b0001 : counter_reg;
/// Set the output signals
assign y = counter_reg;
endmodule
And here's the simple testbench to verify its operation:
module my_counter_tb;
localparam
T = 20;
reg clk, clr;
wire [3:0] y;
my_counter uut(.clk(clk), .clr(clr), .y(y));
always
begin
clk = 1'b1;
#(T/2);
clk = 1'b0;
#(T/2);
end
initial
begin
clr = 1'b1;
#(negedge clk);
clr = 1'b0;
repeat(50) #(negedge clk);
$stop;
end
endmodule

Clock Domain Crossing for Pulse and Level Signal

For pulse we use Pulse-Synchronizer and for Level Signal we use 2-flop synchronizer but what if the signal can be of Pulse or Level behaviour. Is there any way to synchronize that?
Yes, you can but the solution needs to be based on the width of the input pulse relative to the output clock.
When the output clock is very slow, and you have a pulse, you need to add an inline pulse stretcher that operates in the input clock domain. The stretch is defined by the bit width of stretch_out below and "MUST" be greater than one clock on the output clk domain.
reg [3:0] stretch_out;
always # (posedge inclk)
begin
stretch_out <= in_signal ? 4'b1111 : {stretch_out[2:0],1'b0};
end
Now you can just use your double flop synchronizer.
reg [1:0] out_sync;
always # (posedge outclk)
begin
out_sync <= {out_sync[0],stretch_out[3]};
end
This should synchronize a level and pulse from a fast domain into a slow domain.
The only issue, is that you will be adding more than just your usual two flop latency.
You could asynchronously set using the signal in the destination domain, synchronize using dual flops, and then detect the rising edge. Should work for both short pulses and long levels.
// Prevent DRC violations if using scan
wire in_signal_n = scan_mode ? 1'b1 : !signal_in;
// Following code creates a flop with both async setb and resetb
reg sig_n_async;
always # ( posedge outclk or negedge reset_n or negedge in_signal_n)
if (!reset_n)
sig_n_async <= 0;
else if (!in_signal_n)
sig_n_async <= 1;
else
sig_n_async <= 0;
// Synchronizer
reg [1:0] out_sync;
always # (posedge outclk or negedge reset_n)
if (!reset_n)
out_sync <= 0;
else
out_sync <= {out_sync[0],sig_n_async};
// Rising edge
reg out_sync_del;
always # (posedge outclk or negedge reset_n)
if (!reset_n)
out_sync_del <= 0;
else
out_sync_del <= out_sync[1];
wire signal_out = out_sync[1] & !out_sync_del;

1second down counter with initial value verilog code

I want to write the code of 1-second down counter that get the initial value from outside and count it down till 0. but there is a problem. How can I get the initial value. i tried some ways but ....
here is the code:
module second_counter ( input clk,
input top_num,
output reg [3:0] sec_num
);
parameter clk_frequency = 25;
reg [31:0]cnt;
wire [3:0]sec;
/// how can get the top_num and count it down.
assign sec=top_num;
always #(posedge clk)
begin
if (cnt==clk_frequency)
begin
sec <= sec -1;
cnt<=0;
end
else
cnt <=cnt+1;
end
What you basically need is a reset signal. Just like clock, reset is to be added in the sensitivity list.
After instantiation of module, you must apply a reset signal to initialize all the internal variables and registers of design.
Following code gives you initial value of cnt by reset application. This is an active low reset.
module second_counter ( input clk, input reset, input top_num, output reg [3:0] sec_num );
parameter clk_frequency = 25;
reg [31:0]cnt;
// wire [3:0]sec;
reg [3:0] sec;
///
// assign sec=top_num;
always #(posedge clk, negedge reset)
begin
if(!reset)
begin
cnt<=0; // initialize all internal variables and registers
sec<=0;
end
else
begin
if(sec == 0) // latch input when previous count is completed
sec<=top_num;
if (cnt==clk_frequency)
begin
sec <= sec -1;
cnt<=0;
end
else
cnt <=cnt+1;
end
end
Note that this is an asynchronous reset, means it does not depend on clocking signal. Synchronous reset is the one which only affects the registers at the clock pulse.
Edit:
Regarding to sec, I have modified the code. Now the design latches the inputs for one clock cycle and counts down to zero. Once the counter reaches zero, it again latches the input to re-count to zero.
Note that you cannot do like latching top_num at every clock and counting through zero (since top_num can change at every pulse). For latching at every clock pulse, you need more complex logic implementation.

Delay using Verilog for PR controller

i want to shift a signal by fixed number of clock cycles. I receive the signal from adc. kindly let me know how to implement this
HINT: Not a full answer
A 8 bit flip-flop in verilog might look like:
reg [7:0] a;
always #(posedge clk, negedge rst_n) begin
if (~rst_n) begin
// Active Low Reset condition
a <= 'b0;
end
else begin
a <= input_eight_bit;
end
end
To delay for multiple clock cycles you need multiple flip-flops feeding from one to the next. This creates a pipe line or delay line.

Resources