Create a 2-1 multiplexer. When sel=0, choose a. When sel=1, choose b.


Consider the state machine shown below:

// A (0) --0--> B
// A (0) --1--> A
// B (0) --0--> C
// B (0) --1--> D
// C (0) --0--> E
// C (0) --1--> D
// D (0) --0--> F
// D (0) --1--> A
// E (1) --0--> E
// E (1) --1--> D
// F (1) --0--> C
// F (1) --1--> D

// Assume that you want to Implement the FSM using three flip-flops and state codes y[3:1] = 000, 001, ..., 101 for states A, B, ..., F, respectively. Implement just the next-state logic for y[2] in Verilog. The output Y2 is y[2].


Suppose you are designing a circuit to control a cellphone's ringer and vibration motor. Whenever the phone needs to ring from an incoming call (input ring), your circuit must either turn on the ringer (output ringer = 1) or the motor (output motor = 1), but not both. If the phone is in vibrate mode (input vibrate_mode = 1), turn on the motor. Otherwise, turn on the ringer.


Build an AND gate using both an assign statement and a combinational always block.


Build a circuit that always outputs a LOW.


This is a sequential circuit. Read the simulation waveforms to determine what the circuit does, then implement it.

// time            clk             a               q
// 0ns             0               x               x
// 5ns             1               0               x
// 10ns            0               0               x
// 15ns            1               0               1
// 20ns            0               0               1
// 25ns            1               0               1
// 30ns            0               0               1
// 35ns            1               1               1
// 40ns            0               1               1
// 45ns            1               1               0
// 50ns            0               1               0
// 55ns            1               1               0
// 60ns            0               1               0
// 65ns            1               1               0
// 70ns            0               1               0
// 75ns            1               1               0
// 80ns            0               1               0
// 85ns            1               1               0
// 90ns            0               1               0


You are to design a one-input one-output serial 2's complementer Moore state machine. The input (x) is a series of bits (one per clock cycle) beginning with the least-significant bit of the number, and the output (Z) is the 2's complement of the input. The machine will accept input numbers of arbitrary length. The circuit requires a positive edge triggered asynchronous reset. The conversion begins when Reset is released and stops when Reset is asserted.


The following is the state transition table for a Moore state machine with one input, one output, and four states. Implement this state machine. Include a positive edge triggered asynchronous reset that resets the FSM to state A.

// state | next state in=0, next state in=1 | output
// A | A, B | 0
// B | C, B | 0
// C | A, D | 0
// D | C, B | 1


Build a circuit that reverses the byte order of a 32-bit vector.


Implement a simple D flip flop with active high synchronous reset (reset output to 0).


Implement the boolean function z = (x^y) & x.


Build a 64-bit arithmetic shift register, with synchronous load. The shifter can shift both left and right, and by 1 or 8 bit positions, selected by "amount." Assume the right shit is an arithmetic right shift.

// Signals are defined as below:
// (1) load: Loads shift register with data[63:0] instead of shifting. Active high.
// (2) ena: Chooses whether to shift. Active high.
// (3) amount: Chooses which direction and how much to shift.
//     (a) 2'b00: shift left by 1 bit.
//     (b) 2'b01: shift left by 8 bits.
//     (c) 2'b10: shift right by 1 bit.
//     (d) 2'b11: shift right by 8 bits.
// (4) q: The contents of the shifter.


Implement a Mealy-type finite state machine that recognizes the sequence "101" on an input signal named x. Your FSM should have an output signal, z, that is asserted to logic-1 when the "101" sequence is detected. Your FSM should also have a negative edge triggered asynchronous reset. You may only have 3 states in your state machine. Your FSM should recognize overlapping sequences.


We want a finite state machine that will search for message boundaries when given an input byte stream. The algorithm we'll use is to discard bytes until we see one with in[3]=1. We then assume that this is byte 1 of a message, and signal the receipt of a message once all 3 bytes have been received (done). The FSM should signal done in the cycle immediately after the third byte of each message was successfully received.

// Implement the datapath module that will output the 24-bit (3 byte) message whenever a packet is received (out_bytes[23:16] is the first byte, out_bytes[15:8] is the second byte, etc.). The reset signal is active high synchronous. out_bytes needs to be valid whenever the done signal is asserted. You may output anything at other times (i.e., don't-care).

// Waveform example:
// time            clk             reset           in[7:0]         done            out_bytes
// 0ns             0               1                0              x                    x
// 5ns             1               1                0              0                    x
// 10ns            0               1                0              0                    x
// 15ns            1               0               2c              0                    x
// 20ns            0               0               2c              0                    x
// 25ns            1               0               81              0                    x
// 30ns            0               0               81              0                    x
// 35ns            1               0                9              0                    x
// 40ns            0               0                9              0                    x
// 45ns            1               0               6b              1               2c8109
// 50ns            0               0               6b              1               2c8109
// 55ns            1               0                d              0                    x
// 60ns            0               0                d              0                    x
// 65ns            1               0               8d              0                    x
// 70ns            0               0               8d              0                    x
// 75ns            1               0               6d              1               6b0d8d
// 80ns            0               0               6d              1               6b0d8d
// 85ns            1               0               12              0                    x
// 90ns            0               0               12              0                    x
// 95ns            1               0                1              0                    x
// 100ns           0               0                1              0                    x
// 105ns           1               0                d              1               6d1201
// 110ns           0               0                d              1               6d1201
// 115ns           1               0               76              0                    x
// 120ns           0               0               76              0                    x
// 125ns           1               0               3d              0                    x
// 130ns           0               0               3d              0                    x
// 135ns           1               0               ed              1                d763d
// 140ns           0               0               ed              1                d763d
// 145ns           1               0               8c              0                    x
// 150ns           0               0               8c              0                    x
// 155ns           1               0               f9              0                    x
// 160ns           0               0               f9              0                    x
// 165ns           1               0               ce              1               ed8cf9
// 170ns           0               0               ce              1               ed8cf9
// 175ns           1               0               c5              0                    x
// 180ns           0               0               c5              0                    x
// 185ns           1               0               aa              0                    x
// 190ns           0               0               aa              0                    x


// Consider the state machine shown below:

// A (0) --1--> B
// A (0) --0--> A
// B (0) --1--> C
// B (0) --0--> D
// C (0) --1--> E
// C (0) --0--> D
// D (0) --1--> F
// D (0) --0--> A
// E (1) --1--> E
// E (1) --0--> D
// F (1) --1--> C
// F (1) --0--> D

// Assume that a one-hot code is used with the state assignment y[5:0] = 000001(A), 000010(B), 000100(C), 001000(D), 010000(E), 100000(F)

// Write a Verilog for the signal Y1, which is the input of state flip-flop y[1], for the signal Y3, which is the input of state flip-flop y[3]. Derive the Verilog by inspection assuming a one-hot encoding.


Build a circuit that has one 3-bit input, then outputs the same vector, and also splits it into three separate 1-bit outputs. Connect output o0 to the input vector's position 0, o1 to position 1, etc.


Build a combinational circuit that splits an input half-word (16 bits, [15:0] ) into lower [7:0] and upper [15:8] bytes.


Create a module that implements a NOR gate.


Build an XOR gate three ways, using an assign statement (output out_assign), a combinational always block (output out_always_comb), and a clocked always block (output out_always_ff). Note that the clocked always block produces a different circuit from the other two: There is a flip-flop so the output is delayed.


Consider the state machine shown below:

// A (0) --0--> B
// A (0) --1--> A
// B (0) --0--> C
// B (0) --1--> D
// C (0) --0--> E
// C (0) --1--> D
// D (0) --0--> F
// D (0) --1--> A
// E (1) --0--> E
// E (1) --1--> D
// F (1) --0--> C
// F (1) --1--> D

// Resets into state A. For this part, assume that a one-hot code is used with the state assignment y[6:1] = 000001, 000010, 000100, 001000, 010000, 100000 for states A, B,..., F, respectively.

// Write Verilog for the next-state signals Y2 and Y4 corresponding to signal y[2] and y[4]. Derive the logic equations by inspection assuming a one-hot encoding.


