HDLBits之BCDadd4

You are provided with a BCD (binary-coded decimal) one-digit adder named bcd_fadd that adds two BCD digits and carry-in, and produces a sum and carry-out.

module bcd_fadd {
    input [3:0] a,
    input [3:0] b,
    input     cin,
    output   cout,
    output [3:0] sum );

Instantiate 4 copies of bcd_fadd to create a 4-digit BCD ripple-carry adder. Your adder should add two 4-digit BCD numbers (packed into 16-bit vectors) and a carry-in to produce a 4-digit sum and carry out.

出现了和之前的bcd相同的问题:

程序:module top_module( 
    input [15:0] a, b,
    input cin,
    output cout,
    output [15:0] sum );
    reg[4:0] i;
    reg [3:0]count;
    
        for(i=0;i<4;i++)begin:add
            if(i==0)
                bcd_fadd u_bcd_fadd(a[3:0],b[3:0],cin,count[0],sum[3:0]);
            else
                bcd_fadd u_bcd_fadd(a[4*i+3:4*i],b[4*i+3:4*i],cin,count[i],sum[4*i+3:4*i]);
        end
        assign cout=count[3];
  
endmodule

在例化模块的位置出现如下错误:

Error (10170): Verilog HDL syntax error at top_module.v(11) near text: "u_bcd_fadd";  expecting "<=", or "=", or "+=", or "-=", or "*=", or "/=", or "%=", or "&=", or "|=", or "^=", or "<<=", or ">>=", or "<<<=", or ">>>=", or "++", or "--".

错误原因:模块例化调用不能出现在always语句内,因例化只实现一次,而always满足敏感表即进行。例化应与always并行。

解决方法:使用generate循环

generate循环的语法与for循环语句的语法很相似。但是在使用时必须先在genvar声明中声明循环中使用的索引变量名,然后才能使用它。genvar声明的索引变量被用作整数用来判断generate循环。genvar声明可以是generate结构的内部或外部区域,并且相同的循环索引变量可以在多个generate循环中,只要这些环不嵌套。genvar只有在建模的时候才会出现,在仿真时就已经消失了。

引用:HDLBits答案(5)_Generate实例化模块_谦豫-CSDN博客_generate 例化

Verilog中generate循环中的generate块可以命名也可以不命名。如果已命名,则会创建一个generate块实例数组。如果未命名,则有些仿真工具会出现警告,因此,最好始终对它们进行命名。

程序:module top_module( 
    input [15:0] a, b,
    input cin,
    output cout,
    output [15:0] sum );
    genvar i;
    reg [3:0]count;
    generate
        for(i=0;i<4;i++)begin:add
            if(i==0)
                bcd_fadd u_bcd_fadd(a[3:0],b[3:0],cin,count[0],sum[3:0]);
            else
                bcd_fadd u_bcd_fadd(a[4*i+3:4*i],b[4*i+3:4*i],count[i-1],count[i],sum[4*i+3:4*i]);
        end
        assign cout=count[3];
    endgenerate
endmodule

注意:最好对for循环模块命名,在最后对cout不能直接使用cout=count[3](因为不在always语句块中)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值