Make a Verilog module sensitive to a switch turning off - syntax

This would make a Verilog module sensitive to a clock and a reset switch being turned on:
always #(posedge clk, posedge rst)
How would this be changed to being sensitive to a switch being turned off?

If you want your block to be sensitive to a switch being turned off, you'll want a negedge in front of the name of the switch input, for example, "switch_line":
always #(posedge clock, posedge reset, negedge swtich_line)
If you just want to have a flipflop check the status of a switch on every positive edge of the clock cycle,
always #(posedge clock, posedge reset)
if (!switch_line)
// ...
else
// ...
Are you trying to model a flip-flop, latch, or perhaps some new type of hardware? Usually, only flipflops and latches are interested in the clock signal. A flip-flop with an asynchronous reset is modeled as
always #(posedge clock, posedge reset)
For a synchronous reset, drop the reset signal from the sensitivity list.
As per the user's comment, another option is to just plug-in the go signal for the reset signal. When you are hooking up this module, you can do the following:
mymodule UUT(
.clock(clock),
.reset(~go),
//...
);
If you negate go, you'll get the same as behavior as reset, just inverted (e.g. a signal going from 1->0).

Unless you are running at a very low clock frequency the change in button state will be much slower that a clock period. Treating the button input as a async signal is therefore not a good idea. Instead you probably want to sample the input and also probably remove glitches.
As minimum sample the input by a register and then have your control FSM look at that register and when the expected change is detected move to the appropriate state. This means that it will take the design 1-2 cycles to "react" to the button change. But, again, unless the clock frequency is very low, the period will be short enough that no human will notice a few cycles latency.
If you connect the signal to the reset you (1) loose all state info by pressing the button (bad) and suddenly have two reset signals. Hot rodding the design like that might work, but is bad design methodology and will make your design sensitive to noise etc.

Related

does after [some delay in second] statement provide delay only in simulation or in actual synthesized model to be loaded in to fpga in VHDL?

We use after [some delay] statement for providing delay and that we can analysis in simulation. But when we will load this model in to FPGA so in actual hardware being made by VHDL code will have affect of delay or this delay is limited to simulation only?
a <= not b after 1s;
So suppose I connected one switch to b and LED to a so will I get one second delay in between pressing the switch and updating LED status?
as said before, the wait statement cannot be synthesized and will only affect the simulation. However, I should add that even in simulation you might not get what you expect. Allow me to explain.
VHDL offers 2 delay models: transport delay and inertial delay, the latter being the default, which you selected by not specifying which model to use.
If b would happen not to be stable in the course of the delay, say it toggles every 500ms, a would not toggle as you may desire. To really introduce pure delay, select the transport delay model as follows:
a <= transport not b after 1s;
Of course, again, this cannot be synthesized and is for simulation purposes only.
When you are simulating you need to provide when things happen and what happens to the inputs. After implementing it on the FPGA, exterior events create the inputs and the simulation has nothing to do about it.
So if I understood your question right, yes, the delay you are showing will only affect the simulation.
EDIT :
Regarding the timer, you know the FPGA's clock frequency. So you can create a variable and increment it on each clk_up (I use CLK = '1' and CLK'Event but there are better ways to do it), and when it reaches the same value as the clock frequency, 1 sec has passed.
Not-so-Pseudo code:
signal clock: unsigned (9 downto 0);
if CLK = '1' and CLK'Event then
clock<= clock + 1;
if clock = "1100100000" then --clock frequency (this is an example)
clock <= "0000000000"
-- 1 secound passed!
end if;
end if;

Edge detection of signal in VHDL