Create a 1-bit wide, 256-to-1 multiplexer. The 256 inputs are all packed into a single 256-bit input vector. sel=0 should select in[0], sel=1 selects bits in[1], sel=2 selects bits in[2], etc.


Consider an n-bit shift register circuit. Inputs E are for enabling shift, R for value to load, L is asserted when it should load, and w is the input to the first stage of the shift register. Write a Verilog module named top_module for one stage of this circuit, including both the flip-flop and multiplexers.


Given the finite state machine circuit described below, assume that the D flip-flops are initially reset to zero before the machine begins.

// Build this circuit in Verilog.

// Input x goes to three different two-input gates: a XOR, an AND, and a OR gate. Each of the three gates is connected to the input of a D flip-flop and then the flip-flop outputs all go to a three-input XNOR, whose output is Z. The second input of the XOR is its corresponding flip-flop's output, the second input of the AND is its corresponding flip-flop's complemented output, and finally the second input of the OR is its corresponding flip-flop's complementary output.


Rule 110 is a one-dimensional cellular automaton with interesting properties (such as being Turing-complete). There is a one-dimensional array of cells (on or off). At each time step, the state of each cell changes. In Rule 110, the next state of each cell depends only on itself and its two neighbours, according to the following table:
// Left | Center | Right | Center's next state
// 1 | 1 | 1 | 0
// 1 | 1 | 0 | 1
// 1 | 0 | 1 | 1
// 1 | 0 | 0 | 0
// 0 | 1 | 1 | 1
// 0 | 1 | 0 | 1
// 0 | 0 | 1 | 1
// 0 | 0 | 0 | 0
// In this circuit, create a 512-cell system (q[511:0]), and advance by one time step each clock cycle. The synchronous active high load input indicates the state of the system should be loaded with data[511:0]. Assume the boundaries (q[-1] and q[512]) are both zero (off).


The following is the state transition table for a Moore state machine with one input, one output, and four states. Implement this state machine. Include a synchronous active high reset that resets the FSM to state A.
// State | Next state in=0, Next state in=1 | Output
// A | A, B | 0
// B | C, B | 0
// C | A, D | 0
// D | C, B | 1


This is a combinational circuit. Read the simulation waveforms to determine what the circuit does, then implement it.

// time            a               b               c               d               e               q
// 0ns             x               x               x               x               x               x
// 5ns             x               x               x               x               x               x
// 10ns            x               x               x               x               x               x
// 15ns            a               b               0               d               e               b
// 20ns            a               b               1               d               e               e
// 25ns            a               b               2               d               e               a
// 30ns            a               b               3               d               e               d
// 35ns            a               b               4               d               e               f
// 40ns            a               b               5               d               e               f
// 45ns            a               b               6               d               e               f
// 50ns            a               b               7               d               e               f
// 55ns            a               b               8               d               e               f
// 60ns            a               b               9               d               e               f
// 65ns            a               b               a               d               e               f
// 70ns            a               b               b               d               e               f
// 75ns            a               b               c               d               e               f
// 80ns            a               b               d               d               e               f
// 85ns            a               b               e               d               e               f
// 90ns            a               b               f               d               e               f


Find the bug and fix this 8-bit wide 2-to-1 mux.

// module top_module (
//     input sel,
//     input [7:0] a,
//     input [7:0] b,
//     output out  );

//     assign out = (~sel & a) | (sel & b);

// endmodule


Consider this Verilog module "full_module":

// module full_module (
//     input [2:0] r,
//     input L,
//     input clk,
//     output reg [2:0] q
);

// always @(posedge clk) begin
//     if (L) begin
//         q <= r;
//     end else begin
//         q <= {q[1] ^ q[2], q[0], q[2]};
//     end
// end

// endmodule

// You want to create a hierarchical Verilog design where a flipflop and 2-1 multiplexer are in a submodule, and that submodule is instantiated three times in this code. Create the submodule called "top_module".


For each bit in a 32-bit vector, capture when the input signal changes from 1 in one clock cycle to 0 the next. "Capture" means that the output will remain 1 until the register is reset (active high synchronous reset).


Create 8 D flip-flops. All DFFs should be triggered by the positive edge of clk.


Assume that you have two 8-bit 2's complement numbers, a[7:0] and b[7:0]. These numbers are added to produce s[7:0]. Also compute whether a (signed) overflow has occurred.


Given the following Moore state machine with 3 input (d, done_counting, ack) and 3 outputs (shift_ena, counting, done). Unless otherwise stated in the diagram below, assume outputs are 0 and inputs are don't cares.

// S () --d=0--> S
// S () --d=1--> S1
// S1 () --d=0--> S
// S1 () --d=1--> S11
// S11 () --d=0--> S110
// S11 () --d=1--> S11
// S110 () --d=0--> S
// S110 () --d=1--> B0
// B0 (shift_ena=1) -- (always go to next cycle) --> B1
// B1 (shift_ena=1) -- (always go to next cycle) --> B2
// B2 (shift_ena=1) -- (always go to next cycle) --> B3
// B3 (shift_ena=1) -- (always go to next cycle) --> Count
// Count (counting=1) --!(done_counting)--> Count
// Count (counting=1) --(done_counting)--> Wait
// Wait (done=1) --ack=0--> Wait
// Wait (done=1) --ack=1--> S

// At reset, the state machine starts in state "S". Derive next-state logic equations and output logic equations by inspection assuming the following one-hot encoding is used: (S, S1, S11, S110, B0, B1, B2, B3, Count, Wait) = (10'b0000000001, 10'b0000000010, 10'b0000000100, ... , 10'b1000000000)

// Derive state transition and output logic equations by inspection assuming a one-hot encoding. Implement only the state transition logic and output logic (the combinational logic portion) for this state machine.

// Write code that generates the following equations:

// - B3_next -- next-state logic for state B3
// - S_next
// - S1_next
// - Count_next
// - Wait_next
// - done -- output logic
// - counting
// - shift_ena


