module myadder(idata1,idata2,odata1,odata2,clk,overflow);
//输入
input clk;
input [3:0]idata1,idata2;
//输出
output [4:0]odata1;
output overflow;
output reg [3:0]odata2;
//中间变量
wire var1;
wire [3:0]var2;
/////////////////////
reg [3:0]rdata1,rdata2;
reg [4:0]oreg;
wire [2:0]flag;
reg flag1;
////////////////////////
initial begin
rdata1<=0;
rdata2<=0;
oreg<=0;
end
always @(posedge clk) begin
rdata1<=idata1;
rdata2<=idata2;
oreg<=idata1+idata2;
end
assign odata1=oreg;
assign var1=odata1[4];//cout
assign var2=odata1[3:0];//result
assign flag={rdata1[3],rdata2[3],oreg[3]};//符号位
always @(var1 or var2) begin
if (flag==3'b001 | flag==3'b110)
flag1<=1'b1;
else
flag1<=1'b0;
end
assign overflow=flag1;
always @(posedge clk) begin
if (overflow)
odata2<=odata1[4:1];
else
odata2<=var2;
end
endmodule
自编程序与altera自带的加法器ip仿真结果对比
(a)ip
(b)自编
后仿真波形对比
(a)自编
(b)ip
从仿真结果可以看出,前仿真完全相同;后仿真基本相同,自编加法器的overflow在第5个时钟周期处出现了一个glitch。