# Counter in verilog

i want to make a counter that increases by the value of its inputs, but i did the testbench and the output is undetermined, xxxx. Can someone tell me if there is something wrong in this code?

    //Count

module count(clk,

rst, val, coin

);

input  clk, rst;
input  [3:0] coin;
output [3:0] val;

reg [3:0] val;
reg [3:0] nval;

always @(posedge clk, negedge rst)
if(rst == 0) val <= 4'b0000;
else val <= nval;

always @(val)
nval <= val + coin ;
endmodule

• I mostly using VHDL, and my verilog is very rusty, but it seems weird to me that you declare an output called val, and a reg called val as well. If that's legal in Verilog, my apologies. Might be worth using different name for clarity anyway. – MAB Oct 6 '17 at 19:04
• This is where you learn to debug. – Brian Drummond Oct 6 '17 at 19:13
• @MAB i understand your point. In fact what i was trying to do was to declare the output as a reg but it might be wrong. Thank you anyways, i'm going to check it. – Mel J Oct 6 '17 at 19:15

You are not assigning initial value to nval anywhere, so all further values depends on this, therefore val is undetermined.

Hard to be sure without testing that there is nothing else, but I think it's this

always @(val)
nval <= val + coin ;


As a non=blocking assignment, it will possibly take the old value of val (i.e. X) at reset. You could use a blocking assignment, and fill out the sensitivity list properly:

always @(val or coin)
nval = val + coin;


or use an assign:

wire [3:0] nval;
assign nval = val + coin;


Doing anything else is likely to cause problems (if not here, with other code).