【例5.6 】用fork-join 并行块产生信号波形
`timescale 10ns/1ns
module wave2;
reg wave;
parameter cycle=5;
initial
fork
wave=0;
#(cycle) wave=1;
#(2*cycle) wave=0;
#(3*cycle) wave=1;
#(4*cycle) wave=0;
#(5*cycle) wave=1;
#(6*cycle) $finish;
join
initial $monitor($time,,,"wave=%b",wave);
endmodule
【例5.7 】持续赋值方式定义的2 选1 多路选择器
module MUX21_1(out,a,b,sel);
input a,b,sel;
output out;
assign out=(sel==0)?a:b;
//持续赋值,如果sel为0,则out=a ;否则out=b
endmodule
【例5.8 】阻塞赋值方式定义的2 选1 多路选择器
module MUX21_2(out,a,b,sel);
input a,b,sel;
output out;
reg out;
always@(a or b or sel)
begin
if(sel==0) out=a; //阻塞赋值
else out=b;
end
endmodule
【例5.2 】同步置数、同步清零的计数器
module count(out,data,load,reset,clk);
output[7:0] out;
input[7:0] data;
input load,clk,reset;
reg[7:0] out;
always @(posedge clk) //clk 上升沿触发
begin
if (!reset) out = 8'h00; //同步清0,低电平有效
else if (load) out = data; //同步预置
else out = out + 1; //计数
end
endmodule
【例5.9 】非阻塞赋值
module non_block(c,b,a,clk);
output c,b;
input clk,a;
reg c,b;
always @(posedge clk)
begin
b<=a;
c<=b;
end
endmodule
【例5.10 】阻塞赋值
module block(c,b,a,clk);
output c,b;
input clk,a;
reg c,b;
always @(posedge clk)
begin
b=a;
c=b;
end
endmodule
【例5.15 】用for 语句描述的七人投票表决器
module voter7(pass,vote);
output pass;
input[6:0] vote;
reg[2:0] sum;
integer i;
reg pass;
always @(vote)
begin
sum=0;
for(i=0;i<=6;i=i+1) //for语句
if(vote[i]) sum=sum+1;
if(sum[2]) pass=1; //若超过4人赞成,则pass=1
else pass=0;
end
endmodule
【例6.2 】任务举例
module alutask(code,a,b,c);
input[1:0] code;
input[3:0] a,b;
output[4:0] c;
reg[4:0] c;
task my_and; //任务定义,注意无端口列表
input[3:0] a,b; //a,b,out 名称的作用域范围为task任务内部
output[4:0] out;
integer i;
begin
for(i=3;i>=0;i=i-1)
out[i]=a[i]&b[i]; //按位与
end
endtask
always@(code or a or b)
begin
case(code)
2'b00: my_and(a,b,c);
/*调用任务my_and,需注意端口列表的顺序应与任务定义中的一致,这里的a,b,c
分别对应任务定义中的a,b,out */
2'b01: c=a|b; //或
2'b10: c=a-b; //相减
2'b11: c=a+b; //相加
endcase
end
endmodule
【例6.3 】测试程序
`include "alutask.v"
module alu_tp;
reg[3:0] a,b;
reg[1:0] code;
wire[4:0] c;
parameter DELY = 100;
alutask ADD(code,a,b,c); //调用被测试模块
initial begin
code=4'd0; a= 4'b0000; b= 4'b1111;
#DELY code=4'd0; a= 4'b0111; b= 4'b1101;
#DELY code=4'd1; a= 4'b0001; b= 4'b0011;
#DELY code=4'd2; a= 4'b1001; b= 4'b0011;
#DELY code=4'd3; a= 4'b0011; b=