Build a two-bit saturating counter. The counter increments (up to a maximum of 3) when train_valid = 1 and train_taken = 1. It decrements (down to a minimum of 0) when train_valid = 1 and train_taken = 0. When not training (train_valid = 0), the counter keeps its value unchanged. areset is a positive edge triggered asynchronous reset that resets the counter to weakly not-taken (2'b01). Output state[1:0] is the two-bit counter value.


Build a priority encoder for 8-bit inputs. Given an 8-bit vector, the output should report the first (least significant) bit in the vector that is 1. Report zero if the input vector has no bits that are high. For example, the input 8'b10010000 should output 3'd4, because bit[4] is first bit that is high.


Suppose you're building a circuit to process scancodes from a PS/2 keyboard for a game. Given the last two bytes of scancodes received, you need to indicate whether one of the arrow keys on the keyboard have been pressed. This involves a fairly simple mapping, which can be implemented as a case statement (or if-elseif) with four cases.
// Scancode[15:0] | Arrow key
// 16'he06b | left arrow
// 16'he072 | down arrow
// 16'he074 | right arrow
// 16'he075 | up arrow
// Anything else | none
// Your circuit has one 16-bit input, and four outputs. Build this circuit that recognizes these four scancodes and asserts the correct output.


Implement a 4-bit adder with full adders. The output sum should include the overflow bit.


Build a 32-bit global history shift register, including support for rolling back state in response to a pipeline flush caused by a branch misprediction. When a branch prediction is made (predict_valid = 1), shift in predict_taken from the LSB side to update the branch history for the predicted branch. (predict_history[0] is the direction of the youngest branch.) When a branch misprediction occurs (train_mispredicted = 1), load the branch history register with the history after the completion of the mispredicted branch. This is the history before the mispredicted branch (train_history) concatenated with the actual result of the branch (train_taken). If both a prediction and misprediction occur at the same time, the misprediction takes precedence, because the pipeline flush will also flush out the branch that is currently making a prediction. predict_history is the value of the branch history register. areset is a positive edge triggered asynchronous reset that resets the history counter to zero.


Implement the following circuit. Create two intermediate wires (named anything you want) to connect the AND and OR gates together. Note that the wire that feeds the NOT gate is really wire `out`, so you do not necessarily need to declare a third wire here. Notice how wires are driven by exactly one source (output of a gate), but can feed multiple inputs.

// The circuit is composed of two layers. The first layer, counting from the input, is two AND gates: one whose input is connected to a and b, and the second is connected to c and d. The second layer there is an OR gate to OR the two AND outputs, connected the output 'out'. Additionally, there is an inverted output 'out_n'.


In this question, you will design a circuit for an 8x1 memory, where writing to the memory is accomplished by shifting-in bits, and reading is "random access", as in a typical RAM. You will then use the circuit to realize a 3-input logic function. First, create an 8-bit shift register with 8 D-type flip-flops. Label the flip-flop outputs from Q[0]...Q[7]. The shift register input should be called S, which feeds the input of Q[0] (MSB is shifted in first). The enable input is synchronous active high and controls whether to shift. Extend the circuit to have 3 additional inputs A,B,C and an output Z. The circuit's behaviour should be as follows: when ABC is 000, Z=Q[0], when ABC is 001, Z=Q[1], and so on. Your circuit should contain ONLY the 8-bit shift register, and multiplexers.


A heating/cooling thermostat controls both a heater (during winter) and an air conditioner (during summer). Implement a circuit that will turn on and off the heater, air conditioning, and blower fan as appropriate. The thermostat can be in one of two modes: heating (mode = 1) and cooling (mode = 0). In heating mode, turn the heater on when it is too cold (too_cold = 1) but do not use the air conditioner. In cooling mode, turn the air conditioner on when it is too hot (too_hot = 1), but do not turn on the heater. When the heater or air conditioner are on, also turn on the fan to circulate the air. In addition, the user can also request the fan to turn on (fan_on = 1), even if the heater and air conditioner are off.


A single-output digital system with four inputs (a,b,c,d) generates a logic-1 when 2, 7, or 15 appears on the inputs, and a logic-0 when 0, 1, 4, 5, 6, 9, 10, 13, or 14 appears. The input conditions for the numbers 3, 8, 11, and 12 never occur in this system. For example, 7 corresponds to a,b,c,d being set to 0,1,1,1, respectively. Determine the output out_sop in minimum sum-of-products form, and the output out_pos in minimum product-of-sums form.


A linear feedback shift register is a shift register usually with a few XOR gates to produce the next state of the shift register. A Galois LFSR is one particular arrangement where bit positions with a "tap" are XORed with the output bit to produce each bit's next value, while bit positions without a tap shift. Build a 32-bit Galois LFSR with taps at bit positions 32, 22, 2, and 1. Reset should be active high synchronous, and should reset the output q to 32'h1.


The 7400-series integrated circuits are a series of digital chips with a few gates each. The 7420 is a chip with two 4-input NAND gates.

// Create a module with the same functionality as the 7420 chip. It has 8 inputs and 2 outputs.


A "population count" circuit counts the number of '1's in an input vector. Build a population count circuit for a 255-bit input vector.


You are given a four-bit input vector in[3:0]. We want to know some relationships between each bit and its neighbour:
// (1) out_both: Each bit of this output vector should indicate whether both the corresponding input bit and its neighbour to the left (higher index) are '1'. For example, out_both[2] should indicate if in[2] and in[3] are both 1. Since in[3] has no neighbour to the left, the answer is obvious so we don't need to know out_both[3].
// (2) out_any: Each bit of this output vector should indicate whether any of the corresponding input bit and its neighbour to the right are '1'. For example, out_any[2] should indicate if either in[2] or in[1] are 1. Since in[0] has no neighbour to the right, the answer is obvious so we don't need to know out_any[0].
// (3) out_different: Each bit of this output vector should indicate whether the corresponding input bit is different from its neighbour to the left. For example, out_different[2] should indicate if in[2] is different from in[3]. For this part, treat the vector as wrapping around, so in[3]'s neighbour to the left is in[0].


This is a combinational circuit. Read the simulation waveforms to determine what the circuit does, then implement it.

// time            a                  q
// 0ns             x                  x
// 5ns             x                  x
// 10ns            x                  x
// 15ns            0               1232
// 20ns            1               aee0
// 25ns            2               27d4
// 30ns            3               5a0e
// 35ns            4               2066
// 40ns            5               64ce
// 45ns            6               c526
// 50ns            7               2f19
// 55ns            0               1232
// 60ns            1               aee0
// 65ns            2               27d4
// 70ns            4               2066
// 75ns            1               aee0
// 80ns            1               aee0
// 85ns            3               5a0e
// 90ns            5               64ce


Build a decade counter that counts from 0 through 9, inclusive, with a period of 10. The reset input is active high synchronous, and should reset the counter to 0. We want to be able to pause the counter rather than always incrementing every clock cycle, so the "slowena" input if high indicates when the counter should increment.


Implement the following circuit in Verilog. Two inputs (in1 and in2) go to an AND gate, but the in2 input to the AND gate has a bubble. The output of the AND gate is connected to 'out'.


The module assigns the output port to the same value as the input port combinationally.


Consider the follow Moore machine with the diagram described below:

// B (1) --0--> A
// B (1) --1--> B
// A (0) --0--> B
// A (0) --1--> A

// Write Verilog implementing this state machine. It should asynchronously reset into state B if reset if high.


A dual-edge triggered flip-flop is triggered on both edges of the clock. However, FPGAs don't have dual-edge triggered flip-flops, and always @(posedge clk or negedge clk) is not accepted as a legal sensitivity list. Build a circuit that functionally behaves like a dual-edge triggered flip-flop.


Create a module that implements an XNOR gate.


Module A implements the boolean function z = (x^y) & x.

// Module B can be described by the following simulation waveform:

// time            x               y               z
// 0ns             0               0               1
// 5ns             0               0               1
// 10ns            0               0               1
// 15ns            0               0               1
// 20ns            0               0               1
// 25ns            1               0               0
// 30ns            1               0               0
// 35ns            0               1               0
// 40ns            0               1               0
// 45ns            1               1               1
// 50ns            1               1               1
// 55ns            0               0               1
// 60ns            0               1               0
// 65ns            0               1               0
// 70ns            1               1               1
// 75ns            0               1               0
// 80ns            0               1               0
// 85ns            0               1               0
// 90ns            1               0               0

// Now consider a top-level that uses two A submodules and two B submodules. The first input of all four submodules is connect to input 'x', and the second input of all four submodules is connected to 'y'. The output of the first A submodule is connected to a two-input OR, along with the output of the first B submodule. The second pair of A and B submodules is similarly connected to an AND gate. The output of the OR and the AND is connected to an XOR, whose output is 'z'.

// Implement this circuit in Verilog.


Build a 100-bit left/right rotator, with synchronous load and left/right enable. A rotator shifts-in the shifted-out bit from the other end of the register, unlike a shifter that discards the shifted-out bit and shifts in a zero. If enabled, a rotator rotates the bits around and does not modify/discard them.
// (1) load: Loads shift register with data[99:0] instead of rotating. Synchronous active high.
// (2) ena[1:0]: Synchronous. Chooses whether and which direction to rotate:
//     (a) 2'b01 rotates right by one bit,
//     (b) 2'b10 rotates left by one bit,
//     (c) 2'b00 and 2'b11 do not rotate.
// (3) q: The contents of the rotator.


Build a counter that counts from 0 to 999, inclusive, with a period of 1000 cycles. The reset input is active high synchronous, and should reset the counter to 0.


Create a module that implements a NOT gate.


Given the follow state machine with 1 input and 2 outputs (the outputs are given as "(out1, out2)"):

// S0 (0, 0) --0--> S0
// S0 (0, 0) --1--> S1
// S1 (0, 0) --0--> S0
// S1 (0, 0) --1--> S2
// S2 (0, 0) --0--> S0
// S2 (0, 0) --1--> S3
// S3 (0, 0) --0--> S0
// S3 (0, 0) --1--> S4
// S4 (0, 0) --0--> S0
// S4 (0, 0) --1--> S5
// S5 (0, 0) --0--> S8
// S5 (0, 0) --1--> S6
// S6 (0, 0) --0--> S9
// S6 (0, 0) --1--> S7
// S7 (0, 1) --0--> S0
// S7 (0, 1) --1--> S7
// S8 (1, 0) --0--> S0
// S8 (1, 0) --1--> S1
// S9 (1, 1) --0--> S0
// S9 (1, 1) --1--> S1

// Suppose this state machine uses one-hot encoding, where state[0] through state[9] correspond to the states S0 though S9, respectively. The outputs are zero unless otherwise specified.

// Write Verilog implementing the state transition logic and output logic portions of the state machine (but not the state flip-flops). You are given the current state in state[9:0] and must produce next_state[9:0] and the two outputs. Derive the logic equations by inspection assuming a one-hot encoding.


A JK flip-flop has the below truth table. Note: Qold is the output of the flip-flop before the positive clock edge.
// J | K | Q
// 0 | 0 | Qold
// 0 | 1 | 0
// 1 | 0 | 1
// 1 | 1 | ~Qold


A "population count" circuit counts the number of '1's in an input vector. Build a population count circuit for a 3-bit input vector.


Given five 1-bit signals (a, b, c, d, and e), compute all 25 pairwise one-bit comparisons in the 25-bit output vector. The output should be 1 if the two bits being compared are equal. Example: out[24] = ~a ^ a; out[23] = ~a ^ b; out[22] = ~a ^ c; ... out[ 1] = ~e ^ d; out[ 0] = ~e ^ e.


The game Lemmings involves critters with fairly simple brains. So simple that we are going to model it using a finite state machine. In the Lemmings' 2D world, Lemmings can be in one of two states: walking left (walk_left is 1) or walking right (walk_right is 1). It will switch directions if it hits an obstacle. In particular, if a Lemming is bumped on the left (by receiving a 1 on bump_left), it will walk right. If it's bumped on the right (by receiving a 1 on bump_right), it will walk left. If it's bumped on both sides at the same time, it will still switch directions. Implement a Moore state machine with two states, two inputs, and one output (internal to the module) that models this behaviour. areset is positive edge triggered asynchronous reseting the Lemming machine to walk left.


This is a combinational circuit. Read the simulation waveforms to determine what the circuit does, then implement it.

// time            a               b               q
// 0ns             0               0               0
// 5ns             0               0               0
// 10ns            0               0               0
// 15ns            0               0               0
// 20ns            0               0               0
// 25ns            0               1               0
// 30ns            0               1               0
// 35ns            1               0               0
// 40ns            1               0               0
// 45ns            1               1               1
// 50ns            1               1               1
// 55ns            0               0               0
// 60ns            0               0               0
// 65ns            0               1               0
// 70ns            0               1               0
// 75ns            1               0               0
// 80ns            1               0               0
// 85ns            1               1               1
// 90ns            1               1               1


The 7458 is a chip with four AND gates and two OR gates. Create a module in Verilog with the same functionality as the 7458 chip. It has 10 inputs and 2 outputs. You may choose to use an `assign` statement to drive each of the output wires, or you may choose to declare (four) wires for use as intermediate signals, where each internal wire is driven by the output of one of the AND gates.

// In this circuit, p1y should be the OR of two 3-input AND gates: one that ANDs p1a, p1b, and p1c, and the second that ANDs p1d, p1e, and p1f. The output p2y is the OR of two 2-input AND gates: one that ANDs p2a and p2b, and the second that ANDs p2c and p2d.


Given the state-assigned table shown below, implement the logic functions Y[0] and z.
// Present state y[2:0] | Next state Y[2:0] x=0, Next state Y[2:0] x=1 | Output z
// 000 | 000, 001 | 0
// 001 | 001, 100 | 0
// 010 | 010, 001 | 0
// 011 | 001, 010 | 1
// 100 | 011, 100 | 1


Create a module with 3 inputs and 4 outputs that behaves like wires that makes these connections: a -> w
// ; b -> x; b -> y; c -> z.


Implement a D flip flop, positive edge triggered, with an asynchronous reset "ar".


Create a 6-to-1 multiplexer. When sel is between 0 and 5, choose the corresponding data input. Otherwise, output 0. The data inputs and outputs are all 4 bits wide.


Implement a timer that counts down for a given number of clock cycles, then asserts a signal to indicate that the given duration has elapsed. A good way to implement this is with a down-counter that asserts an output signal when the count becomes 0. At each clock cycle:
// (1) If load = 1, load the internal counter with the 10-bit data, the number of clock cycles the timer should count before timing out. The counter can be loaded at any time, including when it is still counting and has not yet reached 0.
// (2) If load = 0, the internal counter should decrement by 1. The output signal tc ("terminal count") indicates whether the internal counter has reached 0. Once the internal counter has reached 0, it should stay 0 (stop counting) until the counter is loaded again.


Build a finite-state machine that searches for the sequence 1101 in an input bit stream. When the sequence is found, it should set start_shifting to 1, forever, until reset. Reset is active high synchronous.


Create 8 D flip-flops with active high synchronous reset setting the output to zero. All DFFs should be triggered by the positive edge of clk.


For each bit in an 8-bit vector, detect when the input signal changes from one clock cycle to the next (detect any edge). The output bit should be set the cycle after a 0 to 1 transition occurs.


Make a decade counter that counts 1 through 10, inclusive. The reset input is active high synchronous, and should reset the counter to 1.


This is a sequential circuit. Read the simulation waveforms to determine what the circuit does, then implement it.

// time            clk             a               q
// 0ns             0               1               x
// 5ns             1               1               4
// 10ns            0               1               4
// 15ns            1               1               4
// 20ns            0               1               4
// 25ns            1               1               4
// 30ns            0               1               4
// 35ns            1               1               4
// 40ns            0               1               4
// 45ns            1               0               4
// 50ns            0               0               4
// 55ns            1               0               5
// 60ns            0               0               5
// 65ns            1               0               6
// 70ns            0               0               6
// 75ns            1               0               0
// 80ns            0               0               0
// 85ns            1               0               1
// 90ns            0               0               1


A linear feedback shift register is a shift register usually with a few XOR gates to produce the next state of the shift register. A Galois LFSR is one particular arrangement where bit positions with a "tap" are XORed with the output bit to produce its next value, while bit positions without a tap shift. If the taps positions are carefully chosen, the LFSR can be made to be "maximum-length". A maximum-length LFSR of n bits cycles through 2**n-1 states before repeating (the all-zero state is never reached). Build a 5-bit maximal-length Galois LFSR with taps at bit positions 5 and 3. The active-high synchronous reset should reset the LFSR output to 1.


The following adder-subtractor with zero flag doesn't work. Fix the bug(s).

// synthesis verilog_input_version verilog_2001
// module top_module (
//     input do_sub,
//     input [7:0] a,
//     input [7:0] b,
//     output reg [7:0] out,
//     output reg result_is_zero
// );//

//     always @(*) begin
//         case (do_sub)
//           0: out = a+b;
//           1: out = a-b;
//         endcase

//         if (~out)
//             result_is_zero = 1;
//     end

// endmodule


Consider the function f shown in the Karnaugh map below. d is don't-care, which means you may choose to output whatever value is convenient. Implement this function.
//        x[1]x[2]
// x[3]x[4]   00 01 11 10
//  00 | d | 0 | d | d |
//  01 | 0 | d | 1 | 0 |
//  11 | 1 | 1 | d | d |
//  10 | 1 | 1 | 0 | d |


This combinational circuit is supposed to recognize 8-bit keyboard scancodes for keys 0 through 9. It should indicate whether one of the 10 cases were recognized (valid), and if so, which key was detected. If the 8-bit input is 8'h45, 8'h16, 8'h1e, 8'h26, 8'h25, 8'h2e, 8'h36, 8'h3d, 8'h3e, or 8'h46, the 4-bit output will be set to 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9 respectively, the 1-bit valid would be set to 1. If the input does not match any of the cases, both output signals would be set to 0.


Given an 8-bit input vector [7:0], reverse its bit ordering.


Implement the circuit described by the Karnaugh map below. d is don't-care, which means you may choose to output whatever value is convenient.

//        ab
// cd   01 00 10 11
//  00 | d | 0 | 1 | 1 |
//  01 | 0 | 0 | d | d |
//  11 | 0 | 1 | 1 | 1 |
//  10 | 0 | 1 | 1 | 1 |


Build a four-bit shift register that also acts as a down counter. Data is shifted in most-significant-bit first when shift_ena is 1. The number currently in the shift register is decremented when count_ena is 1. Since the full system doesn't ever use shift_ena and count_ena together, it does not matter what your circuit does if both control inputs are 1 (This mainly means that it doesn't matter which case gets higher priority).


