module counter (clk,rst,enable,count);
input clk, rst, enable;
output [3:0] count;
reg [3:0] count;
always # (posedge clk or posedge rst)
if (rst) begin
count <= 0;
end else begin : COUNT
while (enable) begin
count <= count + 1;
disable COUNT;
end
end
endmodule
(Source: http://www.asic-world.com/verilog/verilog_one_day2.html#While)
From what I have learnt, <= is a relational operator and it will return 1 if true and 0 if false, but where does it return in this code?
In the context of your code, <= is not a relational operator, it is an assignment operator. There are two types of assignment in Verilog:
blocking : =
non-blocking : <=
In a Verilog design, you
always use blocking assignments for combinational logic
always use non_blocking assignments for sequential logic
If you do not, you simulation will be indeterminate - it will not necessarily behave the same way every time you run it. Which, of course, is not good.
So, why is that? Well, to start you must learn that Verilog has 4 scheduling regions:
from prev time step
|
ACTIVE
|
INACTIVE
|
NBA
|
POSTPONED
|
V
to next time step
Blocking assignments are executed in the ACTIVE region. However, while the right-hand side of a non-blocking assignment is evaluated in the ACTIVE region, the assignment does not occur until the NBA region. This is key to why you need to use them for sequential logic.
So, why do you need to use non-blocking assignments for sequential logic? The reason is because the delay between evaluation of the right-hand side and assignment of the left hand side enables a Verilog simulation to be determinate, ie to behave the same way every time you run it. This delay means that the behaviour of the simulation does not depend on the order in which the always blocks are executed, which it would if only blocking assignments were used.
A simple analogy to the delay between evaluating the right-hand side of a non-blocking assignment and assigning the left-hand side is the clock-to-Q delay of a real flip-flop. In a real flip-flop, there is always a small delay (clock-to-Q delay) between the D input being sampled (by the clock) and the Q output being driven. This is vital to the correct operation of real sequential logic. For example, if there were no clock-to-Q delay in a real flip-flop instead of it taking exactly 4 clocks for the D input of the first flip-flop in a 4-stage shift register to get to the Q output of the fourth flip-flop, it could take any number of clocks between 1 and 4: its behaviour would also be indeterminate.
Related
I have got two identical (by means of simulation) flip flop process in verilog.
First is just a standard description of register with asynchronous reset (CLR) and clock (SET) with data in tied to 1:
always #(posedge SET, posedge CLR)
if (CLR)
Q <= 0;
else
Q <= 1;
second one is the same as above but with second if condition for SET signal:
always #(posedge SET, posedge CLR)
if (CLR)
Q <= 0;
else if (SET)
Q <= 1;
There is no differences between these two implementations of flip-flop in simulation. But what does the verilog standard says about this cases? Should these tests be equivalent as well as their netlists after synthesis process?
The "if (SET)" in your second example is redundant and would be optimized away n synthesis. Since the always block will only be entered on a posedge of SET or CLR, the else statement implies that a posedge of SET has occurred.
Incidentally, the first example is a much more accepted version for coding flip flops. I've yet to see the second version make it into a shipping design.
I made a basic example on eda playground of the issue I got.
Let s say I have two clocks 1x and 2x. 2x is divided from 1x using flop divider.
I have two registers a and b. a is clocked on 1x, b is clocked in 2x.
b is sampling value of a.
When we have rising edge of 1x and 2x clocks, b is not taking the expected value of a but it s taking the next cycle value.
This is because of this clock divider scheme, if we make division using icgs and en it works fine.
But is there a way to make it work using this clock divider scheme with flops ?
EDA playground link : https://www.edaplayground.com/x/map#
module race_test;
logic clk1x = 0;
logic clk2x = 0;
always
#5ns clk1x = !clk1x;
int a, b;
always #(posedge clk1x) begin
a <= a+1;
clk2x <= !clk2x;
end
// Problem here is that b will sample postpone value of a
// clk2x is not triggering at the same time than clk1x but a bit later
// This can be workaround by putting blocking assignment for clock divider
always #(posedge clk2x) begin
b <= a;
end
initial begin
$dumpfile("test.vcd");
$dumpvars;
#1us
$stop;
end
endmodule
Digital clock dividers present problems with both simulation and physical timing.
Verilog's non-blocking assignment operator assumes that everyone reading and writing the same variables are synchronized to the same clock event. By using an NBA writing to clk2x, you have shifted the reading of a to another delta time*, and as you discovered, a has already been updated.
In real hardware, there are considerable propagation delays that usually avoid this situation. However, you are using the same D-flop to assign to clk2x, so there will be propagation delays there as well. You last always block now represents a clock domain crossing issue. So depending on the skews between the two clocks, you could still have a race condition.
One way of correcting this is using a clock generator module with an even higher frequency clock
always #2.5ns clk = !clk;
always #(posedge clk) begin
clk1x <= !clk1x;
if (clk1x == 1)
clk2x = !clk2x;
Of course you have solved this problem, but I think there is a better way.
The book says one can use blocking assignment to avoid race. But blocking assignemnt causes errors in synopsys lint check. So, one way to avoid race problem without lint error is to use dummy logic, like this
wire [31:0] a_logic;
wire dummy_sel;
assign dummy_sel = 1'b0;
assign a_logic = dummy_sel ? ~a : a;
always #(posedge clk2x) begin
b <= a_logic;
end
What does the <= do in Verilog?
For example:
always #(posedge Clock) begin
if (Clear) begin
BCD1 <= 0;
BCD0 <= 0;
end
end
"<=" in Verilog is called non-blocking assignment which brings a whole lot of difference than "=" which is called as blocking assignment because of scheduling events in any vendor based simulators.
It is Recommended to use non-blocking assignment for sequential logic and blocking assignment for combinational logic, only then it infers correct hardware logic during synthesis.
Non-blocking statements in sequential block will infer flip flop in actual hardware.
Always remember do not mix blocking and non-blocking in any sequential or combinational block.
During scheduling process of simulator:
There are four regions and order of execution of commands as follows
1) Active region
--Blocking assignments
--Evaluation of RHS of non-blocking assignments(NBA)
--Continuous assignment
--$display command
--Evaluate input and output of primitives
2) Inactive region
--#0 blocking assignments
3) NBA(non-blocking assignment update)
--update LHS of non-blocking assignments (NBA)
4) Postponed
--$monitor command
--$strobe command
Using of blocking assignment "=" for two variable at the same time slot causes race condition
eg: Verilog code with race condition,
always #(posedge Clock)
BCD0 = 0; // Usage of blocking statements should be avoided
always #(posedge Clock)
BCD1 = BCD0;
In order to avoid race condition use non-blocking statement "<="
eg:
always #(posedge Clock)
BCD0 <= 0; // Recommended to use NBA
always #(posedge Clock)
BCD1 <= BCD0;
When this block is executed, there will be two events added to the non blocking assign update queue.
Hence, it does the updation of BCD1 from BCD0 at the end of the time step.
Using Non-blocking "<=" assignment in continuous assignment statement is not allowed according to verilog LRM and will result in compilation error.
eg:
assign BCD0 <= BCD1; //Results in compilation error
Only use NBA in procedural assignment statements,
- initial and
- always blocks
This is called a 'non-blocking' assignment. The non-blocking assignment allows designers to describe a state-machine update without needing to declare and use temporary storage variables.
For example, in this code, when you're using a non-blocking assignment, its action won't be registered until the next clock cycle. This means that the order of the assignments is irrelevant and will produce the same result.
The other assignment operator, '=', is referred to as a blocking assignment. When '=' assignment is used, for the purposes of logic, the target variable is updated immediately.
The understand this more deeply, please look at this example (from Wikipedia):
module toplevel(clock,reset);
input clock;
input reset;
reg flop1;
reg flop2;
always # (posedge reset or posedge clock)
if (reset)
begin
flop1 <= 0;
flop2 <= 1;
end
else
begin
flop1 <= flop2;
flop2 <= flop1;
end
endmodule
In this example, flop1 <= flop2 and flop2 <= flop1 would swap the values of these two regs. But if we used blocking assignment, =, this wouldn't happen and the behavior would be wrong.
Since people have already explained the blocking/non blocking situation, I'll just add this here to help with understanding.
" <= " replaces the word "gets" as you read code
For example :
.... //Verilog code here
A<=B //read it as A gets B
When does A get B? In the given time slot, think of everything in hardware happening in time slots, like a specific sampled event, driven by clock. If the "<=" operator is used in a module with a clock that operates every 5ns, imagine A getting B at the end of that time slot, after every other "blocking" assignments have resolved and at the same time as other non blocking assignments.
I know its confusing, it gets better as you use and mess up bunch of designs and learn how it works that way.
"<=" is a non-blocking assignment operator in verilog."=" is a blocking assignment operator.
Consider the following code..
always#(clk)
begin
a=b;
end
always#(clk)
begin
b=a;
end
The values of a and b are being exchanged using two different always blocks.. Using "=" here caused a race-around condition. ie. both the variables a and b are being changes at the same time..
Using "<=" will avoid the race-around.
always#(clk)
begin
a<=b;
end
always#(clk)
begin
b<=a;
end
Hope i helped too..
<= is a non blocking assignment. The <= statements execute parallely. Think of a pipelined architecture, where we come across using such assignments.
A small exammple:
// initialise a, b, c with 1, 2 and 3 respectively.
initial begin
a <= 1
b <= 2
c <= 3
end
always#(clock.posedge)
begin
a <= b
b <= c
c <= a
end
After the first posedge clock:
a = 2, b = 3, c = 1
After the second posedge clock:
a = 3, b = 1, c = 2
After third posedge clock:
a = 1, b = 2, c = 3
As most told, it is a "Non Blocking <=" assignment widely used for Sequential logic design because it can emulate it best.
Here is why :
Mostly involving a delay(here posedge clock) it is something like it schedules the evaluation of the RHS to LHS after the mentioned delay and moves on to the next statement(emulating sequential) in flow unlike "Blocking = " which will actually delay the execution of the next statement in line with the mentioned delay (emulating combinational)
I Want to Design a Verilog code for Interfacing 16*2 LCD. As in LCD's to give "command" or "data" we have to give LCD's Enable pin a "High to low Pulse " pulse that means
**E=1;
Delay();//Must be 450ns wide delay
E=0;**
This the place where I confuse I means in Verilog for synthesis # are not allowed so how can I give delay here I attached my code below. It must be noted that I try give delay in my code but I think delay not work so please help me to get rid of this delay problem......
///////////////////////////////////////////////////////////////////////////////////
////////////////////LCD Interfacing with Xilinx FPGA///////////////////////////////
////////////////////Important code for 16*2/1 LCDs/////////////////////////////////
//////////////////Coder-Shrikant Vaishnav(M.Tech VLSI)/////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
module lcd_fpgashri(output reg [7:0]data,output reg enb,output reg rs,output reg rw ,input CLK);
reg [15:0]hold;
reg [13:0]count=0;
//Code Starts from here like C's Main......
always#(posedge CLK)
begin
count=count+1; //For Delay
//For LCD Initialization
lcd_cmd(8'b00111000);
lcd_cmd(8'b00000001);
lcd_cmd(8'b00000110);
lcd_cmd(8'b00001100);
//This is a String "SHRI" that I want to display
lcd_data(8'b01010011);//S
lcd_data(8'b01001000);//H
lcd_data(8'b01010010);//R
lcd_data(8'b01001001);//I
end
//Task For Command
task lcd_cmd(input reg [7:0]value);
begin
data=value;
rs=1'b0;
rw=1'b0;
enb=1'b1; //sending high to low pulse
hold=count[13]; //This is the place where I try to design delay
enb=1'b0;
end
endtask
//Task for Data
task lcd_data(input reg [7:0]value1);
begin
data=value1;
rs=1'b1;
rw=1'b0;
enb=1'b1; //sending high to low pulse
hold=count[13]; //This is the place where I try to design delay
enb=1'b0;
end
endtask
endmodule
You seem to be stuck in a software programming mindset based on your code, you're going to have to change things around quite a bit if you want to actually describe a controller in HDL.
Unfortunately for you there is no way to just insert an arbitrary delay into a 'routine' like you have written there.
When you write a software program, it is perfectly reasonable to write a program like
doA();
doB();
doC();
Where each line executes one at a time in a sequential fashion. HDL does not work in this way. You need to not think in terms of tasks, and start thinking in terms of clocks and state machines.
Remember that when you have an always block, the entire block executes in parallel on every clock cycle. When you have a statement like this in an always block:
lcd_cmd(8'b00111000);
lcd_cmd(8'b00000001);
lcd_cmd(8'b00000110);
lcd_cmd(8'b00001100);
This does you no good, because all four of these execute simultaneously on positive edge of the clock, and not in a sequential fashion. What you need to do is to create a state machine, such that it advances and performs one action during a clock period.
If I were to try to replicate those four lcd_cmd's in a sequential manner, it might look something like this.
always #(posedge clk)
case(state_f)
`RESET: begin
state_f <= `INIT_STEP_1;
data = 8'b00111000;
end
`INIT_STEP_1: begin
state_f <= `INIT_STEP_2;
data = 8'b00000001;
end
`INIT_STEP_2: begin
state_f <= `INIT_STEP_3;
data = 8'b00000110;
end
`INIT_STEP_3: begin
state_f <= `INIT_STEP_4;
data =8'b00111000;
end
`INIT_STEP_4: begin
state_f <= ???; //go to some new state
data = 8'b00000110;
end
endcase
end
Now with this code you are advancing through four states in four clock cycles, so you can start to see how you might handle writing a sequence of events that advances on each clock cycle.
This answer doesn't get you all of the way, as there is no 'delay' in between these as you wanted. But you could imagine having a state machine where after setting the data you move into a DELAY state, where you could set a counter which counts down enough clock cycles you need to meet your timing requirements before moving into the next state.
The best way to introduce delay is to use a counter as Tim has mentioned.
Find out how many clock cycles you need to wait to obtain the required delay (here 450ns) w.r.t your clock period.
Lets take the number of clock cycles calculated is count. In that case the following piece of code can get you the required delay. You may however need to modify the logic for your purpose.
always # (posedge clk) begin
if (N == count) begin
N <= 0;
E = ~E;
end else begin
N <= N +1;
end
end
Be sure to initialize N and E to zero.
Check the clock frequency of your FPGA board and initialize a counter accordingly. For example, if you want a delay of 1 second on an FPGA board with 50MHz clock frequency, you will have to write a code for a counter that counts from 0 to 49999999. Use the terminalCLK as clk for your design. Delayed clock input will put a delay to your design. The psuedo code for that will be:
module counter(count,terminalCLK,clk)
parameter n = 26, N = 50000000;
input clk;
output reg [n-1:0] count;
output reg terminalCLK;
always#(posedge clk)
begin
count <= count + 1;
if (count <= N/2)
terminalCLK <= ~terminalCLk;
if (count == N)
terminalCLK <= ~terminalCLk;
end
I'm trying to learn Verilog using Pong P. Chu's book. I have a question about how an always block is evaluated and implemented. A style in the authors code is confusing me.
In this example he codes an FSM with two output registers 'y1' and 'y2'. The part I'm confused about is in the NEXT STATE LOGIC AND OUTPUT LOGIC always block, where after the begin statement and always#* y1 and y0 are set to 0. I seems that regardless of state, y1 and y0 will toggle to 0 on every clock cycle and signal change. According to state diagram in the book reg y1 should be equal to 1 while in state 0 or 1.
So does y1 toggle to 0 every clock cycle then back to what ever its value at the present state?? I assume that's not the case and that I'm just confused about how the block is evaluated. Can someone explain what that part of the code is doing. I'm lost. Thanks
module fsm_eg_2_seg
(
input wire clk, reset, a, b,
output reg y0, y1
);
//STATE DECLARATION
localparam [1:0] s0 =2'b00,
s1=2'b01,
s2=2'b10;
// SIGNAL DECLARATION
reg [1:0] state_reg, state_next ;
//STATE REGISTER
always #(posedge clk, posedge reset)
if (reset)
state_reg <= s0;
else
state_reg <= state_next;
//NEXT STATE LOGIC AND OUTPUT LOGIC
always #*
begin
state_next = state_reg; // default next state: the same
y1 = 1'b0; // default output: 0
y0 = 1'b0; // default output: 0
case (state_reg)
s0: begin
y1 = 1'b1;
if (a)
if(b)
begin
state_next = s2;
y0 = 1'b1;
end
else
state_next = s1;
end
s1: begin
y1 = 1'b1;
if (a)
state_next = s0;
end
s2: state_next = s0;
default: state_next = s0;
endcase
end
endmodule
The expression
always #* begin : name_of_my_combinational_logic_block
// code
end
describes combinational logic. Typically the clk and rst signals are not read from inside of this type of always block, so they don't appear in the sensitivity list like wisemonkey says. It is best practice to use #* for the sensitivity lists of combinational logic so that you don't forget to include a signal, which would infer some memory and it would no longer be combinational logic.
Inside a combinational logic block, you should use what are called blocking assignments. These look like regular variable assignments in most programming languages and use a single equals. The value that you assign to a variable (a reg) inside of a combinational logic block happens immediately with respect to other statements and expressions in that same combinational logic block, but does not propagate outside of this combinational logic block until you reach the end. The always block must reach the end before any changes are seen outside of the block. Paul S is right that you want to always assign something to your variables whenever the always block is executed, otherwise you will infer memory.
Have to say I disagree with aqua. What he (and wisemonkey) says about #* is right, but the rest is wrong.
Those two lines have nothing to do with an idle state. Those statements are there as good coding practise. They ensure that those two outputs are always assigned to when that always block is evaluated. Let's see why this is important:
Imagine that those two statements aren't there.
Next suppose that state_reg = S0, and a = b = 0
As we evaluate the always block, we enter the case statement, s0 half, and assign 1 to y1
a is zero so we don't enter the if statement, and we drop out of the case, and end the block
At the end of the block y1 == 1 and y0 == ... erm, hang on what does y0 get? I guess it has to keep it's old value. It didn't get a new one.
That means it's possible y0 has to remember it's value from one cycle to the next. That would mean it needs to have some kind of memory involved, like a register or a latch. In this case it would be a latch as it's written in a style that sometimes drives the output and sometimes holds it.
...but we don't want that. y1 and y0 were meant to be simple wires. Therefore we must make sure each of them are always assigned to, no matter what the state or inputs are. We could do that by having assignments in all the branches of the logic, but that becomes a lot of work. Alternatively we can have a default assignment which we later override if necessary.
The reason these statements don't introduce y1 going to 0 in s0 or s1 is because everything that happens inside an always block happens with no time passing. No time passes between the 0 being assigned at the top and the 1 in s0 or s1. All that's visible is the final state.
You'll note the code does exactly the same thing with the state variable. It has a default assignment that the next state is the current state, and then overrides that it the correct conditions are met.
Nice clean state machine. Nothing wrong with it.
This is a poor example of an FSM. I'm not surprised that you are confused. The way I understand it, an always block is scheduled to run only when the inputs in its sensitivity list change.
So for the first always block, it is scheduled to run every clock transition from 0 to 1, and reset is asynchronous.
The second always block has the #* notation, which basically creates a sensitivity list for you based on the logic within the block. Recall that only inputs matter in a sensitivity list. Therefore, this always block will be scheduled if a, b, or state_reg change.
In this example, the
y1 = 1'b0; // default output: 0
y0 = 1'b0; // default output: 0
is trying to model an IDLE state, a state where the FSM is outputting 0. If you do a quick study of how the FSM operates, you'll see that once it starts transitioning through the states, (the case statements) it won't come back out.
Ideally you want your IDLE information within a state of its own, not floating outside the state logic, but I suppose this works as a trivial example.
I don't think other answers directly and correctly addresses the question of whether y0 and y1 toggle to 0 and back on every clock cycle.
Let's say that the state machine changes from s0 to s1. In both states the end value of y1 is 1 but in re-evaluating the always block y1 is first assigned 0. This toggling may happen multiple times per clock, or not at all on a clock cycle depending how many times a, b, and state_reg change. Whether this toggling propagates to the wire attached to output y1 is simulator dependent. Port assignments are treated as continuous assignments in Verilog, which are separately running threads of execution. It is perfectly legal for the simulator to suspend execution of the always block after the y1=0 assignment is made, assign 0 to the wire attached to output y1, and resume execution of the always block afterwards. Practically speaking, it doesn't matter IF good coding styles are practiced because the value of y1 won't get latched into any registers until the next clock cycle, long after all the toggling is done and the final value of y1 is available.
In simulation the toggling happens in zero time but it also happens in real hardware when multiple inputs change. It takes special design practices to build logic that doesn't "glitch" like this.