一、always语句块实现二选一逻辑
- always语句块里赋值的变量需要是reg型
- reg型变量赋值用带箭头的等号
- ^符号为异或,&为与
verilog代码:
//2023/3/28 lzp
//二选一逻辑设计
`timescale 1ns/10ps
module select_gate(a, b, sel, y);
input a, b, sel;
output y;
//assign y=sel ? (a^b) : (a&b);
reg y;
always@(a or b or sel) begin
if(sel == 1) begin
y<=a^b;
end
else begin
y<=a&b;
end
end
endmodule
//test_bench
module select_gate_tb;
reg A, B, SEL;
wire Y;
select_gate select_gate(.a(A), .b(B), .sel(SEL), .y(Y));
initial begin
A<=0;
B<=1;
SEL<=1;
#2;
SEL<=0;
#2;
$stop;
end
endmodule
波形图:
异名例化:
例化相关博客参考:最强Verilog例化说明_奇点FPGA的博客-CSDN博客
二、case语句实现多路选择
verilog代码:
//使用case实现的多路选择器
module muti_select_gate(a, b, sel, y);
input a, b;
input[1:0] sel;
output y;
reg y;
always@(a or b or sel) begin
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
//test_bench of muti_select_gate
module muti_select_gate_tb;
reg A, B;
reg[1:0] SEL;
wire Y;
muti_select_gate muti_select_gate(.a(A), .b(B), .sel(SEL), .y(Y));
initial begin
A<=0;
B<=1;
SEL<=2'b00;
#2;
SEL<=2'b01;
#2;
SEL<=2'b10;
#2;
SEL<=2'b11;
#2;
$stop;
end
endmodule
波形图:
absel[3:2]指absel的高两位
每过10ns absel自增1