關鍵詞:if,選擇器
條件語句
條件(if)語句用於控製執行語句要根據條件判斷來確定是否執行。
條件語句用關鍵字 if 和 else 來聲明,條件表達式必須在圓括號中。
條件語句使用結構說明如下:
if (condition1) true_statement1 ; else if (condition2) true_statement2 ; else if (condition3) true_statement3 ; else default_statement ;
- if 語句執行時,如果 condition1 為真,則執行 true_statement1 ;如果 condition1 為假,condition2 為真,則執行 true_statement2;依次類推。
- else if 與 else 結構可以省略,即可以隻有一個 if 條件判斷和一組執行語句 ture_statement1 就可以構成一個執行過程。
- else if 可以疊加多個,不僅限於 1 或 2 個。
- ture_statement1 等執行語句可以是一條語句,也可以是多條。如果是多條執行語句,則需要用 begin 與 end 關鍵字進行說明。
下麵代碼實現了一個 4 路選擇器的功能。
實例
module mux4to1(
input [1:0] sel ,
input [1:0] p0 ,
input [1:0] p1 ,
input [1:0] p2 ,
input [1:0] p3 ,
output [1:0] sout);
reg [1:0] sout_t ;
always @(*) begin
if (sel == 2'b00)
sout_t = p0 ;
else if (sel == 2'b01)
sout_t = p1 ;
else if (sel == 2'b10)
sout_t = p2 ;
else
sout_t = p3 ;
end
assign sout = sout_t ;
endmodule
input [1:0] sel ,
input [1:0] p0 ,
input [1:0] p1 ,
input [1:0] p2 ,
input [1:0] p3 ,
output [1:0] sout);
reg [1:0] sout_t ;
always @(*) begin
if (sel == 2'b00)
sout_t = p0 ;
else if (sel == 2'b01)
sout_t = p1 ;
else if (sel == 2'b10)
sout_t = p2 ;
else
sout_t = p3 ;
end
assign sout = sout_t ;
endmodule
testbench 代碼如下:
實例
`timescale 1ns/1ns
module test ;
reg [1:0] sel ;
wire [1:0] sout ;
initial begin
sel = 0 ;
#10 sel = 3 ;
#10 sel = 1 ;
#10 sel = 0 ;
#10 sel = 2 ;
end
mux4to1 u_mux4to1 (
.sel (sel),
.p0 (2'b00), //path0 are assigned to 0
.p1 (2'b01), //path1 are assigned to 1
.p2 (2'b10), //path2 are assigned to 2
.p3 (2'b11), //path3 are assigned to 3
.sout (sout));
//finish the simulation
always begin
#100;
if ($time >= 1000) $finish ;
end
endmodule
module test ;
reg [1:0] sel ;
wire [1:0] sout ;
initial begin
sel = 0 ;
#10 sel = 3 ;
#10 sel = 1 ;
#10 sel = 0 ;
#10 sel = 2 ;
end
mux4to1 u_mux4to1 (
.sel (sel),
.p0 (2'b00), //path0 are assigned to 0
.p1 (2'b01), //path1 are assigned to 1
.p2 (2'b10), //path2 are assigned to 2
.p3 (2'b11), //path3 are assigned to 3
.sout (sout));
//finish the simulation
always begin
#100;
if ($time >= 1000) $finish ;
end
endmodule
仿真結果如下。
由圖可知,輸出信號與選擇信號、輸入信號的狀態是相匹配的。
事例中 if 條件每次執行的語句隻有一條,沒有使用 begin 與 end 關鍵字。但如果是 if-if-else 的形式,即便執行語句隻有一條,不使用 begin 與 end 關鍵字也會引起歧義。
例如下麵代碼,雖然格式上加以區分,但是 else 對應哪一個 if 條件,是有歧義的。
實例
if(en)
if(sel == 2'b1)
sout = p1s ;
else
sout = p0 ;
if(sel == 2'b1)
sout = p1s ;
else
sout = p0 ;
當然,編譯器一般按照就近原則,使 else 與最近的一個 if(例子中第二個 if)相對應。
但顯然這樣的寫法是不規範且不安全的。
所以條件語句中加入 begin 與 and 關鍵字就是一個很好的習慣。
例如上述代碼稍作修改,就不會再有書寫上的歧義。
實例
if(en) begin
if(sel == 2'b1) begin
sout = p1s ;
end
else begin
sout = p0 ;
end
end
if(sel == 2'b1) begin
sout = p1s ;
end
else begin
sout = p0 ;
end
end