Incrementing a counter variable in verilog: combinational or sequential - hardware

I am implementing an FSM controller for a datapath circuit. The controller increments a counter internally. When I simulated the program below, the counter was never updated.
reg[3:0] counter;
//incrementing counter in combinational block
counter = counter + 4'b1;
However, on creating an extra variable, counter_next, as described in Verilog Best Practice - Incrementing a variable and incrementing the counter only in the sequential block, the counter gets incremented.
reg[3:0] counter, counter_next;
//sequential block
always #(posedge clk)
counter <= counter_next;
//combinational block
counter_next = counter + 4'b1;
Why doesn't the counter get incremented in the previous case? Anything I'm missing?

Ok. I'm assuming that you left some code out of your first example since that shouldn't even compile. However, I think I can elucidate the issue for you anyway.
In a block that looks like this:
always #(*) begin // or always #(counter)
counter = counter + 4'b1;
end
there are two problems.
1) counter is never initialized. All 'reg' type variables are X at the start of simulation time so adding 1 to X is X.
2) This is what is considered a combinational loop. The block is sensitive to changes in 'counter' so even assuming that 'counter' was initialized to 0 the simulator would loop forever updating 'counter' and simulation time will never advance. i.e.
always block executes -> counter = 1
counter has changed
always block executes -> counter = 2
counter has changed
and so on...
If you were to put a $display statement in there you could see this loop occurring. Otherwise it'll just appear that the simulator is hung and no waves will be written.
The reason the 2nd example works is that you have a flip-flop breaking the combinational loop. At each clock edge 'counter' gets updated with the current value of 'counter_next'. Then the combinational block executes once (and only once) to calculate the new version of 'counter_next'.
You're still lacking an initialization of 'counter' through a reset clause or initial statement so for completeness.
reg [3:0] counter;
reg [3:0] counter_next;
always #(*) begin
counter_next = counter + 1;
end
always #(posedge clk or negedge rst_l) begin
if (!rst_l)
counter <= 4'b0;
else
counter <= counter_next;
end

Related

Verilog d flipflop circuit testing

I'm trying to construct a structural implementation of a circuit that consists of a d flipflop, it has inputs x and y, x and y are exclusive or'd and that result is exclusive or'd with the current state, and used as the input to the d flip flop. and it'll use the result state from the flipflop in the next run, etc. But I'm not too sure how to construct it.
The circuit looks like so:
module dff(D,clk,q);
input D,clk;
output q;
reg q;
always # (posedge clk)
begin
q<=D;
end
endmodule
I'm pretty sure the d flip flop code is correct but when I try to test this my d and state values are just x for some reason. When I put in different x and y values in my testbench nothing happens, "state" and "d" just always says it has value "1'hx" in the simulation. Why is this happening and how do I actually assign an value to them?
All signals in verilog simulation are initialized to 'x'. So are the values of A and D. Your second xor is applied to xoy ^ A. Since A is x, the result of this xor is always x. you need to break this loop, as oldfart suggested.
The usual way for doing it is to introduce a reset in the flop, synchronous or asynchronous. Here is an example of a synchronous reset flop:
always #(posedge clk)
if (reset)
q <= 0;
else
q <= D;
So, now, if you set your reset to '1' for at least one posedge of clk and then set it to '0', you will break the loop by pushing a non-'x' value in the data path.
You do not clear your D-FF. The output is X at the start and as you use that in a feedback loop it stays X.
This: wire state=1'b0; does not clear you FF. You have to clear 'q'.

clock pulse generator for a PLC

