How to implement hardware that remembers previous value in digital logic design? - digital-logic

I am trying to design the following:
The datapath of an octal calculator which has a 24-bit input register in
reg and a 24-bit accumulator acc.
The contents
of both registers are displayed as eight octal (radix-8) digits. Both are cleared on reset.
The calculator has
buttons for C (clear), the numbers 0-7, and the functions +, -, and x. Pressing C once clears in
reg.
Pressing C a
second time with no other intervening keys clears acc. Pressing a number shifts in
reg to the left three bits and
puts the number pressed into the low three bits.
Pressing a function performs that function on the two registers
and puts the result in acc. Draw a block diagram from the datapath of this calculator
What I have so far is:
reg_in and acc flip flops, with the same clock and reset
an ALU(performing function operations) taking in input from in_reg and acc and outputting back into in_reg, driven by an ALUselect signal
a shift register to shift the input bits by 3 and put them back into the reg_in
However, the part that I am stuck on is how to implement the "pressing C" part. What design choice can I make which will allow me to clear reg_in if C is pressed once and clear acc if C is pressed again? I want to a find a simpler method than using a counter.
Any help is appreciated!

Additional one-bit register should solve the problem. Let's call it last_button.
Set last_button to 1 if C is pressed and last_button is previously 0.
Set last_button to 0 if another button is pressed.
If last_button is 0 when C is pressed, clear reg_in.
If last_button is 1 when C is pressed, clear acc.
In case acc is cleared, clear last_button to 0 as well.
You can assume this logic is a Mealy machine with 2 states, then last_button is the state signal. C button always toggles the state, other buttons set the state to zero. The outputs (clear reg_in/acc) of the machine depend on both the inputs (buttons) and the current state.

Related

Ensuring propagation is complete in VHDL without an explicit click

I am looking to build a VHDL circuit which responds to an input as fast as possible, meaning I don't have an explicit clock to clock signals in and out if I don't absolutely need one. However, I am also looking to avoid "bouncing" where one leg of a combinatorial block of logic finishes before another.
As an example, the expression B <= A xor not not A should clearly never assign true to B. However, in a real implementation, the two not gates introduce delays which permit the output of that expression to flicker after A changes but the not gates have not propagated that change. I'd like to "debounce" that circuit.
The usual, and obvious, solution is to clock the circuit, so that one never observes a transient value. However, for this circuit, I am looking to avoid a dependence on a clock signal, and only have a network of gates.
I'd like to have something like:
x <= not A -- line 1
y <= not x -- line 2
z <= A xor y -- line 3
B <= z -- line 4
such that I guarantee that line 4 occurs after line 3.
The tricky part is that I am not doing this in one block, as the exposition above might suggest. The true behavior of the circuit is defined by two or more separate components which are using signals to communicate. Thus once the signal chain propagates into my sub-circuit, I see nothing until the output changes, or doesn't change!
In effect, the final product I'm looking for is a procedure which can be "armed" by the inputs changing, and "triggered" by the sub-circuit announcing its outputs are fully changed. I'd like the result to be snynthesizable so that it responds to the implementation technology. If it's on a FPGA, it always has access to a clock, so it can use that to manage the debouncing logic. If it's being implemented as an ASIC, the signals would have to be delayed such that any procedure which sees the "triggered" signal is 100% confident that it is seeing updated ouputs from that circuit.
I see very few synthesizable approaches to such a procedural "A happens-before B" behavior. wait seems to be the "right" tool for the job, but is typically only synthesizable for use with explicit clock signals.

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.

Interview Q: Detecting a fighting game moveset

