代码1:
`timescale 1ns/10psmodule fn_sw(a,b,sel,y);
input a,b,sel;
output y;
assign y=(sel)?a^b:a&b;endmodulemodule fn_sw_tb;reg A,B,sel;
wire Y;
fn_sw fn_sw(.a(A),.b(B),.sel(sel),.y(Y));initial begin sel<=0;A<=0;B<=0;#10 sel<=0;A<=0;B<=1;#10 sel<=0;A<=1;B<=0;#10 sel<=0;A<=1;B<=1;#10 sel<=0;A<=0;B<=0;#10 sel<=1;A<=0;B<=1;#10 sel<=1;A<=1;B<=0;#10 sel<=1;A<=1;B<=1;#10 sel<=1;A<=0;B<=0;#10 $stop;
end
endmodule
实验波形:
代码2:always实现:
`timescale 1ns/10psmodule fn_sw(a,b,sel,y);
input a;
input b;
input sel;
output reg y;
//assign y=(sel)?a^b:a&b;always@(a or b or sel)
if(sel)beginy<=a^b;
end
else
beginy<=a&b;
endendmodulemodule fn_sw_tb;reg A,B,sel;
wire YY;
fn_sw fn_sw(.a(A),.b(B),.sel(sel),.y(YY));initial begin sel<=0;A<=0;B<=0;#10 sel<=0;A<=0;B<=1;#10 sel<=0;A<=1;B<=0;#10 sel<=0;A<=1;B<=1;#10 sel<=0;A<=0;B<=0;#10 sel<=1;A<=0;B<=1;#10 sel<=1;A<=1;B<=0;#10 sel<=1;A<=1;B<=1;#10 sel<=1;A<=0;B<=0;#10 $stop;
end
endmodule
实验波形:
代码3:always+case
`timescale 1ns/10psmodule fn_sw_case(a,b,sel,y);
input a;
input b;
input[1:0] sel;
output reg y;
//assign y=(sel)?a^b:a&b;always@(a or b or sel)
begincase(sel)2'b00:begin y<=a&b; end2'b01:begin y<=a|b; end2'b10:begin y<=a^b; end2'b11:begin y<=~(a^b); endendcase
end
endmodulemodule fn_sw_case_tb;reg A,B;
reg[1:0] sel;
wire YY;
fn_sw_case fn_sw_case(.a(A),.b(B),.sel(sel),.y(YY));initial begin sel<=2'b00;A<=0;B<=0; #10 sel<=2'b00;A<=0;B<=1; #10 sel<=2'b00;A<=1;B<=0; #10 sel<=2'b00;A<=1;B<=1; #10 sel<=2'b00;A<=0;B<=0; #10 sel<=2'b01;A<=0;B<=1; #10 sel<=2'b01;A<=1;B<=0; #10 sel<=2'b01;A<=1;B<=1; #10 sel<=2'b01;A<=0;B<=0; #10 sel<=2'b10;A<=0;B<=1; #10 sel<=2'b10;A<=1;B<=0; #10 sel<=2'b10;A<=1;B<=1; #10 sel<=2'b10;A<=0;B<=0; #10 sel<=2'b11;A<=0;B<=1; #10 sel<=2'b11;A<=1;B<=0; #10 sel<=2'b11;A<=1;B<=1; #10 sel<=2'b11;A<=0;B<=0; #10 $stop;
end
endmodule