亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Verilog

Verilog 全加器设计与实现指南

加法器是执行两数相加的数字组件。它是处理器 ALU 的核心组件,用于地址递增、表索引、缓冲指针等需要加法的场合。

全加器在两个输入二进制数之外加上进位输入,产生和与进位输出。

真值表

ABCinCoutSum
00000
00101
01001
01110
10001
10110
11010
11111

设计

下面展示一个 4 位加法器示例,通过信号 a 和 b 接受两个 4 位二进制数。加法器是组合电路,可用连续赋值 assign 或包含所有输入的敏感列表的 always 块建模。下面代码采用前者。

module fulladd ( 
  input [3:0] a, 
  input [3:0] b, 
  input c_in, 
  output c_out, 
  output [3:0] sum
); 
  assign {c_out, sum} = a + b + c_in; 
endmodule 

下面代码使用 always 块,在任一输入变化时执行。

module fulladd ( 
  input [3:0] a, 
  input [3:0] b, 
  input c_in, 
  output reg c_out, 
  output reg [3:0] sum
); 
  always @ (a or b or c_in) begin 
    {c_out, sum} = a + b + c_in; 
  end 
endmodule 

硬件原理图

测试平台

module tb_fulladd; 
  reg [3:0] a; 
  reg [3:0] b; 
  reg c_in; 
  wire [3:0] sum; 
  integer i; 
  fulladd fa0 ( .a (a), .b (b), .c_in (c_in), .c_out (c_out), .sum (sum) ); 
  initial begin 
    a <= 0; b <= 0; c_in <= 0; 
    $monitor ("a=0x%0h b=0x%0h c_in=0x%0h c_out=0x%0h sum=0x%0h", a, b, c_in, c_out, sum); 
    // 使用 for 循环向输入施加随机值
    for (i = 0; i < 5; i = i+1) begin 
      #10 a <= $random; b <= $random; c_in <= $random; 
    end 
  end 
endmodule 

注意当 a 和 b 相加超过 4 位时,和回滚为零且 c_out 变为 1。例如高亮黄色的行相加得到 0x11,低 4 位赋给 sum,第 4 位赋给 c_out。

仿真日志

ncsim> run
a=0x0 b=0x0 c_in=0x0 c_out=0x0 sum=0x0
a=0x4 b=0x1 c_in=0x1 c_out=0x0 sum=0x6
a=0x3 b=0xd c_in=0x1 c_out=0x1 sum=0x1
a=0x5 b=0x2 c_in=0x1 c_out=0x0 sum=0x8
a=0xd b=0x6 c_in=0x1 c_out=0x1 sum=0x4
a=0xd b=0xc c_in=0x1 c_out=0x1 sum=0xa
ncsim: *W,RNQUIE: Simulation is complete.

Verilog

  1. Verilog 入门:数字电路设计完整教程
  2. 掌握 Verilog 拼接操作:实用指南
  3. 深入理解 Verilog 赋值语句:类型、语法与最佳实践
  4. Verilog阻塞与非阻塞赋值:关键区别详解
  5. 掌握Verilog函数:高效RTL设计的复用利器
  6. 理解Verilog任务:函数vs任务、语法与用法全解析
  7. Verilog 时钟发生器设计与实现指南
  8. 掌握 Verilog 数学函数:高效硬件设计的利器
  9. 掌握 Verilog $timeformat:精度控制与显示格式化
  10. 理解与打印 Verilog 任意作用域下的 Timescale
  11. 掌握 Verilog 文件 I/O:打开、读取、写入和关闭
  12. Verilog 入门指南:Hello World 示例