I got this as an interview question and I'm wondering what the optimal way of designing this system would be. The problem:
Say you have a fighting game where certain button combinations represent a special move. Implement 2 functions register_move([button combo],movename) which takes in a list of button inputs and a movename string and on_keypress(button) which registers the current keypress and prints a movename if a button combo has been activated. The buttons are represented as characters: 'U','D','L','R','A','B'
Example:
register_move(['A','B','U'],"Uppercut")
on_keypress('A')
on_keypress('B')
on_keypress('U') -> print "Uppercut"
you can assume moves are registered before on_keypress so you don't have to retroactively look back at the previous keypresses. You can use any language you like
Build a Deterministic Finite State Automaton. The initial state is "no keys recognised". On each keypress, transition into a new state; if it is a final state you have a move. All undefined transitions transition into the starting state. For your example,
S --(a)--> A
A --(b)--> AB
AB --(u) --> ABU: process "Uppercut", move to S
X --(x)--> S
where X is any state, x is any input not otherwise covered by the rules.
More practically and less theoretically, you will end up with a trie, so using a trie library should be sufficient. Root is "no input", walk it until a leaf, or restart on a mispress.
Considering the limited number of moves, you don't need a super efficient finite state machine to handle this.
You could simply store the strings in register_move, and have on_keypress memorize the last potentially valid sequence.
If the current key sequence is the prefix of at least one move (for instance "AB" being a prefix of "ABU"), you're done (just wait for the next keypress to see if a combo is reached).
If the sequence is no prefix, reset the sequence to the last keypress (for instance "ABD" -> "D"). This clears previous keypresses that correspond to no moves.
If the sequence corresponds to a move, perform the move (well, print it at least) and reset the sequence.
This would require to do a prefix search on every possible move combo, which is very quick if you have only a dozen or so. If for some reason you want to be quicker, you can indeed turn your list of combos into a prefix tree, but it would require a lot more code for little gain.

How to make the 2-complement of a number without using adder

In two-complement to invert the sign of a number you usually just negate every bit and add 1.
For example:
011 (3)
100 + 1 = 101 (-3)
In VHDL is:
a <= std_logic_vector(unsigned(not(a)) + 1);
In this way the synthesizer uses an N-bit adder.
Is there another more efficient solution without using the adder?
I would guess there's not an easier way to do it, but the adder is probably not as bad as you think it is.
If you are trying to say invert a 32-bit number, the synthesis tool might start with a 32-bit adder structure. However then upon seeing that the B input is always tied to 1, it can 'hollow out' a lot of the structure due to the unused gates (AND gates with one pin tied to ground, OR gates with one pin tied to logic 1, etc).
So what you're left with I'd imagine would be a reasonably efficient blob of logic which just increments an input number.
If you are just trying to create a two's complement bit pattern then a unary - also works.
a = 3'b001 ; // 1
b = -a ; //3'b111 -1
c = ~a + 1 ; //3'b111 -1
Tim has also correctly pointed out that just because you use a + or imply one through a unary -, the synthesis tools are free to optimise this.
A full adder has 3 inputs (A, B, Carry_in) and 2 outputs (Sum Carry_out). Since for our use the second input is only 1 bit wide, and at the LSB there is no carry, we do not need a 'full adder'.
A half adder which has 2 inputs (A, B) and 2 outputs (Sum Carry), is perfect here.
For the LSB the half adders B input will be high, the +1. The rest of the bits B inputs will be used to propagate the Carry from the previous bit.
There is no way that I am aware of to write in verilog that you want a half adder, but any size number plus 1 bit only requires a half adder rather than a fulladder.

Cycling LED Modes using ControllerMate

