Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice: Verilog Exercises and Interview Questions

Twelve Verilog practice problems with solutions and common interview questions: encoders, parity, Gray code, LFSR, edge detector, debouncer, clock divider and more.

Reading Verilog is not the same as writing it. This final lesson gives you a set of exercises with full solutions, plus the interview questions that come up again and again for hardware design roles. Try each exercise on paper or in your own simulator before you read the solution, and then compare. Several come with C stand-ins that implement the same function so you can compute expected values to test against.

Verilog and its simulators do not run on this site, so the Verilog is read-only; the C programs are labelled stand-ins. For testing your own solutions, free tools such as Icarus Verilog with GTKWave or Verilator work well, and the testbench style from self-checking testbenches applies to every exercise.

Exercise 1: priority encoder

Write a module with an 8-bit input req and outputs valid and a 3-bit index giving the position of the highest set bit.

VERILOG
module prio_enc8 (input [7:0] req, output reg valid, output reg [2:0] index);
  integer i;
  always @* begin
    valid = 1'b0;
    index = 3'd0;
    for (i = 0; i < 8; i = i + 1)
      if (req[i]) begin valid = 1'b1; index = i[2:0]; end   // later (higher) bits win
  end
endmodule

The loop assigns in increasing order, so the last (highest) set bit wins. Defaults at the top avoid latches.

Exercise 2: parity and popcount

Compute the even parity bit of a 16-bit word, and the number of set bits.

VERILOG
module parity16 (input [15:0] d, output p);
  assign p = ^d;                 // reduction XOR: 1 if an odd number of ones
endmodule

For popcount use a loop in a function (synthesizable because the bound is constant): for (i = 0; i < 16; i = i + 1) n = n + d[i];. The first stand-in implements these two functions plus Gray conversion (Exercise 3) so you can generate test vectors:

C Stand-in: reference functions for exercises 1 to 3

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Exercise 3: binary to Gray and back

VERILOG
assign gray = bin ^ (bin >> 1);

// Gray to binary: each binary bit is the XOR of all higher gray bits
integer k;
always @* begin
  bin[N-1] = gray[N-1];
  for (k = N-2; k >= 0; k = k - 1) bin[k] = bin[k+1] ^ gray[k];
end

The conversion back is a chain of XORs: a good place to explain why Gray conversion costs one gate level but the reverse costs N (see clock domain crossing for why you use Gray).

Exercise 4: rising-edge detector

Output a one-cycle pulse when the (already synchronized) input goes from 0 to 1.

VERILOG
module edge_detect (input clk, rst_n, din, output pulse);
  reg prev;
  always @(posedge clk or negedge rst_n)
    if (!rst_n) prev <= 1'b0;
    else        prev <= din;
  assign pulse = din & ~prev;
endmodule

One flip-flop remembers the previous value; the pulse is high only in the cycle where the current value is 1 and the previous was 0. Falling edge: ~din & prev.

Exercise 5: clock divider and enable pulse

Do not build a second clock from a divided signal in an FPGA; generate a one-cycle enable pulse every N cycles and use it as a clock enable:

VERILOG
module tick_gen #(parameter N = 50_000_000) (input clk, rst_n, output reg tick);
  reg [$clog2(N)-1:0] cnt;
  always @(posedge clk or negedge rst_n)
    if (!rst_n) begin cnt <= 0; tick <= 1'b0; end
    else if (cnt == N - 1) begin cnt <= 0; tick <= 1'b1; end
    else begin cnt <= cnt + 1'b1; tick <= 1'b0; end
endmodule

$clog2(N) is the number of bits to count to N. Registers that should run at the slow rate use if (tick) inside the fast clock domain: one clock, no clock-crossing problems.

Exercise 6: LFSR pseudo-random generator

A linear feedback shift register shifts every cycle and feeds the XOR of selected "tap" bits back in. A 4-bit LFSR with taps 4 and 3 (polynomial x^4 + x^3 + 1) cycles through 15 non-zero states:

VERILOG
module lfsr4 (input clk, rst_n, output reg [3:0] q);
  always @(posedge clk or negedge rst_n)
    if (!rst_n) q <= 4'b0001;                   // must not be all zeros
    else        q <= {q[2:0], q[3] ^ q[2]};
endmodule

LFSRs are used for test patterns, scrambling and CRCs. The all-zeros state is a lock-up (it stays zero forever) so reset to non-zero. The second stand-in runs the same register and reports the period:

C Stand-in: 4-bit LFSR sequence and period

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Exercise 7: button debouncer

A mechanical button bounces for milliseconds. Accept a new value only when it has been stable for a time:

VERILOG
module debounce #(parameter STABLE_CYCLES = 500_000) (
  input clk, rst_n, noisy,
  output reg clean
);
  reg sync1, sync2;
  reg [$clog2(STABLE_CYCLES)-1:0] cnt;

  always @(posedge clk or negedge rst_n)
    if (!rst_n) begin sync1 <= 0; sync2 <= 0; cnt <= 0; clean <= 0; end
    else begin
      sync1 <= noisy; sync2 <= sync1;               // synchronize first
      if (sync2 == clean) cnt <= 0;
      else if (cnt == STABLE_CYCLES - 1) begin clean <= sync2; cnt <= 0; end
      else cnt <= cnt + 1'b1;
    end
