module mux4_tb;
integer i;
reg[1:0] s;
reg[3:0] i0,i1,i2,i3;
wire[3:0] out;
initial begin
i0 = 4'b0;
i1 = 4'b0101;
i2 = 4'b1010;
i3 = 4'b1111;
i = 0;
s = 2'b0;
end
always begin
#10
i = i + 1;
if(i > 3)
i = 0;
s = i;
end
mux4 myMux4(
.d0(i0),
.d1(i1),
.d2(i2),
.d3(i3),
.s(s),
.y(out)
);
endmodule
(7)寄存器堆示例(计算机组成原理)
模块
module regFile(clk,reset,s,wEn,din,dout);
input clk,reset,wEn; //时钟,复位,写使能
input[1:0] s; //从regFile的四个单位中选择
input[7:0] din;
output[7:0] dout;
reg[7:0] R[0:3]; //regFile的存储空间,4个字节
assign dout = R[s]; //把R[s]连接到dout,内部信号传出来通常用assign,非时序电路,用=
always @(posedge clk or negedge reset)
begin
if(!reset) begin
R[0] <= 0; //给寄存器写值,这是时序电路,用<=
R[1] <= 1;
R[2] <= 2;
R[3] <= 3;
end
else if (wEn)
R[s] <= din;
end
endmodule
testbench
module regFile_tb;
reg clk,rst,wEn;
reg[1:0] s;
reg[7:0] in;
wire[7:0] out;
initial begin
rst = 1'b0;
wEn = 1'b0;
clk = 1'b0;
s = 2'b0;
in = 8'b1111_1111;
end
always #10 clk = ~clk;
always @(posedge clk) begin
in = in+1;
s = in % 4;
//从第四个clk上升沿开始写入数据,由于读是非时序电路assign,写是时序电路<=,每次都是读出旧数据,写入新数据(下个周期读出)
if(in>=4) begin
rst = 1'b1;
wEn = 1'b1;
end
end
regFile rf(
.clk(clk),
.reset(rst),
.s(s),
.wEn(wEn),
.din(in),
.dout(out)
);
endmodule
(8)ALU示例1(计算机组成原理)
模块
module ALU_1(op,A,B,result);
input[2:0] op;
input[7:0] A,B;
output[7:0] result;
reg[7:0] result;
always @(op or A or B) begin
if(op == 3'b000) result = A+B;
else if(op == 3'b001) result = A-B;
else if(op == 3'b010) result = A&B;
else if(op == 3'b011) result = A|B;
else if(op == 3'b100) result = ~A;
else result = 8'b0;
end
endmodule
testbench
module ALU_1_tb;
reg[7:0] A,B;
reg[2:0] op;
wire[7:0] res;
initial begin
A = 8'b1010_1010;
B = 8'b0101_0101;
op = 3'b0;
end
always #10 op = op+1;
ALU_1 alu(
.op(op),
.A(A),
.B(B),
.result(res)
);
endmodule
(9)ALU示例2(计算机组成原理)
模块
module ALU_2(op,A,B,ci,result,co);
input[2:0] op;
input[7:0] A,B;
input ci;
output[7:0] result;
output co;
reg[7:0] result;
reg co;
always @(op or A or B) begin
case(op)
3'd0: {co,result} = A + B;
3'd1: {co,result} = A + B + ci;
3'd2: {co,result} = A - B - ci;
3'd3: result = A & B;
3'd4: result = A | B;
3'd5: result = A ^ B;
3'd6: result = ~A;
default: begin
co = 0;
result = 8'd0;
end
endcase
end
endmodule
testbench
module ALU_2_tb;
reg[7:0] A,B;
reg[2:0] op;
reg ci;
wire[7:0] res;
wire co;
initial begin
A = 8'b1010_1010;
B = 8'b0101_0101;
ci = 1;
op = 0;
end
always #10 op = op+1;
ALU_2 alu(
.op(op),
.A(A),
.B(B),
.ci(ci),
.result(res),
.co(co)
);
endmodule