经典设计实例_整理加解释(21-25)

21.条件编译举例

module compile(
input    a,
input    b,
output    out
);

`ifdef    add  //宏名为add
    out <= a + b;
`else
    out <= a - b;
`endif

endmodule

`ifdef 为条件编译语句,只有当程序中宏定义过`ifdef后的宏名,才进行下一步的动作。在上个程序中,即为若程序中定义过add,则进行相加处理。

22.加法计数器中的进程

module count(
input        clk,
input        reset,
input        load,
input  [3:0] data,
output       cout,
output reg [3:0] qout
);
always@(posedge clk) begin
    if(reset)            //同步清零
        qout <= 4'b0;
    else if (load)       //同步置位
        qout <= data;
    else              
        qout <= qout + 4'b1; 
end

assign cout = (qout == 4'hf)?1:0;//第二进程输出进位

endmodule

23.任务举例

module alutask(
input [1:0] code,
input [3:0] a,
input [3:0] b,
output reg [4:0] c,
);

task my_and;//任务定义,无输出输出端口列表
input [3:0] a,b;
output [4:0] out;
integer i;
    begin
    for(i = 3;i >= 0; i = i - 1)
        out[i] = a[i] & b[i];
    end
endtask

// ===================================
// 调用task,需注意端口的列表需要与定义的端口顺序相同
// ===================================

always@(code or a or b)begin
    case(code)
        2'b00 : my_and(a,b,c);//与操作
        2'b01 : c = a | b;    //或
        2'b10 : c = a - b;    //减
        2'b11 : c = a + b;    //加
        default :c = 5'b0; 
    endcase
end
endmodule

24.函数举例

function [7:0] get0;
input [7:0] x;
reg   [7:0] count;
integer i;
    begin
        count = 0;
        for(i = 0;i <= 7;i = i + 1 )
            if(x[i] = 1'b0)
                count = count + 1;
            else 
                count = count;
        get0 = count;
    end
endfunction

25.阶乘运算函数

module funct(
input          clk,
input [3:0]    n,
input          reset,
output[31:0]   result
);
always@(posedge clk)begin
    if(result)
        result <= 32'b0;
    else
        result <= 2 * factorial(n);
end

function [31:0]factorial;
input [3:0]    opa;
reg   [3:0]    i;
    begin
    factorial = opa ? 1 : 0;
    for(i = 2; i <= opa; i = i + 1)
        factorial = i * factorial;
    end
endfunction
ebdmodule

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值