Verilog学习笔记4:二选一逻辑

代码1: 

`timescale 1ns/10ps

module fn_sw(
			a,
			b,
			sel,
			y);
input a,b,sel;
output y;
assign y=(sel)?a^b:a&b;

endmodule

module 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/10ps

module 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)begin
	y<=a^b;
end
else
begin
	y<=a&b;
end

endmodule

module 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/10ps

module 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)
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

module 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                             
                                      

小结