Verilog HDL——循环语句

循环语句

Verilog HDL中4种循环语句

  1. for循环:指定循环次数
  2. while循环:设置循环条件
  3. repeat循环:连续执行语句N次
  4. forever循环:连续执行某条语句(不可综合,多用于仿真激励)

for循环

语法:
for(循环变量赋初值;循环执行条件;循环变量增值)
循环体语句的语句块;

/*
for 无符号数乘法器 mult_8b_for
*/
module mult_8b_for(
a,b,q);

parameter bsize =8;
input[bsize:0]a,b;
output[2*bsize-1:0]q;

reg[2*bsize:0]q,a_t; 
reg[bsize-1:0]b_t;
reg[bsize-1:0]cnt;

always@(a or b)begin
	q = 0;
	a_t ={{bsize[0]},a};
	b_t = b;
	cnt = bsize;
	for(cnt = bsize; cnt > 0; cnt = cnt-1)begin
		if(b_t[0])begin
			q = q + a_t;
		end
		else begin
			q = q;
		end
		a_t = a_t<<1;
		b_t = b_t>>1;
	end
end

endmodule

Verilog HDL——循环语句_第1张图片

while循环

while表达式在开始不为真(假、x、z)则语句不被执行。

/*
while 无符号数乘法器 mult_8b_while
*/
module mult_8b_while(
a,b,q);

parameter bsize =8;
input[bsize:0]a,b;
output[2*bsize-1:0]q;

reg[2*bsize:0]q,a_t; 
reg[bsize-1:0]b_t;
reg[bsize-1:0]cnt;

always@(a or b)begin
	q = 0;
	a_t ={{bsize[0]},a};//{0000 0000 a}
	b_t = b;
	cnt = bsize;
	while(cnt>0)begin
		if(b_t[0])begin
			q = q + a_t;
		end
		else begin
			q = q;
		end
		cnt = cnt - 1;
		a_t = a_t<<1;
		b_t = b_t>>1;
	end
end

endmodule

Verilog HDL——循环语句_第2张图片

repeat循环

repeat循环计数表达式的值不确定时(x或z),则循环次数为0。

/*
8比特数据乘法 mult_8b_repeat
*/

module mult_8b_repeat(
a,b,q
);

	parameter bsize = 8;
	input[bsize-1:0]a,b;
	output[2*bsize-1:0]q;

	reg[2*bsize-1:0]q,a_t;
	reg[bsize-1:0]b_t;

	always@(a or b)begin
		q = 0;
		a_t = {{bsize[0]},a};
		b_t = b;
		
		repeat(bsize) begin
			if(b_t[0])begin
				q = q + a_t;
			end
			else begin
				q = q;
			end
			a_t = a_t<<1;
			b_t = b_t>>1;
			end
	end
endmodule

输出q为a、b相乘:

Verilog HDL——循环语句_第3张图片

你可能感兴趣的:(FPGA/CPLD,fpga开发,Verilog,HDL)