I am working with PLCs trying to design a water tank. On one section of the design I am asked to create a clock pulse generator. I am currently trying to do this using ladder diagrams.
I believe I have the logic correct just cant seem to put it together. I want a counter to count the clock pulses that I generate, then I store these pulese in a data memory to ensure the count is retained if the system is switched off and on.
question is how do I design this clock pulse generator.
Kind regards
There are a few different ways to create a pulse generator (or commonly known in the plc world as a BLINK timer). As a matter of fact many plc programming softwares have this function block built in to their function block libraries. But if they don't or you just want to make your own you can do something like this
VAR
ton1: TON;
ton2: TON;
StartPulse: BOOL;
startPulseTrig: R_TRIG;
LatchPulseInitial: BOOL;
PulseOutput: BOOL;
Timer1Done: BOOL;
Timer2Done: BOOL;
PulseWidth:TIME:=t#500ms;
END_VAR
If you would like to count the number of pulses and store this value to a variable you can use a simple CTU (counter up) block available in all plc languages.
Review of functionality
The StartPulse variable can be anything you want that will start the counter. In my case I just used an internal bool variable that I turned on. If you want this timer to start automatically when the plc starts then just initialize this variable to true. Because StartPulse only works on the rising edge of the signal the LatchPulseInitial coil will only ever be set once.
When the LatchPulseInitial variable goes true this will start ton1 a Timer On Delay (TON) function block. This will delay the output of the block from turning on for the time of PT (in my case I have 500ms).
After 500ms has expired the ton1 outputs will turn on. this will turn on the Timer1Done variable and turn off the Timer2Done and LatchPulseInitial. Now that LatchPulseInitial has been turned off it will never interfere with the program again since it can only be turned on by the rising edge of StartPulse. Note: once the block has reached PT the outputs will stay on until the input to the block is removed.
Since Timer1Done is now on ton2 will start counting until PT is reached. Once PT is reached the outputs for that block will turn on. This will reset Timer1Done and set Timer2Done This will start ton1 again and thus starting the whole process over.
For the PulseOutput, which is the actual pulse output you are looking for, I have this being set to true when Timer2Done is true. This is because when this variable is true it is the high state of the pulse generator. When Timer1Done is true it is the low state of the pulse generator.
When the PulseOutput goes true it will trigger the input on the CTU which will increment the count of the variable in CV (current value) by 1.
If you are going to be using this logic in numerous places in your program or you plan on reusing it in the future I would make this into its own function block so you won't have to repeat this logic everytime you want to make this type of timer.
Once I had to create a BLINK FB. It is written in Structured Text. But it is suitable to use in a ladder logic program and IN/OUT Variables are named like TON style. The Blink starts with Q = TRUE. If you want to start with FALSE just invert Q and switch the Times!
FUNCTION_BLOCK BLINK
VAR_INPUT
IN : BOOL;
PT_ON : TIME;
PT_OFF : TIME;
END_VAR
VAR_OUTPUT
Q : BOOL;
ET : TIME;
END_VAR
VAR
rtIN : R_TRIG;
tonBlink : TON;
END_VAR
rtIN(CLK := IN);
IF tonBlink.Q OR rtIN.Q THEN
(*Toggle Output*)
Q := NOT Q;
(*Timer Reset call, important to call timer twice in same cycle for correct Blink Time*)
tonBlink(IN:= FALSE);
(*Set corresponding Time*)
IF Q THEN
tonBlink.PT := PT_ON;
ELSE
tonBlink.PT := PT_OFF;
END_IF
END_IF
(*Timer Run call*)
tonBlink(IN:= IN);
IF IN THEN
ET := tonBlink.ET;
ELSE
ET := T#0S;
Q := FALSE;
END_IF
In my opinion, this is the most straightforward way to do it, using 1 timer, up counter and modulo operator:
Blink function in ladder
Also note, if your PLC doesnt have modulo, then multiply by -1 each time.

verilog assigning to same variable not working

I am having a strange problem with Verilog HDL.
I found in my code that if I multiply a variable by two, but then
assign that value to the same variable, it gets all messed up.
Sometimes, the simv program even crashes. I originally needed to do this,
because I had a for loop for shifting or rotating a certain amount. But,
then I found that not only shifting the same variable did not work, but
also, addition, subtraction, multiplication, or division does not work either.
So in my code example, if you set a to 16'b0001_0000_1010_0101, and b to 3,
then you get an output of 16'b0000_0000_0000_0000. Just note that I am ignoring b for now... I should get 16'b0010_0001_0100_1010... but something is going wrong.
So, this is my code file test.v:
// ALU module.
module test(in1, in2, out1);
input [15:0] in1;
input [15:0] in2;
output reg [15:0] out1;
// Variables for shifting right and for rotating left or right.
reg [15:0] shiftedValue;
always#(in1, in2)
begin
assign shiftedValue = in1;
assign shiftedValue = shiftedValue * 2;
assign out1 = shiftedValue;
// This display value is correct!
// but it's still wrong in the test bench.
$display("out1 == %b", out1);
end
endmodule
module testStim;
reg [15:0] a;
reg [15:0] b;
wire [15:0] c;
// create ALU instance.
test myTest(a, b, c);
initial
begin
a = 16'b0001_0000_1010_0101;
b = 3;
#10
$display("op1In == %b, op1Out == %b", a, c);
$finish;
end
endmodule
This is the output after running simv (I stripped out the erroneous garbage...):
out1 == 0010000101001010
op1In == 0001000010100101, op1Out == 0000000000000000
Thanks,
Erik W.
You have done what is called as procedural continuous assignment.
The difference between regular continuous assignments and procedural continuous assignments is this:
Continuous assignment can only drive wire/net data type. Procedural assignment can drive only reg data type and not nets.
Continuous assignment should appear outside procedural blocks(always, initial etc), while latter must be inside procedural blocks.
Continuous assignment executes each time the right hand side expression changes. Procedural assignment depends on sensitivity list of always block.
As soon as the always block ends, the effect of assign statement is removed. You must add deassign statement to retain the values (which I think is not the real intent) or Just remove assign statement from the code. As shown below:
shiftedValue = in1;
shiftedValue = shiftedValue * 2;
out1 = shiftedValue;
More information about assign, deassign is available at this, this and this links.