Create a module with one input and one output that behaves like a wire.


This module is a part of the FSM for controlling the shift register, we want the ability to enable the shift register for exactly 4 clock cycles whenever the proper bit pattern is detected. Whenever the FSM is reset, assert shift_ena for 4 cycles, then 0 forever (until reset). Reset should be active high synchronous.


Build a 4-bit binary counter that counts from 0 through 15, inclusive, with a period of 16. The reset input is active high synchronous, and should reset the counter to 0.


Build a 2-to-1 mux that chooses between a and b. Choose b if both sel_b1 and sel_b2 are true. Otherwise, choose a. Do the same twice, once using assign statements and once using a procedural if statement.


Implement the circuit described by the Karnaugh map below.
//        a
// bc   0 1
//  00 | 0 | 1 |
//  01 | 1 | 1 |
//  11 | 1 | 1 |
//  10 | 1 | 1 |


Consider the FSM described by the state diagram shown below:

// A --r1=0,r2=0,r3=0--> A
// A --r1=1--> B
// A --r1=0,r2=1--> C
// A --r1=0,r2=0,r3=0--> D
// B (g1=1) --r1=1--> B
// B (g1=1) --r1=0--> A
// C (g2=1) --r2=1--> C
// C (g2=1) --r2=0--> A

// Resetn is an active-low synchronous reset that resets into state A. This FSM acts as an arbiter circuit, which controls access to some type of resource by three requesting devices. Each device makes its request for the resource by setting a signal _r[i]_ = 1, where _r[i]_ is either _r[1]_, _r[2]_, or _r[3]_. Each r[i] is an input signal to the FSM, and represents one of the three devices. The FSM stays in state _A_ as long as there are no requests. When one or more request occurs, then the FSM decides which device receives a grant to use the resource and changes to a state that sets that device's _g[i]_ signal to 1. Each _g[i]_ is an output from the FSM. There is a priority system, in that device 1 has a higher priority than device 2, and device 3 has the lowest priority. Hence, for example, device 3 will only receive a grant if it is the only device making a request when the FSM is in state _A_. Once a device, _i_, is given a grant by the FSM, that device continues to receive the grant as long as its request, _r[i]_ = 1.

