用问号冒号语句实现二选一:
用问号冒号语句写二选一
//2023-5-17
//二选一
`timescale 1ns/10ps
module two_select_one (
A,
B,
sel,
out
);
input A;
input B;
input sel;
output out;
assign out = sel?A:B;
endmodule
//testbench of two select one
module two_select_one_tb ;
reg A;
reg B;
reg sel;
wire out;
two_select_one two_select_one(
.A(A),
.B(B),
.sel(sel),
.out(out)
);
initial begin
A <= 0;
B <= 0;
sel <= 0;
#15
A <= 1;
B <= 0;
sel <= 1;
#15
A <= 1;
B <= 0;
sel <= 0;
#15
A <= 0;
B <= 1;
sel <= 1;
#15
A <= 0;
B <= 1;
sel <= 0;
#15 $stop;
end
endmodule
波形仿真
用3种语句实现3个宽度的八选一
//2023-5-17
//八选一
`timescale 1ns/10ps
module eight_select_one_1 (
A,
sel,
out
);
input[7:0] A;
input[2:0] sel;
output out;
reg out;
always@( * ) begin
if(sel==3'b000) begin
out = A[0];
end
else if(sel==3'b001) begin
out = A[1];
end
else if(sel==3'b010) begin
out = A[2];
end
else if(sel==3'b011) begin
out = A[3];
end
else if(sel==3'b100) begin
out = A[4];
end
else if(sel==3'b101) begin
out = A[5];
end
else if(sel==3'b110) begin
out = A[6];
end
else if(sel==3'b111) begin
out = A[7];
end
end
endmodule
module eight_select_one_2 (
A,
sel,
out
);
input[7:0] A;
input[2:0] sel;
output out;
wire out;
assign out = (sel==3'b000)?A[0]:
(sel==3'b001)?A[1]:
(sel==3'b010)?A[2]:
(sel==3'b011)?A[3]:
(sel==3'b100)?A[4]:
(sel==3'b101)?A[5]:
(sel==3'b110)?A[6]:
A[7];
endmodule
module eight_select_one_3 (
A,
sel,
out
);
input[7:0] A;
input[2:0] sel;
output out;
reg out;
always @( * ) begin
case(sel)
3'b000:out<=A[0];
3'b001:out<=A[1];
3'b010:out<=A[2];
3'b011:out<=A[3];
3'b100:out<=A[4];
3'b101:out<=A[5];
3'b110:out<=A[6];
3'b111:out<=A[7];
endcase
end
endmodule
//testbench of two select one
module eight_select_one_tb ;
reg[7:0] A;
reg[2:0] sel;
wire out1;
wire out2;
wire out3;
eight_select_one_1 eight_select_one_1(
.A(A),
.sel(sel),
.out(out1)
);
eight_select_one_2 eight_select_one_2(
.A(A),
.sel(sel),
.out(out2)
);
eight_select_one_3 eight_select_one_3(
.A(A),
.sel(sel),
.out(out3)
);
initial begin
sel <= 3'b000;
A <= 8'b0000_0000;
#15
A <= 8'b0000_0001;
#15
sel <= 3'b001;
A <= 8'b0000_0000;
#15
A <= 8'b0000_0010;
#15
sel <= 3'b010;
A <= 8'b0000_0000;
#15
A <= 8'b0000_0100;
#15
sel <= 3'b011;
A <= 8'b0000_0000;
#15
A <= 8'b0000_1000;
#15
sel <= 3'b100;
A <= 8'b0000_0000;
#15
A <= 8'b0001_0000;
#15
sel <= 3'b101;
A <= 8'b0000_0000;
#15
A <= 8'b0010_0000;
#15
sel <= 3'b110;
A <= 8'b0000_0000;
#15
A <= 8'b0100_0000;
#15
sel <= 3'b111;
A <= 8'b0000_0000;
#15
A <= 8'b1000_0000;
#15 $stop;
end
endmodule
波形仿真
PS:3bit的sel变量,需要用3‘b或者3’d 来表示二进制或者十进制,否则仿真无法顺利出结果
涉及assign语句的变量,新的变量需用wire来定义
设计always语句的变量,变量需要用reg来定义