Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Understanding Verilog Code

43 views
Skip to first unread message

Rupinder Goyal

unread,
Sep 28, 2021, 1:52:24 AM9/28/21
to
Hi, I am new to verilog. I have written a code but the output is not as expected. I want to know how to interpret the code so that I can debug it? Can someone help me out?
The module will get the input bit by bit ( from LSB side) and output a single bit everytime. Output till any particular moment is the 2's complement form of the input read till now.
What I want to do is: Outputbit and nextstate change according to inputbit and prestate and then prestate gets the value of nextstate.
What actually happening is: The code calculates the nextstate , assigns it to prestate and then outputbit is calculated according to the prestate.

Please help me understand the code and how to correct it.


`timescale 1ns / 1ps

module twoComplement(inputBit, clk, reset, outputBit);
input inputBit, clk, reset;
output reg outputBit;
reg preState, nextState;
parameter Carry1 = 1, Carry0 = 0;

always @ (posedge clk)
begin
if (reset)
preState <= Carry1;
else
preState <= nextState;
end

always @(*)
case (preState)
Carry1: begin
outputBit = inputBit ? 1 : 0;
nextState = inputBit ? Carry0 : Carry1;
end
Carry0: begin
outputBit = inputBit ? 0 : 1;
nextState = Carry0;
end
default: begin
outputBit = 0;
nextState = Carry1;
end
endcase
endmodule



TestBench

`timescale 1ns / 1ps

`include "Q1.v"

module testbenchFortwoComplement;
reg inp, reset, clock;
wire out;

twoComplement a(inp, clock, reset, out);

initial begin
inp = 0;
clock = 1;
reset = 1;

#5 reset = 0;
#5 inp = 0;
#5 $display("%b", out);
#5 inp = 0;
#5 $display("%b", out);
#5 inp = 1;
#5 $display("%b", out);
#5 inp = 1;
#5 $display("%b", out);
#5 inp = 1;
#5 $display("%b", out);
#5 inp = 0;
#5 $display("%b", out);
#5 inp = 1;
#5 $display("%b", out);


#10 $finish;
end

always begin
#5 clock = ~clock;
end
endmodule

Motaz

unread,
Sep 29, 2021, 8:54:54 AM9/29/21
to
Hi,
I think the issue is caused by the process of updating the preState.
It depends on the clk to update the preState, while the FSM that calculates the outputBit and nextState updates its values each time ANY signal inside of it is modified. Meaning that the calculation process updates its values multiple times before the the preState gets assigned a new value.

always @ (posedge clk)
begin
if (reset)
preState <= Carry1;
else
preState <= nextState;
end

I would recommend update the preState reg in the same process as you calculate the outputs of the design .

- Motaz
0 new messages