I'm using ControllerMate with a Nostromo (Belkin) n52 (NOT the te version) Speedpad on an iMac running Snow Leopard.
The official SpeedPad configuration software doesn't run beyond Tiger, or at least, it doesn't run on Snow Leopard due to the kext failing to load properly, hence the attempt at using ControllerMate.
The official SpeedPad configuration software has the capability to load 1 unique set of keys per "page", where there are 4 pages. This ultimately led me to be able to do things like basic key mapping on the first page, key combinations on the second, macro'ing on the third, and I set up some global shortcuts for my music player, and bound those same shortcuts on the last page of the Speedpad.
Pages were represented by the currently lit LED on the unit;
No LEDs On / Red LED On / Green LED On / Blue LED On
I'm attempting to use the Logic functions of ControllerMate in order to recreate this same behavior. Clicking a button bound to this routine will cause the LEDs to start cycling in the order listed above, ultimately circling around and restarting at no LEDs on.
I'm going to explain this as best I can so that the basic principles of programming/logic here could feasibly be answered by any individual here, but I might fail, and you might need to familiarize yourself with ControllerMate first :P.
ControllerMate presents you with a grid, where you simply drag objects in. It's a visual programming canvas. For example, my Canvas has 4 blocks on it currently;
Nostromo SpeedPad 2
Keypad LeftAlt
This is the key that corresponds to the large Orange button above the DPad. It's on the Canvas so I can dump other elements into it, and get elements out of it.
It's a basic Input/Output system with snapping elements.
Num Lock
Caps Lock
Scroll Lock
These represent the LEDs. When these blocks turn "on", the related LED on the SpeedPad lights up.
For example, if I connect one Lock block, or all of them, directly to the LeftAlt block, pressing the "LeftAlt" button on the SpeedPad turns on one/all of the LED light(s) for the duration that it's held.
ControllerMate actually has a wonderful guide of explaining the "Blocks" and showing what they look like at http://www.orderedbytes.com/controllermate/help/?show=blocks
The Logic blocks I have to work with are as follows:
AND
NOT
OR
XOR
ON/OFF Gate
ON/OFF Latch
1:2 Selector
Toggle
Most of these are self explanatory already, but just in case they aren't, please consult the above link to get the specific Block Reference (My Rep. currently prevents me from linking each of the above elements).
I'm thinking that I'm going to have success with using a series of Toggles and Gates, but I haven't quite been able to interconnect them properly to consistently behave in a perfect loop of invocation.
Bonus Points if you're really feeling up to it (you'll get an accepted answer for satisfying only the primary question, promise!):
Not only a linear On/Off per LED, but a complete permutation of all On/Off combinations;
All Off
Red On Blue Off Green Off
Red On Blue On Green Off
Red On Blue Off Green On
Red On Blue On Green On
Red Off Blue On Green Off
etc.
[edit]
If anyone with suitable rep could create/add the "ControllerMate" tag to this question I'd sure appreciate it.
I figured it all out, it was quite a long time coming. Let's break it into a few different topics;
(1) Keybinding / Key Representation
(2) Blocks Used
(3) Logic
First, I set up a simple key remap, but that example failed because pressing the Speedpad 02 key, would input it's original mapping (q) and the re-map I defined (w). I started crawling over the ControllerMate Forums, and I stumbled on a
great couple of posts, which would make better starting points than the .cmate definition files that are easy to find, but I digress…
After ripping my hair out looking for a setting I had missed, program preferences, or what have you, I looked on the forums and came across a great thread. After reading it, I took the 30 second and disabled all the buttons for the "keyboard" palette portion and the "mouse" palette portion that didn't actually exist.
This means disabling all but the 15 numbered keys, plus the orange key, plus the dpad for the keyboard portion, and disabling all the mouse keys for the mouse portion. I'm going to send this new map file to Ken (the ControllerMate developer).
After doing this, and naming the keys something sane so they're properly represented as the key they're labeled, the remaps work as expected. Speedpad 02 only enter my remaped key of w, and nothing else!
This first step finally was finished.
Second and third, I sat down and figured out a creative solution to the LED task;
I'm using exactly zero of the logic blocks above. I use meta blocks (Key blocks, group blocks) and math.
When pressing the Orange thumb button, a "accumulator" block runs, from 0 to 3, stepping by 1 each push.
That accumulator has 3 outlets, each going to a subtraction block. The first subtraction block subtracts 1, the second subtracts 2, the third subtracts 3.
All of those subtractor blocks connect directly to a "Value Selector". If the value is zero, that particular selector turns on.
Thus, when I've pushed the orange button once, the accumulator provides a value of 1, which goes to all of the subtractors, but more specifically the one controlling the Red LED subtracts 1, and totals 0, so it's Value Selector enables, which enables the "Num Lock" (Red
LED) light.
The LED Outlets connect to a constant number value block (again, the -1 subtraction stack connection ultimately provides a constant value of 1, the -2 subtraction stack ends up at a constant value of 2, -3 goes to 3.
All three of these constant value blocks goes to a series of 4 Addition blocks, Red LED/Constant 1 has four outputs, to all four Addition blocks. Blue LED/Constant 2 has four outputs that go to all four Addition blocks, and Green LED/Constant 3 [...].
Then, a configuration page can be placed on the canvas, in which case I moved the "remap" page onto the canvas, and attached it to an addition->expect 0 value selector block, meaning that if the addition equals zero, that particular value selector is on. When all LEDs are
off, the top half constant value blocks are disabled, and don't provide their particular value.
Now, I just need to figure out what to bind to the other three modes I was so desperately working on.
Picture of the ControllerMate Canvas;
http://vxjasonxv.com/images/ControllerMateSC2.png

Resources