Verilog刷题[hdlbits] :Always if2

题目:Always if2

A common source of errors: How to avoid making latches
一个常见的错误来源:如何避免产生latches

When designing circuits, you must think first in terms of circuits:
在设计电路时,必须首先考虑电路:

  • I want this logic gate
    我想要这个逻辑门
  • I want a combinational blob of logic that has these inputs and produces these outputs
    我想要一个有这些输入并产生这些输出的组合逻辑团
  • I want a combinational blob of logic followed by a set of flip-flops
    我想要一个逻辑组合,后面跟着一组flip-flops

What you must not do is write the code first, then hope it generates a proper circuit.
你不能做的是先写代码,然后希望它能产生一个合适的电路。

  • If (cpu_overheated) then shut_off_computer = 1;
  • If (~arrived) then keep_driving = ~gas_tank_empty;

Syntactically-correct code does not necessarily result in a reasonable circuit (combinational logic + flip-flops). The usual reason is: “What happens in the cases other than those you specified?”. Verilog’s answer is: Keep the outputs unchanged.
语法正确的代码不一定产生合理的电路(组合逻辑+触发器)。通常的原因是:“除了你指定的那些情况之外,会发生什么?”Verilog的答案是:保持输出不变。

This behaviour of “keep outputs unchanged” means the current state needs to be remembered, and thus produces a latch. Combinational logic (e.g., logic gates) cannot remember any state. Watch out for Warning (10240): … inferring latch(es)" messages. Unless the latch was intentional, it almost always indicates a bug. Combinational circuits must have a value assigned to all outputs under all conditions. This usually means you always need else clauses or a default value assigned to the outputs.
这种“保持输出不变”的行为意味着需要记住当前状态,从而产生锁存。组合逻辑(例如,逻辑门)不能记住任何状态。注意警告(10240):…推断latch消息。除非latch是故意的,否则它几乎总是表明有bug。在任何条件下,组合电路的所有输出都必须有一个值。这通常意味着您总是需要else子句或为输出分配默认值。

Demonstration

示范

The following code contains incorrect behaviour that creates a latch. Fix the bugs so that you will shut off the computer only if it’s really overheated, and stop driving if you’ve arrived at your destination or you need to refuel.
以下代码包含创建latch的不正确行为。修复这些漏洞,这样你就只会在电脑真的过热时关闭电脑,当你到达目的地或需要加油时就不要开车了。
在这里插入图片描述

组合逻辑中,如果if缺少else语句,或是自己赋值给自己的情况就会产生latch。为了避免latch产生,if需要加上else语句,覆盖所有可能。

// synthesis verilog_input_version verilog_2001
module top_module (
    input      cpu_overheated,
    output reg shut_off_computer,
    input      arrived,
    input      gas_tank_empty,
    output reg keep_driving  ); //

    always @(*) begin
        if (cpu_overheated)
           shut_off_computer = 1;
        else
            shut_off_computer = 0;
    end

    always @(*) begin
        if (~arrived)
           keep_driving = ~gas_tank_empty;
        else
            keep_driving = 0;
    end

endmodule
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值