组合逻辑代码设计:
assign y=sel?(a^b):(a&b); // sel=1,a^b(异或);sel=0,a&b(与)
always@(a or b or sel)
assign
fn_sw.v
// 2022-2-17 Verilog学习
// 二选一逻辑设计 swit选择
`timescale 1ns/10ps
module fn_sw(
// 定义端口
a,
b,
sel,
y
);
// 定义端口属性
input a;
input b;
input sel;
output y;
assign y=sel?(a^b):(a&b); // sel=1,a^b(异或);sel=0,a&b(与)
endmodule
// testbench 测试台
module fn_sw_tb;
reg a,b,sel;
wire y;
fn_sw fn_sw(
.a(a),
.b(b),
.sel(sel),
.y(y)
);
initial begin
a<=0;b<=0;sel<=0;
#10 a<=0;b<=0;sel<=1;
#10 a<=0;b<=1;sel<=0;
#10 a<=0;b<=1;sel<=1;
#10 a<=1;b<=0;sel<=0;
#10 a<=1;b<=0;sel<=1;
#10 a<=1;b<=1;sel<=0;
#10 a<=1;b<=1;sel<=1;
#10 $stop;
end
endmodule
always
fn_sw.v
// 2022-2-17 Verilog学习
// 二选一逻辑设计 swit选择
`timescale 1ns/10ps
module fn_sw(
// 定义端口
a,
b,
sel,
y
);
// 定义端口属性
input a;
input b;
input sel;
output y;
//assign y=sel?(a^b):(a&b); // sel=1,a^b(异或);sel=0,a&b(与)
// 用always语句块实现组合逻辑
reg y; // 此时y为reg型
// @()中是敏感变量
always@(a or b or sel) begin
if(sel==1)begin
y <= a^b; // 此时y<=,除了assign和reg wire赋值中,用<=,因为实际电路是<=
end
else begin
y <= a&b;
end
end
endmodule
// testbench 测试台
module fn_sw_tb;
reg a,b,sel;
wire y;
fn_sw fn_sw(
.a(a),
.b(b),
.sel(sel),
.y(y)
);
initial begin
a<=0;b<=0;sel<=0;
#10 a<=0;b<=0;sel<=1;
#10 a<=0;b<=1;sel<=0;
#10 a<=0;b<=1;sel<=1;
#10 a<=1;b<=0;sel<=0;
#10 a<=1;b<=0;sel<=1;
#10 a<=1;b<=1;sel<=0;
#10 a<=1;b<=1;sel<=1;
#10 $stop;
end
endmodule
多位扩展 always case多路选择
always@(a or b or sel)begin
case(sel)
2'b00: begin end
2'b01: begin end
2'b10: begin end
2'b11: begin end
endcase
end
// 2022-1-17 Verilog学习
// 四选一逻辑
`timescale 1ns/10ps
module fn_sw_4(
a,
b,
sel,
y
);
input a;
input b;
input[1:0] sel; // 两位:00,01,10,11 才有4路选择
output y;
reg y;
always@(a or b or sel)
begin
// 2'b00:2位bit 00; 2'b01:2位bit 01
// &与,|或,a^b异或 相异为1, ~(a^b); 同或 相同为1
case(sel)
2'b00: begin y<=a&b; end
2'b01: begin y<=a|b; end
2'b10: begin y<=a^b; end
2'b11: begin y<=~(a^b); end
endcase
end
endmodule
// testbench 测试台
module fn_sw_4_tb;
reg[3:0] absel; // reg给4位
wire y;
fn_sw_4 fn_sw_4(
.a(absel[0]),
.b(absel[1]),
.sel(absel[3:2]), // 高2位给sel
.y(y)
);
initial begin
absel<=0; // absel 初值
#200 $stop; // absel 过200ns终止(absel四位bit----,16个变化,200ns/10ns=20个即可)
end
always #10 absel<=absel+1; // 过10ns,absel值+1
endmodule