// Write complete Verilog code that represents this FSM. Use separate always blocks for the state table and the state flip-flops, as done in lectures. Describe the FSM outputs, _g[i]_, using either continuous assignment statement(s) or an always block (at your discretion). Assign any state codes that you wish to use.


Build a decade counter that counts from 0 through 9, inclusive, with a period of 10. The reset input is active high synchronous, and should reset the counter to 0.


The PS/2 mouse protocol sends messages that are three bytes long. However, within a continuous byte stream, it's not obvious where messages start and end. The only indication is that the first byte of each three byte message always has in[3]=1 (but in[3] of the other two bytes may be 1 or 0 depending on data). We want a finite state machine that will search for message boundaries when given an input byte stream. The algorithm we'll use is to discard bytes until we see one with in[3]=1. We then assume that this is byte 1 of a message, and signal the receipt of a message once all 3 bytes have been received (done). The FSM should signal done in the cycle immediately after the third byte of each message was successfully received. Reset should be active high synchronous.


Create a one-bit wide, 2-to-1 multiplexer. When sel=0, choose a. When sel=1, choose b.


Build a combinational circuit with four inputs, in[3:0]. There are 3 outputs:
// (1) out_and: output of a 4-input AND gate.
// (2) out_or: output of a 4-input OR gate.
// (3) out_xor: output of a 4-input XOR gate.


Given the state-assigned table shown below, implement the finite-state machine. Reset should synchronous active high reset the FSM to state 000.

// Present state y[2:0] | Next state y[2:0] x=0, Next state y[2:0] x=1, Output z
// 000 | 000, 001 | 0
// 001 | 001, 100 | 0
// 010 | 010, 001 | 0
// 011 | 001, 010 | 1
// 100 | 011, 100 | 1


Consider a finite state machine that is used to control some type of motor. The FSM has inputs x and y, which come from the motor, and produces outputs f and g, which control the motor. There is also a clock input called clk and a reset input (synchronous, active low) called resetn. The FSM has to work as follows. As long as the reset input is asserted, the FSM stays in a beginning state, called state A. When the reset signal is de-asserted, then after the next clock edge the FSM has to set the output f to 1 for one clock cycle. Then, the FSM has to monitor the x input. When x has produced the values 1, 0, 1 in three successive clock cycles, then g should be set to 1 on the following clock cycle. While maintaining g = 1 the FSM has to monitor the y input. If y has the value 1 within at most two clock cycles, then the FSM should maintain g = 1 permanently (that is, until reset). But if y does not become 1 within two clock cycles, then the FSM should set g = 0 permanently (until reset).


Create 8 D flip-flops with active high synchronous reset. The flip-flops must be reset to 0x34 rather than zero. All DFFs should be triggered by the negative edge of clk.


Parity checking is often used as a simple method of detecting errors when transmitting data through an imperfect channel. Create a circuit that will compute a parity bit for a 8-bit byte (which will add a 9th bit to the byte). We will use "even" parity, where the parity bit is just the XOR of all 8 data bits.


The following is the state transition table for a Moore state machine with one input, one output, and four states. Use the following state encoding: A=2'b00, B=2'b01, C=2'b10, D=2'b11.Implement only the state transition logic and output logic (the combinational logic portion) for this state machine. Given the current state (state), compute the next_state and output (out) based on the state transition table.
// State | Next state in=0, Next state in=1 | Output
// A | A, B | 0
// B | C, B | 0
// C | A, D | 0
// D | C, B | 1


Consider the state machine shown below:

// A (0) --1--> B
// A (0) --0--> A
// B (0) --1--> C
// B (0) --0--> D
// C (0) --1--> E
// C (0) --0--> D
// D (0) --1--> F
// D (0) --0--> A
// E (1) --1--> E
// E (1) --0--> D
// F (1) --1--> C
// F (1) --0--> D

// Reset resets into state A and is synchronous active-high.

// Write complete Verilog code that represents this FSM. Use separate **always** blocks for the state table and the state flip-flops. Describe the FSM output, which is called _z_, using either continuous assignment statement(s) or an **always** block (at your discretion). Assign any state codes that you wish to use.


Create 16 D flip-flops. It's sometimes useful to only modify parts of a group of flip-flops. The byte-enable inputs control whether each byte of the 16 registers should be written to on that cycle. byteena[1] controls the upper byte d[15:8], while byteena[0] controls the lower byte d[7:0]. resetn is a synchronous, active-low reset. All DFFs should be triggered by the positive edge of clk.


For each bit in an 8-bit vector, detect when the input signal changes from 0 in one clock cycle to 1 the next (similar to positive edge detection). The output bit should be set the cycle after a 0 to 1 transition occurs.


Rule 90 is a one-dimensional cellular automaton with interesting properties. The rules are simple. There is a one-dimensional array of cells (on or off). At each time step, the next state of each cell is the XOR of the cell's two current neighbours:
// Left | Center | Right | Center's next state
// 1 | 1 | 1 | 0
// 1 | 1 | 0 | 1
// 1 | 0 | 1 | 0
// 1 | 0 | 0 | 1
// 0 | 1 | 1 | 1
// 0 | 1 | 0 | 0
// 0 | 0 | 1 | 1
// 0 | 0 | 0 | 0
// In this circuit, create a 512-cell system (q[511:0]), and advance by one time step each clock cycle. The load input indicates the state of the system should be loaded with data[511:0]. Assume the boundaries (q[-1] and q[512]) are both zero (off).


Create a circuit that has two 2-bit inputs A[1:0] and B[1:0], and produces an output z. The value of z should be 1 if A = B, otherwise z should be 0.


