Verilog中for语句的使用,简单testbench的写法

1,for语句的使用

`timescale	1ns/1ns	
module add16(a,b,c0,sum,cout);
	input	[15:0]	a,b;
	input		c0;
	output	[15:0]	sum;
	output		cout;
	
    	reg 	[15:0]	p,g,sum;  
    	reg 	[16:0] 	CA;	   
	reg		cout;
    	integer 		i;

	always @(a or b) 
		for(i=0;i<=15;i=i+1)
			begin 
				p[i] = a[i] ^ b[i];
				g[i] = a[i] & b[i];
			end
							
    	always @(p or g or c0)        
		begin					
        			CA[0] = c0;	  //CA[i] : carry to i bit
		         	for( i=0; i<=15; i=i+1)	
				 begin					  
                 				CA[i+1] = g[i] | ( p[i] & CA[i]);
			               		sum[i] 	= p[i] ^ CA[i];
         				end	
			cout=CA[16];
	    	end 
		
endmodule

 

2,简单Testbench的写法

`timescale	1ns/1ns
module	add16_tb;
	reg[15:0]		a,b;
	reg		c0;
	wire[15:0]	sum;
	wire		cout;
	
	add16 test(a,b,c0,sum,cout);
	
	initial 
		begin 		
			$display("");
			$display("+++++++++++++++++++++++++++++++++++++++++++++++");
			$display("********	The start of the test	*****************");
			$display("*******a*******b*******c0*******sum********cout"); 
			$display("============================  | ===============");
			$monitor("       %h,   %h,   %b,     | %h,      %b",a,b,c0,sum,cout);
					a=16'h1111;b=16'h1111;c0=0;
			#100	a=16'hffff;b=16'h0000;c0=0;
			#100	a=16'hffff;b=16'h0000;c0=1;
			#100	a=16'h1111;b=16'h1111;c0=0;
			#100	a=16'h2222;b=16'h1111;c0=0;
			#100	a=16'h1111;b=16'h4444;c0=0;
			#100	a=16'h9999;b=16'h4444;c0=0;
			#100
			$display("============================  | ===============");
			$display("********	The end of the test	*****************");
			$display("+++++++++++++++++++++++++++++++++++++++++++++++");
			$display("");
			#100	$finish;
		end
		
endmodule

 

3,总结

a,for语句i需要定义成integer 类型,另外注意表达式写成i=i+1不要写成i++;

b,另外,Verilog中用任何语句都要在头脑中有个硬件的概念,for语句也是,就如上面的加法器一样,在写hdl前在草图上画一个还是要的;

c,Testbench还是要用Active HDL,modelsim或LDV跑一跑才行;;

你可能感兴趣的:(Verilog)