Verilog例子整理(转载)

本文详细介绍了Verilog中的并行(fork-join)块、持续赋值与阻塞赋值的2选1多路选择器、同步计数器、非阻塞与阻塞赋值示例,以及用for语句描述的投票表决器。同时,还展示了任务定义、测试程序、函数和编码器的实现,包括阶乘运算、数据流描述的MUX、半加器和全加器等。此外,文章还探讨了$random函数的使用,以及各种门电路、三态门、双向驱动器和编码器的多种描述方法。
摘要由CSDN通过智能技术生成
               

【例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=

  • 4
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值