endmodule

Exercise 8: sequence generator with a shift register and counter

Design a module that outputs the 8 bits of a byte serially (parallel-in, serial-out shift register) with a load input. The core:

VERILOG
always @(posedge clk)
  if (load)       sh <= data;
  else            sh <= {1'b0, sh[7:1]};     // shift right, LSB leaves first
assign serial_out = sh[0];

Extension: add a 3-bit counter to flag when all 8 bits have been sent. This is the heart of the UART transmitter from the UART project.

Exercise 9: reduce a design with generate

Instantiate N copies of a full adder to build a ripple-carry adder parameterized by width:

VERILOG
module ripple_add #(parameter W = 8) (
  input [W-1:0] a, b, input cin, output [W-1:0] s, output cout
);
  wire [W:0] c;
  assign c[0] = cin;
  genvar i;
  generate
    for (i = 0; i < W; i = i + 1) begin : stage
      assign s[i]   = a[i] ^ b[i] ^ c[i];
      assign c[i+1] = (a[i] & b[i]) | (c[i] & (a[i] ^ b[i]));
    end
  endgenerate
  assign cout = c[W];
endmodule

genvar and generate unroll loops at elaboration time, so there is no runtime loop, only N copies of the hardware.

Exercise 10: arbiter

Write a fixed-priority arbiter where req[0] has the highest priority and grants are one-hot. The classic trick: grant = req & (~req + 1) isolates the lowest set bit. Exercise: extend it to a round-robin arbiter that remembers who was served last (hint: rotate the request vector by the last grant index, apply the fixed-priority rule, rotate back).

Interview questions

These come up constantly. Think about your own answer before checking.

  1. What is the difference between blocking and non-blocking assignments? Blocking (=) executes in order immediately; non-blocking (<=) schedules the update for the end of the time step. Use <= in clocked blocks, = in combinational blocks.
  2. What is a latch and how does it get inferred? A level-sensitive storage element, inferred when a combinational block fails to assign an output on all paths.
  3. reg versus wire? wire is a net driven continuously (by assign or a port); reg is a variable assigned procedurally. A reg does not necessarily become a flip-flop.
  4. Synchronous versus asynchronous reset? Synchronous reset is checked only at the clock edge (needs a running clock, easier timing); asynchronous reset acts at once but its release must be synchronized.
  5. What is a race condition in Verilog? Two processes accessing the same variable at the same time step with an undefined order, such as a testbench changing an input exactly at the clock edge.
  6. What is metastability and how do you handle it? Flip-flop output unresolved after a setup/hold violation; use two-flop synchronizers for single bits and Gray code or handshakes for buses.
  7. How would you design a FIFO, and how do you detect full and empty? Circular buffer with pointers, one extra bit (FIFO project).
  8. Moore versus Mealy? Output from state only versus state and inputs (Moore and Mealy).
  9. How do you divide a clock by 3 with 50% duty cycle? Needs both clock edges: a mod-3 counter on the rising edge and one on the falling edge, then OR (or AND) the outputs. In FPGAs prefer a clock enable.
  10. What is the difference between == and ===? == returns x if either operand has x or z; === compares them literally, used in testbenches.
  11. What does full_case / parallel_case do? Tool pragmas that change synthesis behaviour without changing simulation: dangerous, prefer unique case in SystemVerilog.
  12. How do you make a design testable? Add scan chains and BIST in ASIC flows; in verification, add assertions, coverage and checkers.

A final self-check

Build a short test of your understanding of Gray code, edges and the LFSR with this program, which uses a table of properties you can check by reasoning before running:

C Stand-in: property checks for Gray code and edge detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You should be able to predict the output: two rising edges in the stream, and the one-bit property holds for all 16 neighbours including the wrap from 15 back to 0.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the reduction operator ^d return for a vector d?

    A reduction XOR collapses a vector to one bit; this is the parity of the number of 1 bits.
  2. 2. Why does an LFSR need a non-zero reset value?

    With XOR feedback, zero in gives zero out; the LFSR locks up.
  3. 3. What is the better way to create a slow 1 Hz event in an FPGA design clocked at 50 MHz?

    Clock enables keep everything in one clock domain, avoiding extra clock trees and clock domain crossing problems.
  4. 4. pulse = din & ~prev where prev is din delayed by one cycle detects what?

    The pulse is high when din is 1 now and was 0 last cycle: a rising edge.

Summary

  • Practise with small, well-defined blocks: encoders, parity, Gray code, edge detectors, tick generators, LFSRs, debouncers, arbiters.
  • Always synchronize asynchronous inputs, prefer clock enables to derived clocks, and reset anything that holds state.
  • Know the standard interview topics: blocking versus non-blocking, latches, reset styles, metastability, FIFOs, Moore versus Mealy.
  • Write a reference model and a self-checking test for every exercise, even the small ones.

Next: Verilog and SystemVerilog