The Verilog standard guarantees that all events within a begin..end
block scheduled for the same simulation time will be processed in the order they are declared. Other than in this specific scenario every other event may be taken out of the queue in any order.
With this said, any behavior can be expected because both events are scheduled for the same simulation time in different code blocks.
Nevertheless, the behavior you have is what is generally accepted as correct, because data is not sampled in the same simulation time where it is generated.
Things you could do to improve predictability:
Generate your clock using a blocking assignment.
always #10 clk = ~clk;
Generate stimuli on clock events.
initial
begin
repeat (2) @(posedge clk)
x <= 1;
end
This coding will, in general, guarantee that the RTL simulation will behave as the final gatelevel netlist without requiring data delays. In an RTL simulation, data must not be generated and sampled in the same simulation time.
You can solve this question with a shift and kill method.
Let's say you have N input bits and N is 16.
Step 1)
Load a N bit wide shift register with your input in parallel. Add a zero bit at LSB.
0111 1010 0111 0011|0
reset your result counter to 0
Step 2)
Perform a 'shift' operation that expands existing zeros to the left neighbor bit.
0111 1010 0111 0011|0
0111 0000 0110 0010|0
Increment the result counter.
Step 3)
Check if the register is all zero.
false -> repeat step 2 and 3
true -> result counter holds your longest one sequence.
Example:
0111 1010 0111 0011|0 cnt=0 / input
0111 0000 0110 0010|0 cnt=1
0110 0000 0100 0000|0 cnt=2
0100 0000 0000 0000|0 cnt=3
0000 0000 0000 0000|0 cnt=4 / done
Minimum execution time is 1 load and 1 compare -> can be solved in 1 cycle.
Maximum execution time is 1 load and N shifts -> 17 cycles in the example.
Real execution time is 1 load and n shifts if n is the length of the longest one sequence -> 5 cycles in the example.
How to calculate the bits while shifting?
Let's name the shift register a
.
a(0) := 0
for i in 1..N-1
a(i) := a(i) and a(i-1)
next
How many hardware is used?
- N registers for a
- N LUTs for load and shift before each register
- a ld(N+1) bit counter
- a N bit zero comparator
On Xilinx hardware:
Xilinx FPGAs have 6-input LUTs which can be used as 2 5-input LUTs moreover there are 2 FF per LUT. Synthesis can map a 16 bit shift register into only 2 slices and the comperator into a third slice.
As requested - a 5 bit counter
reg [4:0] counter;
always @(posedge Clock)
begin
if(Reset)
counter <= 5'b0;
else if(counter_en)
counter <= counter + 1;
end
Best Answer
Equality and Relational Operators (return X if an operand has X or Z)
Identity Operators (compare logic values 0, 1, X, and Z)
Example
If reg a is less than 2'b10, store 2'b11 in a.
Caveats
Source: "Verilog HDL Quick Reference Guide based on the Verilog-2001 standard (IEEE Std 1364-2001)" by Stuart Sutherland