Verilog state machine based on switch inputs and button presses - verilog

I'm running into some problems implementing a synthesizeable state machine to output the results from several lower-level modules I've already implemented. As far as I can tell, the structure I have so far wants nested always blocks, but that can't be done in Verilog. I'm not sure how to circumvent this problem.
EDIT: code taken down as at least one classmate has turned in identical (and non-functioning, lol) portions of my own code.

If you think you need nested always blocks then you are likely not thinking about hardware design, while RTL gives some abstraction from the electronic components it has to be written in such away that represent possible hardware behaviour.
always #* represents a combinatorial block.
always #(posdege clk) represents sequential logic, where the outputs are driven by flip-flops.
always blocks tell the simulator when to trigger the block for simulation, as everything is happening at once, it is all parallel. The simulator could not know when to schedule code not contained in these blocks.
You need to have always #(posedge KEY[0] and always #(posedge KEY[1] which each contain the case statement. If they are not to do anything for a particular case then hold or Zero the current values. You can have a default: case as a catch all for those unspecified.
Update
Regarding the rotate function you should be able to take the MSB to indicate if negative.
Use >>> to preserve sign bits. you might need to declare the reg/wires assigned or add $signed function
reg signed [msb:0] data_in;
always #(posedge clk) begin
if (data_in[msb] == 1'b0) begin
data_out <= data_in <<< 1;
end
else begin
data_out <= data_in >>> 1;
end
end
// or use $signed(data_in) >>> 1;

You appear to have everything inside an initial block, so looking for a posedge doesn't even make sense. In general, initial blocks are not synthesizable.
No, you can't nest always blocks and you shouldn't need to.
You should have a single always #(posedge KEY[1]) that contains all of the possible assignments to STATE. You can't make assignments to the same reg in different always blocks. Be sure to use non-blocking assignments.
Create additional always blocks for your other reg signals, ideally using one always block per signal.

Related

I have faced a problem with Verilog Multiplier Module

Picture given is a module I'd like to express.
MulCell
For some reason I had to bring up the Multiplicand or Multiplier from arrays of numbers using wire. ex)wire [3:0] abc = 4'b1111;
But very odd! When I assign specific value of wire abc to "Multiplier", it works well. However if I assign it to "Multiplicand", I see red lines just as in the picture. redline
Any idea what had gone wrong? Thanks
Code for MulCell
module MulCell(Multiplicand,Multiplier,Sin,Cin,Sout,Cout);
input Multiplicand,Multiplier,Sin,Cin;
output Sout,Cout;
reg Sout,Cout;
wire tmp;
assign tmp=Multiplicand&Multiplier;
always#(tmp) begin
{Cout,Sout} <= tmp+Sin+Cin;
end
endmodule
Code for testbench_MulCell
`timescale 1ns/1ns
module testbench_MulCell();
reg Multiplicand,Multiplier,Sin,Cin;
wire Sout,Cout;
MulCell MC(Multiplicand,Multiplier,Sin,Cin,Sout,Cout);
wire [3:0]abc;
assign abc=4'b1111;
initial begin
Multiplicand=abc[2];
Multiplier=1'b1;
Sin=1'b1;
Cin=1'b1;
#10 //expecting 11
Multiplicand=1'b0;
Multiplier=abc[1];
Sin=1'b1;
Cin=1'b1;
#10 $stop;//expecting 10
end
endmodule
I can be wrong, but it seems there's a race condition between assigning value to abc and running initial block. At the moment when initial block started running, the assign abc =.. isn't executed yet. That's why you get x/red_lines in waveform view.
Verilog is an event driven simulator. It means that every 'always...', 'assign' block has inputs and outputs. Inputs in always block is are represented by its sensitivity list. In your case that would be the tmp signal. The whole block will start evaluation if and only if a change of an input is detected.
Also in the module the initial is scheduled for execution once during the simulation and is always executed first, before any of the always blocks (except in special cases in system verilog). So, in your case first few statements of the initial block (before first #10) are executed before the assign statement. So, for the first 10 cycles value of abc will be `4bxxxx, which explains your red line. For the same reason the values. As a result, values of multiplicand and consequently of MC/tmp,Sout,Cout will also be 'x'.
At #10 you change the values of the variables, causing always block in MC to re-evaluate with new values. By that time abc is already set to 1111 and all 'x' disappear.
So, efficiently you simulated only the second set of values but hot the first.
The suggestion is: add a small delay in front of the initial block:
initial begin
#1
Multiplicand=abc[2];
Multiplier=1'b1;
Sin=1'b1;
This will delay execution of the statements and the value of 'abc' will be set by this time. You will have a short period (1) of the red line, but you will see results of the values you set.
Another possibility is to set value of abc in the initial block first, but you would need a reg variable to do so:
reg[3:0] abcSet;
assign abc = abcSet;
initial begin
abcSet = 4'b1111;
...
another thing, in your always block you use non-blocking assignment (<=). Do not! This is good for flops and latches but bad for simple combinatorial logic. Use the regular assignment there (=).
{Cout,Sout} = tmp+Sin+Cin;
Also, this always block will not be avaluated if you just change Sin or Cin and tmp stays the same. You should either add those into the sensitivity list:
always #(tmp, Sin, Cin)
or use always #* instead. Actually it is a good idea to always use this construct instead of regular V95 always blocks. This way you will avoid possible implicit latches in the design (as in your case in respect to missing parts of the sensitivity list).
Also, in general most of the modern designs are synchronous designs and use a clock signal for synchronization. In your case the multpliplier sell shoudl be synchronized as well, you would need to provide a toggling clock signal. In theis case your operation could look like the following:
always #(posedge clk)
{Cout,Sout} <= tmp+Sin+Cin;
It makes evaluation happen at positive edge of the clk signal, it it is the only member of the sensitivity list. All other signals should set before the clock change. And yes, it is a flop and <= is used there.

