Verilog 加法器和減法器(1)
兩個一位的二進位制數x,y相加,假設和為s,進位為cout,其真值表為:
從真值表中,我們可以得到:s = x^y, cout = x&y,用以下的電路,可以實現兩個一位數的相加,該電路稱為半加器。
實現該電路的verilog程式碼如下:
module halfadd(x,y,s,cout); input x; input y; output s; output cout; assign s = x^y; assign cout = x&y; endmodule View Code
相對應的testbench檔案如下程式碼。在程式碼中,我們採用系統函式$random來產生隨機激勵。半加器電路中並沒有使用時鐘,但在testbench中,產生了時鐘訊號,主要是為了功能驗證時候,有一個時間單位訊號,便於檢查結果。
`timescale 1ns/1ns `define clock_period 20 module halfadd_tb; regx,y; wire cout; wire s; reg clk; halfadd halfadd_0( .x(x), .y(y), .s(s), .cout(cout) ); initial clk = 0; always #(`clock_period/2) clk = ~clk; initial begin x = 0; repeat(20) #(`clock_period) x = $random; end initial begin y = 0; repeat(20) #(`clock_period) y = $random; end initial begin #(`clock_period*20) $stop; end endmodule View Code
在quartus II中,分析與綜合後,用rtl view 可以得到 halfadd的電路如下,和我們預想的一樣。
功能模擬結果如下,從波形中可以看到結果正確。
全編譯後,在Cyclone IV E-EP4CE10F17C8中的門級模擬結果如下,輸入和輸出之間,會有幾ns的時延。