EE 학부과목/verilog
[verilog] Full Adder, 4bit Adder 구현
colorful-palette
2023. 3. 13. 12:09
fa.v 파일 (full adder)
module fa(s, cout, a, b, cin); //full adder 모듈
input a, b, cin;
output s, cout;
assign {cout, s} = a + b + cin; //시스템 내의 full adder 계산
endmodule
/*
다르게 짜는 방법 1
module fa(s, cout, a, b, cin);
input a, b, cin;
output s, cout;
wire w1, w2, w3;
xor u1 (w1, a, b);
and u2 (w2, a, b);
xor u3 (s, w1, cin);
and u4 (w3, w1, cin);
or u5 (cout, w3, w2);
endmodule
*/
/*
다르게 짜는 방법 2
module fa(s, cout, a, b, cin);
assign s = (a^b)&cin;
assign cout = (a&b)|((a^b)&(cin));
endmodule
*/
add4bit.v 파일 (fa.v에서 만든 full adder를 가져와 4비트 덧셈기를 만든다)
module add4bit(s, cout, a, b); //4bit Adder 모듈
input [3:0]a, b;
output [3:0]s;
output cout;
wire c0, c1, c2;
//reg cin = 1'b0; //맨 처음 들어오는 carry는 0
fa fa1 (s[0], c0, a[0], b[0], 0); //FA1
fa fa2 (s[1], c1, a[1], b[1], c0); //FA2
fa fa3 (s[2], c2, a[2], b[2], c1); //FA3
fa fa4 (s[3], cout, a[3], b[3], c2); //FA4
endmodule
/* 다르게 짜는 방법:
module add4b1(a, b, sum, cout);
input [3:0] a, b;
output [3:0] sum;
output cout;
wire [4:0] sum1; sum1 vector 새로 정의
assign sum1 = a + b;
assign cout = sum1[4]; sum1의 최상위 비트만 저장
assign sum1 = sum1[3:0]; sum1에는 [3:0]까지만 저장
endmodule
*/
add4_tb.v 파일
module add4_tb(); //testbench에는 cin(carry in)을 넣지 않았다.
reg [3:0] a;
reg [3:0] b;
wire [3:0] s_0609;
wire cout;
add4bit u1 (.s(s_0609), .cout(cout), .a(a), .b(b));
initial begin
a=4'b0000;
b=4'b0000;
#32 $finish; //16번 always문 반복하고 종료
end
always begin //2ns마다 a와 b는 0000~1111 중 random하게 바뀐다.
#2 a = $urandom%4'b1111;
end
always begin
#2 b = $urandom%4'b1111;
end
always @(a or b) begin //cmd창에서 출력
$monitor("%d + %d -> sum: %d, carryout: %b", a, b, s_0609, cout);
end
initial begin
$display("%m");
$display("---------4bit adder test---------");
$dumpfile("output.vcd");
$dumpvars(0);
end
endmodule
/* 다르게 짠 코드
module add4_tb();
reg [3:0] a, b;
wire [3:0] sum1, sum2;
wire cout1, cout2;
add4b1 u1(a, b, sum1, cout1);
initial begin
a = 0; b=0;
#20 $finish;
end
always begin
# 1 a = $random; b = $random;
end
initial begin
$dumpfile("output.vcd");
$dumpvars(0);
end
endmodule
*/