---
# System prepended metadata

title: 02. Verilog 設計層次
tags: [語法教學, Verilog]

---

# Verilog 設計層次

## 1. Gate Level (邏輯閘層次)
- **使用==邏輯閘==設計電路，==輸入/輸出==由邏輯閘的定義決定**
- **語法：==`<gate> gate_name (<net1>, <net2>, ...);`==**
:::success
```verilog
not  g1(not_a , a);
or   g2(or_a  , a1, a2, /*...*/, a_n);
and  g3(and_a , a1, a2, /*...*/, a_n);
nor  g4(nor_a , a1, a2, /*...*/, a_n);
nand g5(nand_a, a1, a2, /*...*/, a_n);
xor  g6(xor_a , a1, a2, /*...*/, a_n);
xnor g7(xnor_a, a1, a2, /*...*/, a_n);
```
:::

:::info
#### ex：2對1多工器
```verilog=
module mux(out, a, b, sel);
    // 輸入/輸出 敘述
    input a, b, sel;
    output out;
    // 變數設定  敘述
    wire out;
    wire sel_b, a_out, b_out;
    // 電路設計  敘述
    not g1(sel_b,sel);
    and g2(a_out, a, sel);
    and g3(b_out, b, sel_b);
    or  g4(out, a_out, b_out);
endmodule
```
:::

## 2. Dataflow Level (資料流層次)
- **使用 ==邏輯==/==數學 符號== 設計電路，==`assign`== 用來連接 net**
- **語法：==`assign net = <expression>;`==**
:::success
```verilog
// 邏輯運算
assign not_gate  = ~a;
assign or_gate   = a | b; 
assign and_gate  = a & b;
assign nor_gate  = ~(a | b);
assign nand_gate = ~(a & b);
assign xor_gate  = a ^ b;
assign xnor_gate = ~(a ^ b);

// 加減乘除
assign sum = a + b;
assign sub = a - b;
assign product = a * b;
assign quotient = a / b;
assign remainder = a % b;

//三元運算子
assign _wire_ = (a > b) ? a : b;
```
:::
:::info
#### ex：2對1多工器
```verilog=
module mux( 
    // 輸入/輸出 敘述
    output out, 
    input a, b, sel
);
    // 變數設定  敘述
    wire out;
    // 電路設計  敘述
    assign out = (sel)? a:b;
endmodule
```
:::

## 3. Behavior Level (行為層次)
- **使用==高階程式語法==設計電路，用於設計==循序邏輯電路==**
- **語法：==`always @(<trig) begin /*...*/ end`==**
:::success
#### ● Trigger
```verilog
always @(<trig>) begin
    // 程式區塊
end
```

|      觸發方式      |             語法              |                                註解                                |
|:------------------:|:-----------------------------:|:------------------------------------------------------------------:|
| **邊緣觸發(正緣)** |  **`always @(posedge clk)`**  |                          **==循序邏輯==**                          |
| **邊緣觸發(負緣)** |  **`always @(negedge clk)`**  |                          **==循序邏輯==**                          |
|    **準位觸發**    |       **`always @(a)`**       | **當 `a` 由 ==$0\rightarrow1$==, ==$1\rightarrow0$== 時 ==觸發==** |
|    **多個觸發**    | **`always @(a or b or clk)`** |                 **邊緣觸發、準位觸發==不要混用==**                 |
|    **全域觸發**    |       **`always @(*)`**       |                          **==組合邏輯==**                          |
:::

:::info
#### ex：2對1多工器
```verilog=
module mux( 
    // 輸入/輸出 敘述
    output out, 
    input a, b, sel
);
    // 變數設定  敘述
    wire out;
    reg register;
    // 電路設計  敘述
    always @(*) begin
        if (sel) begin
            register <= a;
        end
        else begin
            register <= b;
        end
    end
    // 可以組合其他設計架構
    assign out = register;
endmodule
```
:::

---