Passing values to module instance port through loops inside always block in verilog

I need to access ports of module instance through for loop using verilg code, i'm trying to send inputs to a module instance repeatedly hoping every time the output for corresponding input get updated, unfortunately it is not happening because the inputs get passed only after execution exit the procedural block, please find the below code and let me know the possibilities, thanks in advance.
integer i,j;
always#(g_mtx,gi_mtx)
begin
for (i=1;i<3;i=i+1)
for (j=1;j<3;i=j+1)
if(i!=j)
begin
L_in1=g_mtx[j][j];
L_in2=gi_mtx[i][i];
L_in3=gi_mtx[j][i];
L_in4=g_mtx[j][i];
Lmd[i][j]= L_out ;
end
end
Lamda_top lmd (L_out,L_in1,L_in2,L_in3,L_in4,clk);//instance
//here g_mtx,gi_mtx,Lmd are memories.
The solutions differ depending on the context.
If this is for a testbench, all you need do is add some form of delay after simulating the inputs. Seeing as you are using a clock for the Lamda_top module, you can use the same clock as the delay source to ensure enough time has passed:
always #(g_mtx,gi_mtx) begin
for (i=1; i<3; i=i+1) begin
for (j=1; j<3; j=j+1) begin
if(i!=j) begin
L_in1=g_mtx[j][j];
L_in2=gi_mtx[i][i];
L_in3=gi_mtx[j][i];
L_in4=g_mtx[j][i];
repeat ([number of cycles it takes for Lamda_top to finish]) begin
#(posedge clk);
end
#(negedge clk); // Ensure L_out has gotten the value from the function
Lmd[i][j] = L_out;
end
end
end
end
However, if this is instead for actual, synthesizable code, you will need to implement some sort of FSM to serialize the for-loops to only input one set of L_inX variables at a time.
Ultimately, both solutions involve ensuring that only one set of L_inX is passed through for each clock. Without knowing more context, its hard to say how best to handle this (should probably be some sort of pipeline, but thats alot more work to patch the provided code to implement)

signal vs variable

VHDL provides two major object types to hold data, namel signal and variable, but I can't find anywhere that is clear on when to use one data-type over the other. Can anyone shed some light on their strengths/limitations/scope/synthesis/situations in which using one would be better than the other?
Signals can be used to communicate values between processes. Variables cannot. There are shared variables which can in older compilers, but you really are asking for problems (with race conditions) if you do that - unless you use protected types which are a bit like classes. Then they are same to use for communication, but not (as far as I know) synthesisable.
This fundamental restriction on communication comes from the way updates on signals and variables work.
The big distinction comes because variables update immediately they are assigned to (with the := operator). Signals have an update scheduled when assigned to (with the <= operator) but the value that anyone sees when they read the signal will not change until some time passes.
(Aside: That amount of time could be as small as a delta cycle, which is the smallest amount of time in a VHDL simuator - no "real" time passes. Something like wait for 0 ps; causes the simulator to wait for the next delta cycle before continuing.)
If you need the same logic to feed into multiple flipflops a variable is a good way of factoring that logic into a single point, rather than copying/pasting code.
In terms of logic, within a clocked process, signals always infer a flipflop. Variables can be used for both combinatorial logic and inferring a flipflop. Sometimes both for the same variable. Some think this confusing, personally, I think it's fine:
process (clk)
variable something : std_logic;
if rising_edge(clk) then
if reset = '1' then
something := '0';
else
output_b <= something or input c; -- using the previous clock's value of 'something' infers a register
something := input_a and input_b; -- comb. logic for a new value
output_a <= something or input_c; -- which is used immediately, not registered here
end if;
end if;
end process;
One thing to watch using variables is that because if they are read after they are written, no register output is used, you can get long chains of logic which can lead to missing your fmax target
One thing to watch using signals (in clocked processes) is that they always infer a register, and hence leads to latency.
As others have said signals get updated with their new value at the end of the time slice, but variables are updated immediately.
// inside some process
// varA = sigA = 0. sigB = 2
varA := sigB + 1; // varA is now 3
sigC <= varA + 1; // sigC will be 4
sigA <= sigB + 1; // sigA will be 3
sigD <= sigA + 1; // sigD will be 1 (original sigA + 1)
For hardware design, I use variables very infrequently. It's normally when I'm hacking in some feature that really needs the code to be re-factored, but I'm on a deadline. I avoid them because I find the mental model of working with signals and variables too different to live nicely in one piece of code. That's not to say it can't be done, but I think most RTL engineers avoid mixing... and you can't avoid signals.
Other points:
Signals have entity scoping. Variables are local to the process.
Both synthesize