Memorising a value from a push button - verilog

I am trying to do this in Verilog:
when a button gets pressed (goes into state 1), I need a variable to be set to 1, and remain like that till I change it.
My code is:
always#(button)
begin
if(button==1) begin
var1=1;
end
end
But what I seem to get is that the var is set to 1 the whole program.
How do I achieve my goal in a different way???

One of the reasons that you are getting always 1 might be, if the button is on the board, and you assigned that as an input, then they generally give output HIGH when not pressed and LOW when pressed. If that is the case use if(button == 0) as the condition.
As you mentioned in commands you were using another always block to change the value of the variable, however you should not be able to change the same variable from two different always blocks. Hopefully we can find solutions that can solve your problem.
If your design is synchronous and clocked (generally it is the case in practical hardware designs), you can have something like this (it is practical if your clock has frequency that is larger than 10Hz):
module memorize_pb(
input clk,
// you can have some other inputs here for the remaining part of your code
input button
);
reg stored_variable;
// other registers if used
always#(posedge clk)
begin
if(button == 1) begin //if the first reason is not the case
stored_variable <= 1'b1;
end
// other parts of your code and conditions which resets your variable
end //end of always block
endmodule
Note: For this code to work, you have to press the pushbutton for longer time than clock period which is practically the case.
if the design is asynchronous, just include the button in your sensitivity list and write the code in the same always block.

Related

Verilog always block with pushbutton activation, FSM

I'm writing some Verilog code to be programmed on an Altera Cyclone II FPGA board, and I have an always block which should be activated on the press of a key switch:
reg START;
...
...
always # (negedge key[3]) begin
if (START != 1) START = 1;
end
I'm writing a program for a finite state machine and this key press is supposed to indicate that the user would like to begin using the program and it should move from its initial state to the next state. Since the initialization of registers is not synthesizable, I can't assume that START begins at 0.
The problem is that once I program the board and turn it on, this always block has already run once before I press the key assigned to key[3]. I've done checks for the value of START at program execution and it is already at 1. I can't figure out why this would be happening, as the key is at its negative edge only upon key press. I've used always blocks with the same condition in previous situations and it worked fine, so I assume this has something to do with the initialization of START?
It should be noted that synthesizability of initial depends on a target you are coding for.
For example, if you code for simulator, initial works just nice. If your target is FPGA, the tool (quartus in your case) has full control over the schematics and over the initial state of every trigger inside it: actually, uploading the firmware to FPGA sets every trigger to a known state, and quartus is able to parse initials to derive each trigger's state.
In contrary, if your target is a bare silicon, every trigger is just a bunch of transistors and its state is totally indefinite upon power-on, so the only way to control it's power-on state is to apply some type of reset, like this:
always #(posedge clk, negedge rst_n)
if( !rst_n )
START <= 1'b0; // no start condition upon reset
else if( some_condition )
START <= 1'b1;
Another point on your code is that when parsing inputs from switches you should do first resynchronization to your design's clock, like this:
reg start_r, start_rr;
always #(posedge clk)
begin
start_r <= START;
start_rr <= start_r;
end
// now use start_rr instead of START
Resynchronization is a key element to avoid metastable states in your synchronous design.
The second point is that you should consider debouncing of any input from mechanic switches, unless your design is tolerant to multiple tripping of switches.
Returning to the original problem Ryan McClure asks for. It could be seen, that in the original code without initial START is undefined at startup, and can trip only to '1' state. Therefore, synthesizer just assumes START is constant, always having it '1'.
You should use an "initial" block to set the startup value of your signals. The value of START and key[3] has to be set.
initial begin
START = 1'b0;
key[3] = 1'b1;
end
You said
Since the initialization of registers is not synthesizable, I can't
assume that START begins at 0.
But this is not true! You can set a default value to any signal in your design with the method above. This value is included in the bitstream of your firmware and the signal startup with this very value.
cheers

Verilog state machine based on switch inputs and button presses

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.

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 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

How can I create a latch in Verilog

I have a CPLD with a digital input representing a reset button. When the reset button is pressed, the signal goes high. What I need to do is have a register whose value tells if the button has ever been pressed. Basically a latch. When the button goes high, a latch register goes high and stays high forever.
I thought this would be straightforward, but I got a bunch of warnings when I tried to code it up. A little Googling showed "Don't make latches in HDL! Bad practice!", but I don't really see the alternative here.
Here's my attempt. clk_10m is a fast free-running clock, pwr_off_req is the button input.
reg pwr_off_req_latched = 0;
always # (clk_10m or pwr_off_req) begin
if (pwr_off_req == 1'b1)
pwr_off_req_latched <= 1'b1;
else
pwr_off_req_latched <= pwr_off_req_latched;
// I tried this to make sure it's always set to something
end
Can you assume that the pulse length of the button press is much longer than the clock frequency of your device? If it's a physical button I think that is a very safe assumption. In that case I think this would work perfectly fine:
always #(clk_10m)
pwr_off_req_latched <= power_off_req_latched | power_off_req;
Latches are not bad in HDL they just require some consideration, implied latches from forgetting to specify else clauses in combinatorial sections are bad because you do not end up with the hardware you expect, and can create timing problems.
If you are applying a reset you might need to specify a 'pragma' so that the synthesis tool correctly identifies it.
Also latches should use = not <=, when they are enabled they are combinatorial (open) and will not break feedback loops.
This is typical way to create a latch with an asynchronous reset:
//synopsys async_set_reset "rst_an"
always #* begin
if (~rst_an) begin
// Reset
x = 1'b0;
end
else if (latch_open) begin
//next datavalue
x = y ;
end
end
In your case you might want something like :
//synopsys async_set_reset "rst_an"
always #* begin
if (~rst_an) begin
pwr_off_req_latched = 1'b0;
end
else if ( pwr_off_req ) begin
pwr_off_req_latched = 1'b1 ;
end
end
Latches can create problems for timing analysis tools. They also don't map to certain (FPGA) architectures directly, so are much harder for the place-and-route tools. Hence the warnings.
However, what you are asking for is not a latch as I understand the digital logic sense - merely a flipflop which doesn't ever get reset.
So, it can be simplified to a simple d-type flipflop with the D input tied to 1 and the clk input connected to your pwr_off_req signal:
reg pwr_off_req_latched = 0;
always # (posedge pwr_off_req) begin
pwr_off_req_latched <= 1'b1;
end
You'll have no noise rejection on that at all - any positive going edge will latch the flipflop to 1.
If I were doing this, I would run the input into a double-flip-flop synchroniser and then count a few clock pulses of the synchronised signal to make sure it's not noise before setting the latched signal. Unless you are expecting real events shorter than a few clock pulses that'd the way to do it.
Aside:
A "latch" in the digital logic world usually means either
a circuit whose output holds whichever of the two inputs was last high (a Set/Reset or SR latch)
a circuit whose output holds the input value while a control signal is inactive, but follows the input when the control signal is low - a transparent latch
This is in comparison to a flipflop, whose output holds some aspect related to the input(s) when the control signal changes (usually) from low to high, and ignores the inputs except for a tiny time window around that rising edge. These are D-type, T-type and JK-type flipflops, depending on how the output behaves relative to the input.

Resources