DAY 13
1
Software Development

## Latch 的生成條件

### 第一種：if 語句結構不完整

``````module latch_test(
in,
en,
out
);
input  in;
input  en;
output out;
reg    out;

always@(*)begin
if(en) out = in;//no else
end

endmodule
``````

SOL1：補齊 else 語句

``````module latch_test(
in,
en,
out
);
input  in;
input  en;
output out;
reg    out;

always@(*)begin
if(en) out = in;
end

endmodule
``````

SOL2：在 always 內最上方加上初值

``````module latch_test(
in,
en,
out
);
input  in;
input  en;
output out;
reg    out;

always@(*)begin
out = 1'b0;//initialization
if(en) out = in;
end

endmodule
``````

``````module latch_test(
in1,
in2,
en,
out1,
out2
);
input  in1;
input  in2;
input  en;
output out1;
output out2;
reg    out1;
reg    out2;

always@(*)begin
if(en) out1 = in1;
else   out2 = in2;
end

endmodule
``````

``````module latch_test(
in1,
in2,
en,
out1,
out2
);
input  in1;
input  in2;
input  en;
output out1;
output out2;
reg    out1;
reg    out2;

always@(*)begin
if(en)begin
out1 = in1;
end
else begin
out2 = in2;
end
end

endmodule
``````

`這裡值得注意的是，在循序邏輯中（clock觸發），不完整的 if-else 並不會生成 latch，因為 register 具有儲存前態的功能，並只有在正負緣才會改變值~`

### 第二種：case 語句結構不完整

``````module latch_test(
in1,
in2,
sel,
out
);
input       in1;
input       in2;
input [1:0] sel;
output      out;
reg         out;

always@(*)begin
case(sel)
2'd0:out = in1;
2'd1:out = in2;
endcase
end

endmodule
``````

``````module latch_test(
in1,
in2,
sel,
out
);
input       in1;
input [1:0] sel;
output      out;
reg         out;

always@(*)begin
case(sel)
2'd0:out = in1;
2'd1:out = in2;
endcase
end

endmodule
``````

### 第三種：使變數等於自己時或是判斷元素有自己時

``````reg a;
reg b;

always@(*)begin
if(a | b)a = 1'b0;
else     a = 1'b1;
end
``````

``````reg a;
reg b;
always@(*)begin
if(b)a = a;
else a = a + 1'b1;
end
``````

``````wire a;
wire c;
reg b;
assign a = (a & b)?(1'b0):(1'b1);
assign c = (a & b)?(c):(1'b0);
``````

EX:

``````reg a;
reg b;
reg a_temp;

always@(posedge clkSys)begin
a_temp <= a;
end

always@(*)begin
if(a_temp | b)a = 1'b0;
else          a = 1'b1;
end
``````

### 第四種：always 觸發條件不完整

`等號右邊的所有變數或判斷元素都應蓋列入 alway 觸發條件中`

``````module latch_test(
in1,
in2,
sel,
out
);
input  in1;
input  in2;
input  sel;
output out;
reg    out;

always@(in1 or in2)begin
if(sel)out = in1;
else   out = in2;
end

endmodule
``````

``````module latch_test(
in1,
in2,
sel,
out
);
input  in1;
input  in2;
input  sel;
output out;
reg    out;

always@(in1 or in2 or sel)begin//add sel
if(sel)out = in1;
else   out = in2;
end

endmodule
``````