You are given a 100-bit input vector in[99:0]. We want to know some relationships between each bit and its neighbour:
// (1) out_both: Each bit of this output vector should indicate whether both the corresponding input bit and its neighbour to the left are '1'. For example, out_both[98] should indicate if in[98] and in[99] are both 1. Since in[99] has no neighbour to the left, the answer is obvious so we don't need to know out_both[99].
// (2) out_any: Each bit of this output vector should indicate whether any of the corresponding input bit and its neighbour to the right are '1'. For example, out_any[2] should indicate if either in[2] or in[1] are 1. Since in[0] has no neighbour to the right, the answer is obvious so we don't need to know out_any[0].
// (3) out_different: Each bit of this output vector should indicate whether the corresponding input bit is different from its neighbour to the left. For example, out_different[98] should indicate if in[98] is different from in[99]. For this part, treat the vector as wrapping around, so in[99]'s neighbour to the left is in[0].


Implement a D latch using an always block.


Create a 4-bit wide, 256-to-1 multiplexer. The 256 4-bit inputs are all packed into a single 1024-bit input vector. sel=0 should select bits in[3:0], sel=1 selects bits in[7:4], sel=2 selects bits in[11:8], etc.


Create a 16-bit wide, 9-to-1 multiplexer. sel=0 chooses a, sel=1 chooses b, etc. For the unused cases (sel=9 to 15), set all output bits to '1'.


Build a circuit that has two 3-bit inputs that computes the bitwise-OR of the two vectors, the logical-OR of the two vectors, and the inverse (NOT) of both vectors. Place the inverse of b in the upper half of out_not (i.e., bits [5:3]), and the inverse of a in the lower half.


The following is the state transition table for a Moore state machine with one input, one output, and four states. Use the following one-hot state encoding: A=4'b0001, B=4'b0010, C=4'b0100, D=4'b1000. Derive state transition and output logic equations by inspection assuming a one-hot encoding. Implement only the state transition logic and output logic (the combinational logic portion) for this state machine.
// State | Next state in=0, Next state in=1 | Output
// A | A, B | 0
// B | C, B | 0
// C | A, D | 0
// D | C, B | 1


Given four unsigned numbers, find the minimum. Unsigned numbers can be compared with standard comparison operators (a < b).


Build a combinational circuit with two inputs, a and b. There are 7 outputs, each with a logic gate driving it:
// (1) out_and: a and b
// (2) out_or: a or b
// (3) out_xor: a xor b
// (4) out_nand: a nand b
// (5) out_nor: a nor b
// (6) out_xnor: a xnor b
// (7) out_anotb: a and-not b


Consider a finite state machine with inputs s and w. Assume that the FSM begins in a reset state called A, as depicted below. The FSM remains in state A as long as s = 0, and it moves to state B when s = 1. Once in state B the FSM examines the value of the input w in the next three clock cycles. If w = 1 in exactly two of these clock cycles, then the FSM has to set an output z to 1 in the following clock cycle. Otherwise z has to be 0. The FSM continues checking w for the next three clock cycles, and so on. Use as few states as possible. Note that the s input is used only in state A, so you need to consider just the w input. Assume reset is active high synchronous.


One common place to see a replication operator is when sign-extending a smaller number to a larger one, while preserving its signed value. This is done by replicating the sign bit (the most significant bit) of the smaller number to the left. For example, sign-extending 4'b0101 (5) to 8 bits results in 8'b00000101 (5), while sign-extending 4'b1101 (-3) to 8 bits results in 8'b11111101 (-3). Build a circuit that sign-extends an 8-bit number to 32 bits. This requires a concatenation of 24 copies of the sign bit (i.e., replicate bit[7] 24 times) followed by the 8-bit number itself.


Implement a shift register with four D flops. Reset is active-low synchronous resettable.


A priority encoder is a combinational circuit that, when given an input bit vector, outputs the position of the first 1 bit in the vector. For example, a 8-bit priority encoder given the input 8'b10010000 would output 3'd4, because bit[4] is first bit that is high. Build a 4-bit priority encoder. For this problem, if none of the input bits are high (i.e., input is zero), output zero. Note that a 4-bit number has 16 possible combinations.


This is a Moore state machine with two states, two inputs, and one output. Implement this state machine in Verilog. Reset is an active-high asynchronous reset to state OFF.

// OFF (out=0) --j=0--> OFF
// OFF (out=0) --j=1--> ON
// ON (out=1) --k=0--> ON
// ON (out=1) --k=1--> OFF


Build a circuit with no inputs and one output. That output should always drive 0 (or logic low).


Build a circuit with no inputs and one output. That output should always drive 1 (or logic high).


Given a 100-bit input vector [99:0], reverse its bit ordering.


Implement in Verilog the following circuit: A D flip-flop takes as input the output of a two-input XOR. The flip-flop is positive edge triggered by clk, but there is no reset. The XOR takes as input 'in' along with the output 'out' of the flip-flop.


Build a 4-bit shift register (right shift), with asynchronous positive edge triggered areset, synchronous active high signals load, and enable.
// (1) areset: Resets shift register to zero.
// (2) load: Loads shift register with data[3:0] instead of shifting.
// (3) ena: Shift right (q[3] becomes zero, q[0] is shifted out and disappears).
// (4) q: The contents of the shift register. If both the load and ena inputs are asserted (1), the load input has higher priority.


Create 8 D flip-flops with active high asynchronous reset. The output should be reset to 0. All DFFs should be triggered by the positive edge of clk.


Build a combinational circuit with 100 inputs, in[99:0]. There are 3 outputs:
// (1) out_and: output of a 100-input AND gate.
// (2) out_or: output of a 100-input OR gate.
// (3) out_xor: output of a 100-input XOR gate.


Create a half adder. A half adder adds two bits (with no carry-in) and produces a sum and carry-out.


Fix any and all bugs in this code:

// module top_module (
//     input      cpu_overheated,
//     output reg shut_off_computer,
//     input      arrived,
//     input      gas_tank_empty,
//     output reg keep_driving  ); //

//     always @(*) begin
//         if (cpu_overheated)
//            shut_off_computer = 1;
//     end

//     always @(*) begin
//         if (~arrived)
//            keep_driving = ~gas_tank_empty;
//     end

// endmodule


This is a Moore state machine with two states, two inputs, and one output. Implement this state machine in Verilog. Reset is an active-high synchronous reset to state OFF.

// OFF (out=0) --j=0--> OFF
// OFF (out=0) --j=1--> ON
// ON (out=1) --k=0--> ON
// ON (out=1) --k=1--> OFF


Given several input vectors, concatenate them together then split them up into several output vectors. There are six 5-bit input vectors: a, b, c, d, e, and f, for a total of 30 bits of input. There are four 8-bit output vectors: w, x, y, and z, for 32 bits of output. The output should be a concatenation of the input vectors followed by two 1 bits (the two 1 bits should be in the LSB positions).


Create a module that implements an AND gate.


This is a Moore state machine with two states, one input, and one output. Implement this state machine in Verilog. The reset state is B and reset is active-high synchronous.

// B (out=1) --in=0--> A
// B (out=1) --in=1--> B
// A (out=0) --in=0--> B
// A (out=0) --in=1--> A


Create a full adder. A full adder adds three bits (including carry-in) and produces a sum and carry-out.