Verilog Synchronous state machine

I'm trying to design this state machine in verilog:
I was have:
`timescale 1ns/1ns
module labEightMachine(y, x,clk,clr)
output y;
input [1:2] x;
input clk, clr;
reg [1:2] q;
reg y;
reg nX;
always # (posedge clk)
begin
if(clr)
{q}<=2'b00;
else
q<= {nX}
end
always #(y,x)
begin
if(q==2'b00)
if(x==2'b00)
q<=2'b00;
else
q<=2'b01;
y<=1;
if(q==2'b01)
if((x==2'b00)||(x==2'b01))
q<=2'b00;
y<=0;
else
q<=2'b11;
y<=0;
if(q==2'b11)
if(x==2'b10)
q<=2'b10;
y<=1;
else
q<=2'b00;
y<=0;
if(q==2'b10)
q<=2'b00;
y<=0;
end
endmodule
If any one could help by telling me where it is incorrect, that would be greatly appreciated. The state machines confuse me and I'm not sure that I am reassigning everything correctly.
Applying stimulus is always a better way to check your code. Leaving the syntax errors of semi-colons/begin-end and all that, a couple of immediate logical errors I can see are as below.
The declaration reg nX declares a variable of single bit width. On the contrary, q is declared as reg [1:2] q, of two bits width.
Secondly,q is driven from two always blocks. If clr is LOW, then q is driven by nX. While, nX is never driven by any signal. So, the output will be x majority of times (leaving those race-conditions). Multiple driver issues.
Thirdly, it would be better to use if--else if--else ladder instead of multiple ifs. This will make the next_state logic clear.
A better FSM, might have two always blocks and one output logic block. One for sequential logic and other for combinational logic. Sequential block is used to update the current_state value by the next_state value. While, a combinational block is used to update the next state value according to inputs. The output logic must either have a separate block of continuous assignments or a procedural block.
Also, it might be convenient to use a case statement for next_state logic. This will be useful when too many states are interacting with each other in a single FSM. Using default in case statement is inevitable.
For further information on efficient FSM coding styles, refer to CummingsSNUG1998SJ_FSM paper and CummingsSNUG2000Boston_FSM paper.

Always block not behaving as expected

I am making a state machine in verilog to implement certain arithmetic functions based on user input. I've run into a snag, however; my first always block, the one that handles my reset and maintains the correct state, is not behaving as expected; it is not updating the state correctly. The code is as follows:
always # (posedge CLOCK_50 or negedge RESET) begin
if(RESET == 1'b0)
STATE <= BASE;
else
STATE <= NEXT_STATE; // this always block, and specifically this line, is //not executing correctly.
end
Here is the general output of the file when reset and then following three button presses (KEY[1]) with SW = 0000:
EDIT: waveform with actual CLOCK_50 and RESET signals added
http://imgur.com/0DUka21
As for my question, I just want to know what I am doing incorrectly with this section of code. I can think of no reason for it to behave this way. Thanks for any help you can provide.
EDIT2: FFS, I changed the block to negedge CLOCK_50 and now it's working. I'd really like to know why if you can tell.
Ah, I see what you did now. You're assigning STATE in both of your two always blocks (STATE <= STATE in the default of the case block). This is bad, as it's a race condition between the two blocks as to which gets actually assigned. In your case, the second block is overriding the first, such that STATE <= STATE gets executed every clock. You should not assign the same variable in more than one always block.
Also you should pay attention to those warnings, but they are referring to the always #(ENABLE) block. This is complaining because you are inferring weird latched behavior, because the output is depending on STATE and SW, but they are not in the sensitivity list. You should probably just make this a combinational block, and use the auto-sensitivity list always #*.
Every always block, as well as every statement outside of an always block, effectively runs in parallel.
Since you have "state" being driven by two always blocks, you're effectively having two wires feed into a single wire. In digital logic design, you just can't do that. (Excluding pull-up resistors and such, but that's another topic.)
In simulation, if the multiple wires driving that single wire have the same logical value, you can get the output you desire; but if they have different values, you'll get invalid or unpredictable output.
In synthesis, this will simply fail with a "multiple drivers" error.
Also, the sensitivity list for an always block should have one of three things in it:
A clock
A clock and an asynchronous reset
Every wire/reg that is used as an input to that always block (*)
Anything else can result in an unintentional latch, which will cause problems.
In case 3, you need to make sure that every wire driven in the always block has a default value. Anything else can result in an unintentional latch.
Lastly, you can't have circular assignments or you risk a logic loop. You have one by assigning next_state to itself. Anything "circular" requires a flip-flop, aka an always block of type 1 or 2 outlined above.

Verilog always block statement

i just want to know the difference between this two statement
always #(posedge CLK)
begin
state <= next_state;
end
AND:
always #(CLK)
begin
case(CLK)
1'b1:
state <= next_state;
1'b0:
state <= state;
end
Is there a difference between both ?
Thanks
Not quite. posedge detects these transitions (from the LRM):
Table 43—Detecting posedge and negedge
To 0 1 x z
From
0 No edge posedge posedge posedge
1 negedge No edge negedge negedge
x negedge posedge No edge No edge
z negedge posedge No edge No edge
So, 0->x is a posedge, for example. Your second example only detects cases where CLK ends up as 1, so misses 0->x and 0->z.
The IEEE Std. 1364.1(E):2002 (IEC 624142(E):2005), the Verilog register transfer level synthesis standard, states in Sec. 5.1 that an always block without any posedge/negedge events in the sensitivity list is combinational logic. I.e. the signals in the event list are ignored and the block is synthesized as if an implicit expression list (#(*), #*) was used. The following example is given in the standard ("Example 4" on page 14):
always # (in)
if (ena)
out = in;
else
out = 1’b1;
// Supported, but simulation mismatch might occur.
// To assure the simulation will match the synthesized logic, add ena
// to the event list so the event list reads: always # (in or ena)
(the comment is also copied from the standard document)
I.e. for a synthesis tool your second block is effectively:
always #*
begin
case(CLK)
1'b1:
state <= next_state;
1'b0:
state <= state;
end
which is just a multiplexer with CLK as select input, next_state as active-1 input and the output (state) fed back as active-0 input. A smart synthesis tool might detect that this is identical to a d-type latch with CLK as enable-input and create a d-type latch instead of a combinational loop. Note that the synthesis tool is not required to detect this latch because the code explicitly assigns state in all branches (compare Sec. 5.3. of the standard).
Either way this is different from the d-type flip-flop your first code example would synthesize to. This is one of many cases where Verilog-code has different meaning in simulation and synthesis. Therefore it is important to (1) write synthesizeable Verilog code in a way that avoids this cases and (2) always run post-synthesis simulations of your design (even if you are also using formal verification!) to make sure you have successfully avoided this pitfalls.
Functionally, those two circuits describe the same behavior in verilog, so I think there should be no difference.
However you should generally use the first style, as that is the one that is standard for writing synthesizable code, and most understandable by anyone else reading your code. The latter style, while describing the correct behavior, may confuse some synthesizers that don't expect to see clocks that are both sensitive to positive and negative edge.
The two blocks are VERY different.
The top one gives you a flip-flop while the bottom one gives you a latch with a multiplexer with the CLK as the select signal.
The critical difference between the two blocks is that the top one is a synchronous block i.e. the posedge clk part while the bottom one is asynchronous with the CLK level, not edge.
A verilog simulator could do left-hand sampling of CLK, effectively making the the case(CLK) version the same as a negedge CLK flop. Otherwise the simulator will treat it like a posedge CLK flop. It really depends how it is handled in the scheduler of specific simulator (or how a particular synthesizer will process it).
The most common codding styles all use the first condition. It is explicitly clear to the synthesizer and anyone reading the code that state is intended to be a flip-flop with a positive edge clocking trigger.
There is also a simulation performance differences. The posedge CLK performances 2 CPU operations every clock period, while the case(CLK) will perform 6 CPU operations every clock period. Granted in this example the differences is insignificance, but in large designs the poor coding used everywhere will add up to hours of simulation time wasted.

Verilog Multiple Signals Change In Sensitivity List of an Always Block

I was wondering whether it was possible for an always block to be executed only when multiple signals in the sensitivity list change together.
As in, suppose I have a signal 'in' and another 'posedge clk'. I want the always block to be executed when BOTH the signals change. Is it possible, and if yes, what is the syntax for it?
In general, no there is no way to do it, as this doesn't actually map to any kind of standard logic cells that one would typically synthesize. However if you describe what your ultimate goal is, I'm sure someone can point you in the right direction while still using synthesizable logic. I'm having a hard time imagining what you could want such a block for.
This an answer to the original question, not the problem revealed in the comments
As #Tim has mentioned there is no hardware construct which can do this. always #(posedge clk) create flip-flops which sample the data on the edge of a clk.
always #* blocks create combinatorial logic which is evaluated by the simulator when ever the right hand side of an assignment or a select signal changes.
If you had multiple 1 bit signals driven from D-type flip-flops you could XOR (^) the input (D) and output (Q) to create a, 1 clock cycle wide, signal indicating the value has changed. These change signals could be combined to create an enable signal. Which is used as a select or enable for a flip-flop.
always #(posedge clk or negedge rst_n) begin
if (~rst_n) begin
//reset condition
end
else if (enabled)
//Enabled condition
end
// no final else, everything will holds its value
end
Or may be as the enable for a latch :
//synopsys async_set_reset "rst_n"
always #* begin
if (~rst_n) begin
// Reset
end
else if (latch_open) begin
//next datavalue
end
end

Resources