I am new on VHDL, I have a push button which I want to detect the it signal when it is pushed, meaning i want to detect the raising edge of the signal push button when it is pressed?
I did research and all what I found was about the detecting the raising edge of a clk.
the problem that I have is that when the push button is pressed the the signal for the push button goes to 1 and stay at 1 until until another even happen so I am interested more when the signal of the push button raise?
Your question in idiomatic English:
I am new to VHDL and have a push button that I want to detect as a
rising edge when pressed.
I did some research and all what I found was about the detecting the
rising edge of a clock.
When the push button is pressed the signal for the push button goes to
'1' and stay at '1' until until another event occurs.
How do I detect the push button rising edge event?
This isn't so much of a VHDL question as it is a digital design question. VHDL comes into play for implementing a solution in VHDL.
See sonicwave's answer to the question VHDL - Incrementing Register Value on Push Button Event which provides an edge detector.
However switch bounce can occur for tens of milliseconds (Maxim web article on switch bounce), potentially generating multiple events, is switch dependent and corrective action also depends on sampling clock rate.
Notice the Maxim web page article mentions membrane switches can be bounce free when new and degrade over time and bounce characteristics are not repeatable.
Some FPGA vendors provide a Schmidt trigger buffer between buttons and claim membrane momentary switches are then 'debounced'. The Maxim web article claims membrane switches may not remain clean over their useful lifetime. These and other types of momentary switches can require debouncing.
debouncing
When debouncing is not provided by the FPGA board the idea is to filter out all these bounces digitally and generate a single event showing the button has been depressed. This requires a clock.
first get the button signal into your clock domain
This requires metastability filtering, which is accomplished by minimizing the delay between two successive flip flops to maximize immunity to events occurring within the metastability region of the first flip flop when the first flip flop sees a setup or hold time violation.
The input to the first flip flop is the button signal, the input to the second flip flop is the output of first flip flop.
The output of the second flip flop is in the clock domain, metastability free when not exceeding the a clock rate representing period comprised of the routing delay between the two flip flops plus the metastability recovery time of the flip flop.
The metastability recovery time of the flip flop is usually represented by the maximum clock rate period in an FPGA.
filtering out bounces
Feed the metastability filtered button signal to a counter as a reset when the button is invalid. When you release the button the counter is cleared.
The size of the counter depends on the clock rate and length of switch bounce, you can require tens of milliseconds.
A terminal count signifies a valid button event and also is used to stop the counter. (Terminal count FALSE is an enable for the counter).
The counter is stopped to provide a single button event.
Also note that when the button input is metastability filtered it acts as a synchronous reset.
Edge detection
Edge detection is done with a flip flop with the terminal count signal as an input and a two input gate, the type of gate and polarity of it's inputs can be used to select which edge of the event (potentially both with an XOR gate) you detect. One input to the gate from the flip flop, the other the terminal count from the counter.
If you've deemed debounce is provided adequately by the FPGA board design you can combine metastability filtering and edge detection without using a debounce counter.
Maxim's application note
If you have a commercially produced FPGA board you shouldn't have to worry about voltage transients outside digital signalling levels, the Maxim article is promoting their protective devices to board designers.
The web article provides an authoritative reference on switch bounce and the bounce waveforms.
FPGA board vendors
Some FPGA board vendors provide debounce circuit reference design code. They'll do this because the counter size is dependent on the reference clock rate, and potentially the clock used is derived by a DPLL.
Depended on if you want safety check for meta-stability or not make a shift register and shift your input signal on a clock and look when there is a difference. The code below is very simple and takes into account that you have a clock in your system.
signal edge_detect : std_logic_vector( 1 downto 0 );
process (clk_i) is
begin
if rising_edge(clk_i) then
edge_detect <= edge_detect(0) & input_signal;
if edge_detect = "01" then
-- do stuff on rising_edge
elsif edge_detect = "10" then
-- do stuff on falling_edge
end if;
end process;
But depended on rising/ falling time of your signal vs. your clock you might want to look into meta-stability also if you get problems with false positives.

VHDL: Mealy machine and button press detection

