Electronic – When should I use negedge on a clock signal

digital-logicfpgaverilog

I was reading about block ram and I came across the following post. I notice here that whoever wrote the code is using negedge on the clock signal. Thus far almost all the examples I have seen of verilog use posedge on clock signals. In fact I have not really seen any always blocks with negedge specified. I am just wondering when you would want to use that and why might the code bellow contain negedge?

module RAM_param(clk, addr, read_write, clear, data_in, data_out);
    parameter n = 4;
    parameter w = 8;

    input clk, read_write, clear;
    input [n-1:0] addr;
    input [w-1:0] data_in;
    output reg [w-1:0] data_out;

    reg [w-1:0] reg_array [2**n-1:0];

    integer i;
    initial begin
        for( i = 0; i < 2**n; i = i + 1 ) begin
            reg_array[i] <= 0;
        end
    end

    always @(negedge(clk)) begin
        if( read_write == 1 )
            reg_array[addr] <= data_in;
        if( clear == 1 ) begin
            for( i = 0; i < 2**n; i = i + 1 ) begin
                reg_array[i] <= 0;
            end
        end
        data_out = reg_array[addr];
    end
endmodule

Best Answer

If you are a novice in digital design, I would recommend that you only use negative edge-triggered register for interfacing to other circuits where this is required to get the timing right. An example of this is a DDR interface as @Paebbels mentioned in his comment.

Of course, if you are an experienced digital designer you could use a negative edge-triggered register in an otherwise positive edge-triggered design to interface between aligned clock domains.

The main point to remember is that you should not mix positive and negative edge-triggered registers in a design unless you are absolutely sure you know what you are doing, otherwise this may cause bugs that can be very hard to find.

P.S. The code you show will by most synthesis tools not be implemented as a blockram because of the clear signal setting the content to zero. It will most likely be implemented in discrete registers and be very slow.

Edit: Another possibility of using a negative edge-triggered clock in a positive edge-triggered design is on a synchronous block ram. If you have a synchronous block ram in between two positive edge-triggered registers and you clock the block ram on the negative edge, you circumvent the one clock cycle delay of the otherwise synchronous block ram.