Build state machine with 2 variables - state-machine

I am new with Modelica but I would like to build an easy state machine with 2 variables :
The initial step is "off" (the variable Light_cabin==0) then if button_Evac == 1 (second variable) then go to step "on" and Light_Cabin == 1 if Button_Evac==0 return to initial step.
This is my state machine :
state_machine
But when I launched the simulation Light_Cabin = 0 even if button_Evac = 1 and the active step is the initial step.
This is my code :
model StateMachine
block Off
outer output Integer Light_Cabin;
equation
Light_Cabin = 0;
end Off;
block On
outer output Integer Light_Cabin;
equation
Light_Cabin = 1;
end On;
parameter Integer Button_Evac(start=0);
inner Integer Light_Cabin(start=0);
Off off;
On on;
equation
transition(
off,
on,
Button_Evac == 1,
immediate=true,
reset=false,
synchronize=false,
priority=1);
transition(
on,
off,
Button_Evac == 0,
immediate=true,
reset=false,
synchronize=false,
priority=1);
initialState(off);
end StateMachine;
If you have any idea where my error is please let me know.
Thank you for your help,
Eloise

This is due to the design of state machines in Modelica, as can be seen in https://specification.modelica.org/v3.4/Ch17.html#semantics-summary
Even though the transition is immediate the state is active one clock tick. If that wasn't the case there would be a risk of infinite loops if all transitions are immediate - which would require additional semantic checks.
It technically not starting in "off", but a separate "initial state" and in the first clock tick the state machine transitions to "off" and thus cannot transition further in that clock tick.

Related

How to print system verilog coverage bin value at end of simulation?

I want to find out how many times the state machine went through the following sequence of states by displaying the count at the end of the simulation.
I could not find a way to dump the value of the bin "b" in the code below.
interface i;
typedef enum { S0, S1, S2, S3} state_e;
state_e state;
assign state = dut1.sm_state;
covergroup my_cg #(state);
coverpoint state {
bins b = (S0 => S1 => S2 => S3);
}
endgroup
my_cg cg1 = new();
final begin
$display("COVERAGE:CG1.state:%0d", cg1.state.get_coverage());
end
endinterface
Currently the output gives 100 if the sm went through the arc even once. I would instead like the count how many times it went through the arc.
get_coverage does not give you a count of bin hits—it only gives you the percent of bins hit, or the ratio of bins hit to the total number of bins. For performance, most tools stop counting after the bin has met its required minimum hits, just 1 hit by default. This saves not only the counting, but also evaluating the set of selection expressions that determine which bin to hit.
For debug, most tools give you a way of reporting the actual bin hit counts for the entire simulation.

Counting of different channels diverge and jumps

