三选一数据选择器modelsim仿真代码和测试代码
时间: 2024-03-24 18:39:26 浏览: 97
以下是一个三选一的数据选择器的Verilog代码和测试代码,可以在ModelSim中进行仿真:
```
module mux_3to1(input [2:0] data_in, input [1:0] sel, output reg data_out);
always @ (sel or data_in)
begin
case(sel)
2'b00: data_out = data_in[0];
2'b01: data_out = data_in[1];
2'b10: data_out = data_in[2];
2'b11: data_out = 1'b0; // if sel is invalid, output 0
endcase
end
endmodule
```
测试代码:
```
module test_mux_3to1();
reg [2:0] data_in;
reg [1:0] sel;
wire data_out;
mux_3to1 uut(
.data_in(data_in),
.sel(sel),
.data_out(data_out)
);
initial begin
// Test case 1: sel = 0, expect data_out = data_in[0]
data_in = 3'b001;
sel = 2'b00;
#10;
if (data_out !== 1'b0) $error("Test case 1 failed: data_out = %b", data_out);
sel = 2'b01;
#10;
if (data_out !== 1'b0) $error("Test case 1 failed: data_out = %b", data_out);
sel = 2'b10;
#10;
if (data_out !== 1'b1) $error("Test case 1 failed: data_out = %b", data_out);
sel = 2'b11;
#10;
if (data_out !== 1'b0) $error("Test case 1 failed: data_out = %b", data_out);
// Test case 2: sel = 1, expect data_out = data_in[1]
data_in = 3'b110;
sel = 2'b01;
#10;
if (data_out !== 1'b1) $error("Test case 2 failed: data_out = %b", data_out);
sel = 2'b00;
#10;
if (data_out !== 1'b0) $error("Test case 2 failed: data_out = %b", data_out);
sel = 2'b10;
#10;
if (data_out !== 1'b0) $error("Test case 2 failed: data_out = %b", data_out);
sel = 2'b11;
#10;
if (data_out !== 1'b0) $error("Test case 2 failed: data_out = %b", data_out);
// Test case 3: sel = 2, expect data_out = data_in[2]
data_in = 3'b010;
sel = 2'b10;
#10;
if (data_out !== 1'b0) $error("Test case 3 failed: data_out = %b", data_out);
sel = 2'b00;
#10;
if (data_out !== 1'b0) $error("Test case 3 failed: data_out = %b", data_out);
sel = 2'b01;
#10;
if (data_out !== 1'b1) $error("Test case 3 failed: data_out = %b", data_out);
sel = 2'b11;
#10;
if (data_out !== 1'b0) $error("Test case 3 failed: data_out = %b", data_out);
// Test case 4: sel = 3, expect data_out = 0
data_in = 3'b111;
sel = 2'b11;
#10;
if (data_out !== 1'b0) $error("Test case 4 failed: data_out = %b", data_out);
sel = 2'b00;
#10;
if (data_out !== 1'b0) $error("Test case 4 failed: data_out = %b", data_out);
sel = 2'b01;
#10;
if (data_out !== 1'b0) $error("Test case 4 failed: data_out = %b", data_out);
sel = 2'b10;
#10;
if (data_out !== 1'b0) $error("Test case 4 failed: data_out = %b", data_out);
$display("All test cases passed!");
$finish;
end
endmodule
```
阅读全文