Search code examples
verilogsystem-verilog

Layer module output shows 1 instead of 11


I am new to SystemVerilog and wanted to write a module that performs a weighted sum of inputs with corresponding weights. This is my module code:

module Layer #(parameter num_inps=2)(out, inps, ws, clk, rst);
    output reg out;
    input real inps[num_inps];
    input logic clk, rst;
    input real ws[num_inps];
    real temp[num_inps];
    genvar i;
    generate
        for(i=0; i<num_inps; i++) begin
            assign temp[i] = inps[i] * ws[i];
        end
    endgenerate
    always @( posedge clk, posedge rst) begin : res
        if (rst==1) begin
            out = 0;
        end
        else begin
            out = 0;
            begin
                for(int j=0; j<num_inps; j++) begin
                    out = out + temp[j];
                end
            end
        end
    end
endmodule

and this is my testbench code

module main_tb();
real out;
real inps[2], ws[2];
logic clk, rst;
Layer l1(out, inps, ws, clk, rst);
initial begin
    $dumpfile("ow.vcd");
    $dumpvars(0, l1);
    inps[0] = 1.0;
    inps[1] = 2.0;
    ws[0] = 5.0;
    ws[1] = 3.0;
    rst = 0;
    clk = 0;
    #10
    clk = 1;
    #10
    clk = 0;
    $display(out);
    #10
    $finish;
end
endmodule

I am facing issues because when I Instantiate my Layer module and pass the appropriate inputs, out turns out to be 1.0000 instead of 11.0000. Am I using the always block incorrectly? if so please help me correct this. Thank you so much!

I am currently using Icarus verilog for simulation and this is the flag I'm passing to compile:

iverilog -g2012 -o output layer.sv main.sv vvp output


Solution

  • The problem is that you declared out as a 1-bit reg in the Layer module. It's known values can only be 0 and 1, not 11. You correctly declared it as a real type in the testbench.

    Change:

    output reg out;
    

    to:

    output real out;
    

    With this change, it will show 11.