Implement in Verilog the following circuit: A two-input XNOR (connected to 'in1' and 'in2) has an output connected to the input of a two-input XOR. The second input of the XOR is 'in3.' The output of the XOR is 'out'.


For the following Karnaugh map, give the circuit implementation using one 4-to-1 multiplexer and as many 2-to-1 multiplexers as required, but using as few as possible. You are not allowed to use any other logic gate and you must use _a_ and _b_ as the multiplexer selector inputs, as shown on the 4-to-1 multiplexer below.

//       ab
// cd   00 01 11 10
//  00 | 0 | 0 | 0 | 1 |
//  01 | 1 | 0 | 0 | 0 |
//  11 | 1 | 0 | 1 | 1 |
//  10 | 1 | 0 | 0 | 1 |

// Consider a block diagram with inputs 'c' and 'd' going into a module called "top_module". This "top_module" has four outputs, mux_in[3:0], that connect to a four input mux. The mux takes as input {a,b} and ab = 00 is connected to mux_in[0], ab=01 is connected to mux_in[1], and so in. You are implementing in Verilog just the portion labelled "top_module", such that the entire circuit (including the 4-to-1 mux) implements the K-map.


The following diagram is a Mealy machine implementation of the 2's complementer. Implement in Verilog using one-hot encoding. Resets into state A and reset is asynchronous active-high.

// A --x=0 (z=0)--> A
// A --x=1 (z=1)--> B
// B --x=0 (z=1)--> B
// B --x=1 (z=0)--> B


This is a sequential circuit. The circuit consists of combinational logic and one bit of memory (i.e., one flip-flop). The output of the flip-flop has been made observable through the output state.

// Read the simulation waveforms to determine what the circuit does, then implement it.

// time            clk             a               b               state           q
// 0ns             0               1               x               x               x
// 5ns             1               1               x               x               x
// 10ns            0               0               0               x               x
// 15ns            1               0               0               0               0
// 20ns            0               0               0               0               0
// 25ns            1               0               0               0               0
// 30ns            0               0               0               0               0
// 35ns            1               0               0               0               0
// 40ns            0               0               0               0               0
// 45ns            1               0               1               0               1
// 50ns            0               0               1               0               1
// 55ns            1               1               0               0               1
// 60ns            0               1               0               0               1
// 65ns            1               1               1               0               0
// 70ns            0               1               1               0               0
// 75ns            1               0               0               1               1
// 80ns            0               0               0               1               1
// 85ns            1               1               1               0               0
// 90ns            0               1               1               0               0
// 95ns            1               1               1               1               1
// 100ns           0               1               1               1               1
// 105ns           1               1               1               1               1
// 110ns           0               1               1               1               1
// 115ns           1               1               0               1               0
// 120ns           0               1               0               1               0
// 125ns           1               0               1               1               0
// 130ns           0               0               1               1               0
// 135ns           1               0               0               1               1
// 140ns           0               0               0               1               1
// 145ns           1               0               0               0               0
// 150ns           0               0               0               0               0
// 155ns           1               0               0               0               0
// 160ns           0               0               0               0               0
// 165ns           1               0               0               0               0
// 170ns           0               0               0               0               0
// 175ns           1               0               0               0               0
// 180ns           0               0               0               0               0
// 185ns           1               0               0               0               0
// 190ns           0               0               0               0               0


Synchronous HDLC framing involves decoding a continuous bit stream of data to look for bit patterns that indicate the beginning and end of frames (packets). Seeing exactly 6 consecutive 1s (i.e., 01111110) is a "flag" that indicate frame boundaries. To avoid the data stream from accidentally containing "flags", the sender inserts a zero after every 5 consecutive 1s which the receiver must detect and discard. We also need to signal an error if there are 7 or more consecutive 1s. Create a Moore-type finite state machine to recognize these three sequences:

// (1) 0111110: Signal a bit needs to be discarded (disc).
// (2) 01111110: Flag the beginning/end of a frame (flag).
// (3) 01111111...: Error (7 or more 1s) (err).

// When the FSM is reset, it should be in a state that behaves as though the previous input were 0. The reset signal is active high synchronous. The output signals should be asserted for a complete cycle beginning on the clock cycle after the condition occurs.


We want to create a timer with one input that:

// (1) is started when a particular input pattern (1101) is detected,
// (2) shifts in 4 more bits to determine the duration to delay,
// (3) waits for the counters to finish counting, and
// (4) notifies the user and waits for the user to acknowledge the timer.

// The serial data is available on the data input pin. When the pattern 1101 is received, the circuit must then shift in the next 4 bits, most-significant-bit first. These 4 bits determine the duration of the timer delay, referred to as delay[3:0]. After that, the state machine asserts its counting output to indicate it is counting. Once the 1101 and delay[3:0] have been read, the circuit no longer looks at the data input until it resumes searching after everything else is done.

// The state machine must count for exactly (delay[3:0] + 1) * 1000 clock cycles. e.g., delay=0 means count 1000 cycles, and delay=5 means count 6000 cycles. Also output the current remaining time. This should be equal to delay for 1000 cycles, then delay-1 for 1000 cycles, and so on until it is 0 for 1000 cycles.

// When the circuit isn't counting, the count[3:0] output is don't-care (whatever value is convenient for you to implement). At that point, the circuit must assert done to notify the user the timer has timed out, and waits until input ack is 1 before being reset to look for the next occurrence of the start sequence (1101).

// The circuit should reset into a state where it begins searching for the input sequence 1101. The reset signal is active high synchronous.


A large reservior of water serves several users. In order to keep the level of water succificently high, three sensors are placed vertically at 5-inch intervals. When the water level is above the highest sensor s[3], the input flow rate should be zero. When the level is below the lowest sensor s[1], the flow rate should be at maximum (both Nominal flow valve and Supplemental flow valve opened). The flow rate when the level is between the upper and lower sensors is determined by two factors: the water level and the level previous to the last sensor change. Each water level has a nominal flow rate associated with it as show in the table below. If the sensor change indicates that the previous level was lower than the current level, the flow rate should be increased by opening the Supplemental flow valve (controlled by dfr).
// Water Level | Sensors Asserted | Nominal Flow Rate Inputs to be Asserted
// Above s[3] | s[1], s[2], s[3] | None
// Between s[3] and s[2] | s[1], s[2] | fr1
// Between s[2] and s[1]  | s[1] | fr1, fr2
// Below s[1] | None | fr1, fr2, fr3
// Also include an active-high synchronous reset that resets the state machine to a state equivalent to if the water level had been low for a long time (no sensors asserted, and all four outputs asserted).


In many (older) serial communications protocols, each data byte is sent along with a start bit and a stop bit, to help the receiver delimit bytes from the stream of bits. One common scheme is to use one start bit (0), 8 data bits, and 1 stop bit (1). The line is also at logic 1 when nothing is being transmitted (idle). Design a finite state machine that will identify when bytes have been correctly received when given a stream of bits. It needs to identify the start bit, wait for all 8 data bits, then verify that the stop bit was correct. If the stop bit does not appear when expected, the FSM must wait until it finds a stop bit before attempting to receive the next byte. Include a active-high synchronous reset. Note that the serial protocol sends the least significant bit first.


In many (older) serial communications protocols, each data byte is sent along with a start bit and a stop bit, to help the receiver delimit bytes from the stream of bits. One common scheme is to use one start bit (0), 8 data bits, and 1 stop bit (1). The line is also at logic 1 when nothing is being transmitted (idle). Design a finite state machine that will identify when bytes have been correctly received when given a stream of bits. It needs to identify the start bit, wait for all 8 data bits, then verify that the stop bit was correct. The module will also output the correctly-received data byte. out_byte needs to be valid when done is 1, and is don't-care otherwise.If the stop bit does not appear when expected, the FSM must wait until it finds a stop bit before attempting to receive the next byte. Include a active-high synchronous reset. Note that the serial protocol sends the least significant bit first. It should assert done each time it finds a stop bit.


Build a gshare branch predictor with 7-bit pc and 7-bit global history, hashed (using xor) into a 7-bit index. This index accesses a 128-entry table of two-bit saturating counters. The branch predictor should contain a 7-bit global branch history register. The branch predictor has two sets of interfaces: One for doing predictions and one for doing training. The prediction interface is used in the processor's Fetch stage to ask the branch predictor for branch direction predictions for the instructions being fetched. Once these branches proceed down the pipeline and are executed, the true outcomes of the branches become known. The branch predictor is then trained using the actual branch direction outcomes.
// When a branch prediction is requested (predict_valid = 1) for a given pc, the branch predictor produces the predicted branch direction and state of the branch history register used to make the prediction. The branch history register is then updated (at the next positive clock edge) for the predicted branch.
// When training for a branch is requested (train_valid = 1), the branch predictor is told the pc and branch history register value for the branch that is being trained, as well as the actual branch outcome and whether the branch was a misprediction (needing a pipeline flush). Update the pattern history table (PHT) to train the branch predictor to predict this branch more accurately next time. In addition, if the branch being trained is mispredicted, also recover the branch history register to the state immediately after the mispredicting branch completes execution.
// If training for a misprediction and a prediction (for a different, younger instruction) occurs in the same cycle, both operations will want to modify the branch history register. When this happens, training takes precedence, because the branch being predicted will be discarded anyway. If training and prediction of the same PHT entry happen at the same time, the prediction sees the PHT state before training because training only modifies the PHT at the next positive clock edge. The following timing diagram shows the timing when training and predicting PHT entry 0 at the same time. The training request at cycle 4 changes the PHT entry state in cycle 5, but the prediction request in cycle 4 outputs the PHT state at cycle 4, without considering the effect of the training request in cycle 4. Reset is asynchronous active-high.


The game Lemmings involves critters with fairly simple brains. So simple that we are going to model it using a finite state machine. In the Lemmings' 2D world, Lemmings can be in one of two states: walking left (walk_left is 1) or walking right (walk_right is 1). It will switch directions if it hits an obstacle. In particular, if a Lemming is bumped on the left (by receiving a 1 on bump_left), it will walk right. If it's bumped on the right (by receiving a 1 on bump_right), it will walk left. If it's bumped on both sides at the same time, it will still switch directions.
// In addition to walking left and right and changing direction when bumped, when ground=0, the Lemming will fall and say ""aaah!"". When the ground reappears (ground=1), the Lemming will resume walking in the same direction as before the fall. Being bumped while falling does not affect the walking direction, and being bumped in the same cycle as ground disappears (but not yet falling), or when the ground reappears while still falling, also does not affect the walking direction.
// In addition to walking and falling, Lemmings can sometimes be told to do useful things, like dig (it starts digging when dig=1). A Lemming can dig if it is currently walking on ground (ground=1 and not falling), and will continue digging until it reaches the other side (ground=0). At that point, since there is no ground, it will fall (aaah!), then continue walking in its original direction once it hits ground again. As with falling, being bumped while digging has no effect, and being told to dig when falling or when there is no ground is ignored. (In other words, a walking Lemming can fall, dig, or switch directions. If more than one of these conditions are satisfied, fall has higher precedence than dig, which has higher precedence than switching directions.)
// Although Lemmings can walk, fall, and dig, Lemmings aren't invulnerable. If a Lemming falls for too long then hits the ground, it can splatter. In particular, if a Lemming falls for more than 20 clock cycles then hits the ground, it will splatter and cease walking, falling, or digging (all 4 outputs become 0), forever (Or until the FSM gets reset). There is no upper limit on how far a Lemming can fall before hitting the ground. Lemmings only splatter when hitting the ground; they do not splatter in mid-air.
// Implement a Moore state machine that models this behaviour. areset is positive edge triggered asynchronous reseting the Lemming machine to walk left.


We want to create a timer that:
// (1) is started when a particular pattern (1101) is detected,
// (2) shifts in 4 more bits to determine the duration to delay,
// (3) waits for the counters to finish counting, and
// (4) notifies the user and waits for the user to acknowledge the timer.
// In this problem, implement just the finite-state machine that controls the timer. The data path (counters and some comparators) are not included here.
// The serial data is available on the data input pin. When the pattern 1101 is received, the state machine must then assert output shift_ena for exactly 4 clock cycles. After that, the state machine asserts its counting output to indicate it is waiting for the counters, and waits until input done_counting is high.At that point, the state machine must assert done to notify the user the timer has timed out, and waits until input ack is 1 before being reset to look for the next occurrence of the start sequence (1101). The state machine should have a active high synchronous reset, setting the state to where it begins searching for the input sequence 1101.


The "game" is played on a two-dimensional grid of cells, where each cell is either 1 (alive) or 0 (dead). At each time step, each cell changes state depending on how many neighbours it has:
// (1) 0-1 neighbour: Cell becomes 0.
// (2) 2 neighbours: Cell state does not change.
// (3) 3 neighbours: Cell becomes 1.
// (4) 4+ neighbours: Cell becomes 0.
// The game is formulated for an infinite grid. In this circuit, we will use a 16x16 grid. To make things more interesting, we will use a 16x16 toroid, where the sides wrap around to the other side of the grid. For example, the corner cell (0,0) has 8 neighbours: (15,1), (15,0), (15,15), (0,1), (0,15), (1,1), (1,0), and (1,15). The 16x16 grid is represented by a length 256 vector, where each row of 16 cells is represented by a sub-vector: q[15:0] is row 0, q[31:16] is row 1, etc.
// (1) load: Loads data into q at the next clock edge, for loading initial state. Active high synchronous.
// (2) q: The 16x16 current state of the game, updated every clock cycle.
// The game state should advance by one timestep every clock cycle.


The game Lemmings involves critters with fairly simple brains. So simple that we are going to model it using a finite state machine. In the Lemmings' 2D world, Lemmings can be in one of two states: walking left (walk_left is 1) or walking right (walk_right is 1). It will switch directions if it hits an obstacle. In particular, if a Lemming is bumped on the left (by receiving a 1 on bump_left), it will walk right. If it's bumped on the right (by receiving a 1 on bump_right), it will walk left. If it's bumped on both sides at the same time, it will still switch directions.
// In addition to walking left and right and changing direction when bumped, when ground=0, the Lemming will fall and say "aaah!". When the ground reappears (ground=1), the Lemming will resume walking in the same direction as before the fall. Being bumped while falling does not affect the walking direction, and being bumped in the same cycle as ground disappears (but not yet falling), or when the ground reappears while still falling, also does not affect the walking direction.
// In addition to walking and falling, Lemmings can sometimes be told to do useful things, like dig (it starts digging when dig=1). A Lemming can dig if it is currently walking on ground (ground=1 and not falling), and will continue digging until it reaches the other side (ground=0). At that point, since there is no ground, it will fall (aaah!), then continue walking in its original direction once it hits ground again. As with falling, being bumped while digging has no effect, and being told to dig when falling or when there is no ground is ignored. (In other words, a walking Lemming can fall, dig, or switch directions. If more than one of these conditions are satisfied, fall has higher precedence than dig, which has higher precedence than switching directions.)
// Implement a Moore state machine that models this behaviour. areset is positive edge triggered asynchronous reseting the Lemming machine to walk left.


Create a set of counters suitable for use as a 12-hour clock (with am/pm indicator). Your counters are clocked by a fast-running clk, with a pulse on ena whenever your clock should increment (i.e., once per second, while "clk" is much faster than once per second). The signal "pm" is asserted if the clock is PM, or is otherwise AM. hh, mm, and ss are two BCD (Binary-Coded Decimal) digits each for hours (01-12), minutes (00-59), and seconds (00-59). Reset is the active high synchronous signal that resets the clock to "12:00 AM." Reset has higher priority than enable and can occur even when not enabled.


The game Lemmings involves critters with fairly simple brains. So simple that we are going to model it using a finite state machine. In the Lemmings' 2D world, Lemmings can be in one of two states: walking left (walk_left is 1) or walking right (walk_right is 1). It will switch directions if it hits an obstacle. In particular, if a Lemming is bumped on the left (by receiving a 1 on bump_left), it will walk right. If it's bumped on the right (by receiving a 1 on bump_right), it will walk left. If it's bumped on both sides at the same time, it will still switch directions.
// In addition to walking left and right and changing direction when bumped, when ground=0, the Lemming will fall and say "aaah!". When the ground reappears (ground=1), the Lemming will resume walking in the same direction as before the fall. Being bumped while falling does not affect the walking direction, and being bumped in the same cycle as ground disappears (but not yet falling), or when the ground reappears while still falling, also does not affect the walking direction.
// Implement a Moore state machine that models this behaviour. areset is positive edge triggered asynchronous reseting the Lemming machine to walk left.


Build a 4-digit BCD (binary-coded decimal) counter. Each decimal digit is encoded using 4 bits: q[3:0] is the ones digit, q[7:4] is the tens digit, etc. For digits [3:1], also output an enable signal indicating when each of the upper three digits should be incremented. Include a synchronous active-high reset.