Hi I'm a bit confused about the implementation of Mealy state machine using VHDL. My current work is like this:
process(clk, rst)
begin
if rst = '1' then
state <= s1;
elsif (clk'event and clk = '1') then
state <= next_state;
end if;
end process;
and another process like this:
process(state, op)
begin
case state is
when s1 =>
...some implementation
end process;
And now the problem is: I need to detect the press of the button from the user, but I'm not sure where to put it. Should it be inside the first process or the second process? Besides, I also looked through the following guide: implement state machine in FPGA, is it okay to use just one process for the Mealy machine as shown on the webpage? If it is so then I think the work will be easier. Thanks!
You should put it in the second process. The first process is only used to change states and the next_state is also calculated in the second.
There are several ways to write FSMs and people tend to favour one or the other for various reasons. Pick the one that works for you.
You cannot design a Mealy state machine with only one process. Even Moore state machines, in most cases, cannot be modelled with only one process.
A state machine always has a state register which must be modelled with a synchronous process. That is, a process which sensitivity list contains only the clock (and set or reset signals if they are asynchronous).
Every output of a synchronous process will synthesize as the output of a register because its value changes only on an edge of the clock (plus states of asynchronous set or reset if any). So, you cannot describe the outputs of a Mealy state machine in the same synchronous process as the state register. If you were doing so, it would not be a Mealy machine any more because its outputs would not combinationally depend on the inputs.
For Moore machines, things are a bit more subtle but, except in very exceptional cases, you also need at least two processes. When I write "process", I include processes short-hands like concurrent signal assignments, concurrent procedure calls or component/entity instantiations.
To make it simple: VHDL modelling for synthesis is straightforward if you have a clear view of the hardware you want.
Draw a block diagram of your hardware with registers and combinatorial parts clearly identified.
Draw bubbles enclosing hardware elements, one bubble per process, respecting the rule that if a bubble contains a register, all its outputs must be register outputs.
The synchronous processes are those enclosing registers. Their code is exactly:
process(clk)
begin
if rising_edge(clk) then
<your code>
end if;
end process;
Put your code in <your code>, never put code elsewhere. If you have asynchronous set or reset the code must be something like:
process(clk, reset)
begin
if reset = '1' then
<initialize outputs>
elsif rising_edge(clk) then
<your code>
end if;
end process;
The other processes are combinatorial processes. List all their entering signals (INPUTS) and output signals (OUTPUTS). The code must be:
process(INPUTS)
begin
<your code>
end process;
with the constraint that each OUTPUT signal must be assigned a value in every execution of the process. The best way to guarantee this is to start the process with a default assignment of all OUTPUTS.
That's all. Draw and code what you see. Bonus: every arrow crossing the border of one of your process-bubbles is a signal that you will have to declare unless it is already a primary input or output of your design.
Exercise: draw the block diagram of a Mealy state machine and understand why it cannot be modelled with one single process. Understand also why it can always be modelled with two processes, even if it is not necessarily desirable. Finally, try to identify the rare cases where a Moore state machine can be modelled with one process only.

Do all Flip Flops in a design need to be resettable (ASIC)?

I'm trying to understand clock-reset in a chip. In a design what criteria are used to decide whether a flop should be assigned to a value (typically to zero) during reset?
always_ff #(posedge clk or negedge reset) begin : process_w_reset
if(~reset) begin
flop1 <= '0;
....
end else begin
if (condition) begin
flop1 <= something ;
....
end
end
end
always_ff #(posedge clk) begin : process_wo_reset
if (condition) begin
flop1 <= something ;
....
end
end
Is it a bad practice to not to reset a flop which is used later as a control signal in a comb logic? What if the design makes sure that the flop will have a valid value (0 or 1) assigned to it before its used in a comb logic block (i.e. in a if statement or in FSM comb logic) ?
I feel like it's better to always reset all the flops in the design. In that way there won't be any Xs after reset in the chip. However, it seems like for datapath logic, resetting flop might need not be a big deal as it'll be just pipe stages. However if a flop is in control path (i.e. FSM next state comb logic) then it should be reset to a default value. Is my understanding correct? I don't know much about DFT and not sure if it has any other implication.
Assuming that reset means asynchronous reset, as in the code examples.
The answer is partly opinion based, since a design can be made to work with reset of a minimum number of the Flip-Flops (FFs) and all of the FFs.
I suggest that a minimum number of FFs are reset, and typically that leads to reset of most FFs in the control path, and no reset of FFs in the data path. The advantages of this approach are outlined below.
Simulation is often conservative with respect to propagation of uninitialized values, both for Verilog and VHDL, so it is like simulation can check both 0 and 1 values at once when the value is uninitialized.
Bugs due to FFs that are not reset, are therefore likely to show earlier in verification with simulation, and the designer thereby gets valuable feedback about wrong design assumptions, which may lead to corrections in the design that fixes other bugs. Just resetting all the FFs is likely to hide such bugs.
It may seem like design and verification is just easier if all FFs are reset, both in control and data path, since it fixes all those "annoying" X propagation in the design. But it requires an increased number of tests in order to verify all value combinations when X propagation is suppressed through reset.
Implementation gives a smaller load on the reset signal, so it is easier to meet timing of the reset net throughout the chip.
DFT (Design For Test) in general, then adding reset to the FFs will not aid DFT in finding nets stuck at reset value. With a DFT scan chain approach where all the FFs are loaded through the scan chain, then the lack of reset on some FFs will not require more vectors.
Generally you need to think about where the 'X's will propagate in your simulation and which ones matter and which ones are don't care conditions. For example, if you have a block of logic which doesn't start operating until an enable bit is set, so long as the enable bit itself is set and enough upstream logic is reset so reset values will propagate through to the enabled logic in time, you are most likely OK with not reseting the logic in between. However, you do want to reset any logic that feeds back into itself, (for example state machines) otherwise the upstream resets will never be able to establish a known state in the feedback block.
I agree with Morten Zilmer that you should only reset flops that require resetting, although my background is more FPGA than ASIC.
It's worth pointing out there is a gotcha in Verilog / SystemVerilog - if you have a clocked process that drives registers that are reset and registers that aren't you will end up inferring a clock enable or an additional mux on the input of your flip-flop.
This is usually not what was intended.
There is a more detailed explanation in this answer. I also wrote a blog post outlining a mechanism for abstracting away synchronous/asynchronous and active high/low reset.
As a general rule of thumb, you should probably always reset control signals.
For data flops, resetting can cost you area, so it really depends on whether you care about area.
In recent years simulators started to support X propagation modes that allow you to catch some of the X issues in RTL (instead of gate level simulation). It is a good practice to run these to make sure you don't have a reset problem with uninitialized sram or flops.

Latch signal without delay

I would like to latch a signal, however when I try to do so, I get a delay of one cycle, how can I avoid this?
myLatch: process(wclk, we) -- Can I ommit the we in the sensitivity list?
begin
if wclk'event and wclk = '1' then
lwe <= we;
end if;
end process;
However if I try this and look into the waves during simulation lwe is delayed by one cycle of wclk. All I want tp achieve is to sample we on the rising edge of wclk and keep it stable till the next rising edge. I then assign the latched signal to another entities port map which is defined in the architecture.
==============================================
Well I figured out that I have to omit the wclk'event to get a latch instead of a flip flop. This seems rather unintuitive to me. By simply shortening the time where I sample the signal to be latched I go from latch to flip flop. Can anyone explain why this is and where my perception is wrong. (I am a vhdl beginner)
First off, a few observations on the process you pasted above:
myLatch: process(wclk, we)
begin
if wclk'event and wclk = '1' then
lwe <= we;
end if;
end process;
The signal we can be omitted from the sensitivity list because you have described a clocked process. The only signals required in the sensitivity list of a process like this are the clock and the asynchronous reset if you choose to use one (a synchronous reset would not need to be added to the sensitivity list).
Instead of using if wclk'event and wclk = '1' then you should instead use if rising_edge(wclk) then or if falling_edge(wclk) then, there's a good blog post on the reasons why here.
By omitting the wclk'event you changed the process from a clocked process to a combinatorial process, like so:
myLatch: process(wclk, we)
begin
if wclk = '1' then
lwe <= we;
end if;
end process;
In a combinatorial process all inputs should be present in the sensitivity list, so you would be correct to have both wclk and we in the list as they had an influence on the output. Normally you would ensure that lwe is assigned in all cases of your if statement to avoid inferring a latch, however this appears to be your intention in this case.
Latches in general should be avoided, so if you find yourself needing one you should perhaps pause and consider your approach. Doulos have a couple of articles on latches here and here that you might find useful.
You stated that all you want to achieve is to sample we on the rising edge of wclk and keep it stable until the next rising edge. The process below will accomplish this:
store : process(wclk)
begin
if rising_edge(wclk) then
lwe <= we;
end if;
end process;
With this process, lwe will be updated with the value of we upon every rising edge of wclk and it will remain valid for a single clock cycle.
Let me know if this clears things up for you.
Believe it or not, the issue is actually in your testbench. This has to do with how the VHDL simulation model works.
VHDL is usually used for synchronous hardware design -- that means, using flip-flops that sample on the rising edge and set outputs on the falling edge, so that there are no race conditions between reading and writing. But in VHDL this master/slave logic is not actually simulated using opposite clock edges.
Consider a process
process (clock) begin
if rising_edge(clock) then
a <= b;
end if;
end process;
At the start of a simulation timestep, if clock has just risen, the if will execute. Then the assignment a <= b will be executed, and this will not immediately cause an assignment to take place, but schedule the assignment for the end of the timestep.
After all processes have been run, then all scheduled assignments take place. This means that no process will "see" the new value of a until the next timestep.
Time a b Actions
Start of ts 1 '0' '1' a <= '1' is scheduled
End of ts 1 '1' '0' a <= '1' is executed
Start of ts 2 '1' '0' a <= '0' is scheduled
End of ts 2 '0' '1' a <= '0' is executed
So when you look on the waveform viewer, what you will see is a apparently being set on the rising edge of the clock, and following b delayed by one clock cycle; you don't see the intermediate scheduling of assignments that causes this to happen.
Of course, in real life, there is no "end of the timestep", and the actual changing of signal a happens when the slave part of the flip-flop triggers, ie, on the negative edge. (Maybe it would have been less confusing for VHDL to just use the negative edge; but, oh well, this is how it works).
Here are two testbenches for your latch code:
Test bench 1, using rising edges
Test bench 2, using falling edges
In the first, if you look in the waveform viewer you will see exactly what you describe -- lwe appears to be delayed by 1 clock cycle -- but really, the delay is happening in the non-blocking assignment that sets counter -- so when the rising edge happens, we does not actually have its new value yet. And in the second, you see no such delay; lwe is set exactly on the rising edge to the value of we at that time.
For a related topic in Verilog, see Nonblocking Assignments in Verilog Synthesis, Coding Styles That Kill .
The process you have is what you want according to your description, although 'we' should be removed from the sensitivity list. If this doesn't work as you believe it should it is almost certainly a problem with your test bench/simulation. (See Owen's answer.) Specifically you are probably changing the value of 'we' too late, so that the flip-flop latches the previous value instead of the new one.
I'm interested to know what the source of this signal is though, if it's an asynchronous signal that can change at any time you will have to add some logic to protect against metastability.
To answer your second question about latches, it is correct that omitting wclk'event will result in a latch. This process will not do what you want, however, because it will propagate changes to 'we' to 'lwe' during the whole positive half-period of the clock. The short answer to your question is that implementing this type of behavior requires a latch, while the behavior described by the original process requires a flip-flop.

Resources