1.比较数据a和b,若两个数据相同则输出1,否则输出0(a、b均为单比特)
看需求就简单设置输入a,b,输出o。
module compare (a,b,o);
input a;
input b;
output o;
//先来第一种写法,使用?:,这里是默认全是wire类型
assign o = (a == b)?1'b1 : 1'b0;
//第二种写法,使用if else
reg o;
always @ (*) begin
if (a==b)
o=1;
else
o=0;
end
//第三种写法,针对always更好的写法
reg o;
always @ (*) begin
o=1'b0;
if (a==b)
o=1'b1;
end
//第四种写法,直接同或
assign o = ~(a ^ b);
//以上方法run一种即可
endmodule
//testbench
module compare_tb;//这里插一下,文件名最好是与模块名一致,是个好习惯
reg a , b;
wire o;
initial begin
a=1; b=0;
#20 a=1; b=1;
#20 a=0; b=1;
#20 a=0; b=0; //这种简单逻辑就全例举就可以了
#20 $finish; //退出仿真的意思
end
compare u_compare (.a(a) , .b(b) , .o(o) )//前面是调用模块的名字,也就是上面写的模块compare.v的模块名字,后面是例化名,是自己起的
endmodule
2.实现四位全加器。a,b,进位,o
module full_adder4 (a,b,carry,o);
input [3:0] a;
input [3:0] b;
output carry;
output [3:0] o;
assign {carry,o} = {1'b0,a} + {1'b0,b} ; //防止位数报错
endmodule
//testbench
module full_adder_tb;
reg [3:0] a,b;
wire carry;
wire [3:0] o;
integer i,j;
initial begin
a = 4'b0000; b=4'b0000;
for (i=0;i<16;i++)
for(j=0;j<16;j++) begin
#20 a=i; b=j;
end
full_adder4 u_fa4( .a(a), .b(b), .carry(carry), .o(o) )
endmodule
3.实现一个4位全加器(default输出任意态)
module mux4( in0,inl,in2,in3,sel,out );
input [3:0] in0;
input [3:0] in1;
input [3:0] in2;
input [3:0] in3;
input [1:0] sel;
output [3:0] out;
reg [3;0] out;
always @(*)begin
case(sel)
2'b00: out=in0;
2'b01: out=inl;
2'b10: out=in2;
2'b11: out=in3;
default: out=4'dx;//十进制不定态
endcase
end
endmodule
//testbench
module mux4_tb:
reg [3:0] in0 in1,in2,in3;
reg [1:0] sel;
wire [3:0] out;
initial begin
in0=0; in1=1; in2=2; in3=3; sel=2'dx;
#20 sel=2'dX;
#20 sel=2'd0;
#20 sel=2'd1;
#20 sel=2'd2;
#20 sel=2'd3;
#20 $finish;
end
mux4 u_mux4( .in0(in0), .in1(in1), .in2(in2), .in3(in3), .sel(sel), .out(out) )
endmodule
4.使用for语句实现七人投票表决器(可以设置inpu同时[3:0],1同意,0同意)
module vote( ticket,result);
input [6;0] ticket;
output result;
reg result;
integer i;
reg [2:0] cnt;
always @(*) begin
cnt=3'd0; //最高就是7,所以只需要三比特
result = 1'b;
for(i=0;i<7;i++) begin
if(ticket[i]==1) //就是数1的个数
cnt =cnt +1;
end
if(cnt >3)
result = 1'b1;
end
endmodule
//benchmark
module vote_tb;
reg [6;0] tick;
wire result;
initial begin
tick =0;
#20 tick =2'b0011001;
#20 tick =2 b0111001;
#20 tick =2'b1011001;
#20 tick =2'b0011101;
#20 tick =2'b0011110;
#20 tick =2'b1100001;
#20 tick =2'b0111001;
#20 tick =2'b0011011;
#20 tick =2'b0011000;
#20 tick =2'b0001000:
#20 $finish;
end
endmodule
简单的组合逻辑电路例子就这些,明天再更新记录一下时序逻辑电路。
(ps.果然自己打一遍效果更好,相比于纯看好很多)
标签:HDL,20,sel,Verilog,input,tick,out,reg,逻辑设计 From: https://blog.csdn.net/weixin_47104706/article/details/140595449