I'm trying to realize a counting module. My basic setup:
FPGA (Digilent's Arty with Xilinx Artix-35T) with two BNC cables attached to IO ports connected to a signal generator and via USB/UART to the PC for reading out. My signal generator produces with, say, 1 Hz some TTL signal.
I now want to count the amount of events in channel 1, in channel 2 and the coincidences of channels 1 and 2. While the basic principle works, I see channels 1 and 2 separate, even though they have the same input (via BNC-T connector). Also, sometimes one of the output channels jumps - in either direction, see figure.
The violet channel ("Channel 1") has a different slope than green ("Channel 2"). Also the coincidences make here two little lossy jumps.
My sequential counting code looks like
reg [15:0] coinciInt [(numCoincidences -1):0]; // internally store events
always #(posedge clk or posedge reset) // every time the clock rises...
begin
signalDelay <= signal; // delayed signal for not counting the same event twice
if(reset) // reset
begin
for(i=0;i<numCoincidences;i=i+1)
coinciInt[i] <= 16'b0;
end
else // No reset
begin
for(i=1;i<numCoincidences;i=i+1) // loop through all coincidence possibilities:
begin
if( ((signal & i) == i) && ((signalDelay & i) != i) ) // only if signal give coincidence, but did not give before, it's a coincidence
begin // "(signal & i) == i" means that "signal" is checked if bitmask of "i" is contained:
// ((0011 & 0010) == 0010) is true, since 0011 & 0010 = 0010 == 0010
coinciInt[i] <= coinciInt[i] + 1'b1; // the i-th coincidence triggered, store it
end
end
end
end // end of always
assign coinci = coinciInt; // the output variable is called coinci, so assign to this one
Please note that all events are in the register coinci - coincidences as well as 'single events'. Ideally, coinci[1] should store events of channel 1, coinci[2] these of channel 2 and coinci[3] coincidences between 1 and 2, since channels are labelled by 1,2,4,8,...,2^n and coincidences by the respective sum. coinci[0] is used for some kind of checksum, but that's off-topic now.
Are there any ideas for the missing counts? For the different slopes?
Thank you very much
Edit 1
#Brian Magnuson pointed to the meta stability issue. Using multi-buffered inputs solved the issue of diverging channels. That works nicely. Although I don't fully understand the reason for this, I also did not see any jumps in the coincidence channel so far. You probably save me a lot of time, thanks!
I would suspect a meta-stability problem. Your incoming pulses on ch1/ch2 are probably not synchronized with the system clock you are using. See here.
Because of this you are probably sometimes catching the counter updates 'mid-stride' so to speak which will cause unexpected behavior.
To fix this you can flop the inputs twice (called a dual-rank synchronizer) before feeding them into the rest of your logic. Usually multi-bit synchronization requires a bit more careful handling but in your case each bit can be treated independently.

Non blocking Statements execution in verilog

I am new to verilog, can anyone please explain me how does these statements execute.
always#(posedge clock) begin
A <= B ^ C;
D <= E & F;
G <= H | J;
K <= G ? ~&{A,D} : ^{A,D}
end
As far I can tell, the right side is first executed. Hence, the values for A, D, G, K are first calculated. While calculating value for K, depending on value of G the either first or second expression would execute. Can anyone please explain this operation. Please also tell how the last statement gets synthesized as this entire code is inside a always block and with positive edge clock. Thanks in advance.
A nonblocking assignment evaluates the RHS expression at the
beginning of a time step and schedules the LHS update to take place at the end of the time step.
In Verilog, there is a well defined event queue as shown below. For each and every timestamp, all the regions are evaluated. If there are any events to be executed in current timestamp, then they are triggered. Once all the events of current timestamp are triggered, then only simulation time moves forward.
Here, the RHS of ALL the expressions are evaluated at the beginning of the timestamp of posedge of clock. Hence, the values of B^C, E&F,H|J,G ? ~&{A,D} : ^{A,D} are evaluated and stored internally in the simulator.
Thereafter, the LHS are updated as the simulation progresses to NBA region of the same timestamp.
The values of G,AandDare not updated in active region. Hence, while calculating the value ofK, the previous values ofG,AandDare taken in the Active region. Then, all the veriables;G,A,DandK` are updated simulatanously.
I have made an example code over EDAPlayground. The waveforms might be helpful.
As far as last statement is concerned, I guess it will create a flop with mux (with Select=G and Inputs as nand(A,D) , xor(A,D) ) as input.

Verilog: detect pulses larger than tmax

I have a question and I hope somebody can give me a hint to solve the problem.
I need a verilog code to make a signal "reset" goes high immediately if the period of input signal "in" is larger than tmax.
Signal "reset" should go low again at the next positive edge of "in" (if there is a next positive edge)
If the period of input signal "in" is smaller than tmax then signal "reset" should remain low.
Example 1.
tmax=100ns
period(in) = 80ns
reset remains low all the time
Example 2.
tmax=100ns
period(in) = 130ns
reset goes high 100ns after the first positive edge of "in"
reset goes low at the next positive edge of "in", if there is a second pulse
Where should I start?
How about this. You will still have to do your check to see if Tmax is exceed, but you get a 1 timescale resolution between results.
always # (*)
begin
while(1)
begin
current_time = $realtime;
if (last_time > 0.0) freq = 1.0e9 / (current_time - last_time);
last_time = current_time;
# 1; // This allows for 1 timescale between loops. If you leave
// this out, most simulators become non-responsive in the loop.
end
end

How do you move non-zero elements in an array to the top in a single cycle?

I have the following 8-bit array:
0
4
0
0
5
0
2
0
How do I make it to the following in a single cycle (without iterating the element one by one)?
4
5
2
0
0
0
0
0
I know how to do it in software (MATLAB), but I'm not sure how to do it with combinational logic.
% initialise temporary vectors
TempType = zeros(maxType,1);
TempStart = zeros(maxType,1);
TempStop = zeros(maxType,1);
index = 1;
% remove zero elements from the middle
for j = 1:maxType
if (PreType(j) > 0 && PreStart(j) > 0 && PreStop(j) > 0)
TempType(index) = PreType(j);
TempStart(index) = PreStart(j);
TempStop(index) = PreStop(j);
index = index + 1;
end
end
I think any simplified sorting algorithm can do the job. For example, here is a modified bubble sort solution implemented in a single cycle:
module MoveZeros;
parameter W1 = 8;
parameter W2 = 10;
integer i, j;
logic [W1-1:0] array[W2-1:0] = {0,4,0,0,5,0,2,0,0,1};
logic [W1-1:0] temp;
always_comb begin
for (i=W2-1 ; i >=0 ; i=i-1)
for (j=W2-1 ; j >= 0 ; j=j-1)
begin
if (array[j]==0 && array[j-1] != 0) begin
temp = array[j];
array[j] = array [j-1];
array[j-1] = temp;
end
end
end
endmodule
output:
# array = '{4, 5, 2, 1, 0, 0, 0, 0, 0, 0}
Working example on edaplayground. Depending on your cycle time and the width of your input array (W2), you may want to break this algorithm into multiple cycles.
Synthesis tools unroll loops, therefore, the synthesized circuit will have O(W2^2) comparators and multiplexers, which can explode. Hence for bigger arrays, a multi-cycle solution is the way to go.
This is not an answer, which would take several hours of work, but SO's comments are not up to this sort of question. You should ask on comp.arch.fpga, if it's still alive.
Start by finding a datasheet for one of the old asynchronous fall-through FIFOs; these will include a circuit diagram. You don't really want to do anything like this, because the stage-to-stage handshaking is hairy, and you can't apply all 8 values simultaneously, but it'll give you ideas for a more synchronous implementation. Adapting a fall-through FIFO to do what you want is trivial - just ignore zero inputs.
If you can go up to 8 clock cycles, a more synchronous implementation is easy, with relatively limited hardware.
One cycle doesn't look too difficult, but will use more hardware. How sure are you that you must do it in one cycle? How much hardware can you use? If you've got a free PLL/DLL I'd be inclined to use that to get an 8x clock.
EDIT
Actually, with the benefit of more than 2 minutes thought, this seems pretty easy, even in one cycle.
Say you've got 8 registers with your 8 inputs (I0-I7), and 8 output registers (Q0-Q7). Each output register has associated logic which selects an input register for source data. The Q0 selector finds the lowest-numbered I register which contains non-zero data. The Q1 selector finds the next highest I register which contains non-zero data, and so on. Each selector drives a mux which loads the corresponding output register. Q0 requires an 8-1 mux (eight 8-bit inputs from I0-I7, one 8-bit output which goes to the input of Q0). Q1 requires a 7-1 mux (the inputs can only be I1-I7), and so on, until Q7, which doesn't require a mux at all (it can only be driven by I7).
The only smarts are in the selectors which find the source data for each output register. The Q7 selector is trivial; Q7 can only select I7, and only if all of I0-I7 contain non-zero data. Q6 is a bit more complicated, and so on.
If you can't see how to code a selector, ask specifically about that one in a new question, to avoid all the comments.

Resources