Search code examples
veriloghdl

How can I create a latch in Verilog


I have a CPLD with a digital input representing a reset button. When the reset button is pressed, the signal goes high. What I need to do is have a register whose value tells if the button has ever been pressed. Basically a latch. When the button goes high, a latch register goes high and stays high forever.

I thought this would be straightforward, but I got a bunch of warnings when I tried to code it up. A little Googling showed "Don't make latches in HDL! Bad practice!", but I don't really see the alternative here.

Here's my attempt. clk_10m is a fast free-running clock, pwr_off_req is the button input.

reg pwr_off_req_latched = 0;

always @ (clk_10m or pwr_off_req) begin

   if (pwr_off_req == 1'b1)
      pwr_off_req_latched <= 1'b1;   
   else
      pwr_off_req_latched <= pwr_off_req_latched;
      // I tried this to make sure it's always set to something          
end

Solution

  • Can you assume that the pulse length of the button press is much longer than the clock frequency of your device? If it's a physical button I think that is a very safe assumption. In that case I think this would work perfectly fine:

    always @(clk_10m) 
       pwr_off_req_latched <= power_off_req_latched | power_off_req;