- Learn
- Engineering
- Electrical Engineering
- Digital Logic Design
- HDL and RTL Design
HDL and RTL Design: Verilog, VHDL and Testbenches
IntermediateLesson 7 of 7 in Digital Logic Design Course
What you will learn
- Explain what a hardware description language describes, write module interfaces, and build combinational circuits from module instances and continuous assignments in Verilog, with the matching VHDL forms.
- Explain what an HDL describes and how a module is builtTell hardware description apart from software, follow the simulate-then-synthesize design flow, and write a module with ports, signals, vectors and sized number literals.
- Build circuits structurally from gates and module instancesDescribe a circuit as connected gate primitives and module instances, wire a hierarchy with named ports, and make blocks reusable with parameters and generate loops.
- Describe combinational logic with continuous assignmentsWrite dataflow descriptions with assign statements and Verilog operators, and predict the width and value of each result.
- Explain what an HDL describes and how a module is built
- Write combinational circuits with always blocks and if and case statements, and avoid the coding errors that create latches or make simulation disagree with the synthesized hardware.
- Write combinational always blocks with if and caseDescribe decoders, encoders, multiplexers and small ALUs behaviorally with always @(*), blocking assignments, if-else chains and case statements.
- Avoid inferred latches and simulation-synthesis mismatchesRecognize the coding patterns that create latches, combinational loops, multiple drivers or simulation results that differ from the hardware, and correct them.
- Write combinational always blocks with if and case
- Write flip-flops, registers, counters and finite state machines in HDL code with correct clocking, reset and assignment semantics.
- Describe flip-flops, registers and countersWrite edge-triggered storage with synchronous or asynchronous reset and load enable, and build parameterized counters and shift registers.
- Use blocking and nonblocking assignments correctlyPredict the result of blocking and nonblocking assignments in clocked blocks, and follow the coding rules that keep simulation consistent with hardware and free of races.
- Write finite state machines in HDLCode Moore and Mealy state machines as a state register plus next-state and output logic, choose a state encoding, and trace a machine through an input sequence.
- Describe flip-flops, registers and counters
- Explain how an HDL simulator executes a design, and write self-checking testbenches for combinational and clocked modules.
- Explain how an HDL simulator runs a designDescribe event-driven simulation, time units and delays, initial and always blocks, unknown values and the limits of RTL simulation.
- Write self-checking testbenches for combinational modulesBuild a testbench that instantiates the design, applies inputs, compares the outputs with expected values and reports errors, using exhaustive, directed and random tests.
- Test clocked designs with clock, reset and timed stimulusGenerate a clock and reset, apply inputs away from the active clock edge, wait on clock edges and conditions, and check counters and state machines cycle by cycle.
- Explain how an HDL simulator runs a design
- Use register transfer notation and ASM charts to state what a digital system does in each clock cycle, and translate both into HDL code.
- Write and read register transfer notationDescribe transfers and micro-operations between registers, including conditional and simultaneous transfers, and identify the hardware and HDL code each statement implies.
- Draw and interpret ASM chartsBuild and read algorithmic state machine charts from state, decision and conditional output boxes, apply their clock timing, and translate a chart into HDL.
- Write and read register transfer notation
- Split a register-transfer design into a datapath and a controlling state machine, design both from an ASMD chart, and implement and verify the system in HDL.
- Partition a design into a datapath and a controllerIdentify datapath components, control signals and status signals, follow a step-by-step design procedure, and derive a controller from its ASM chart.
- Design a sequential shift-and-add multiplierTurn the shift-and-add multiplication algorithm into an ASMD chart, a datapath and a controller, and trace the design cycle by cycle.
- Implement and verify a datapath-controller design in HDLCode the controller and the datapath as connected modules, test the complete system with a self-checking testbench, and check the synthesized result.
- Partition a design into a datapath and a controller
HDL and RTL Design study guide
1Describe digital circuits as HDL modules
An HDL turns a circuit description into something a simulator can execute and a synthesis tool can build. The first step is to identify the blocks, their ports, and the bits each connection carries. You will read concurrent logic, connect reusable instances, and choose expressions whose widths preserve the intended result. Verilog supplies the main examples, with VHDL forms alongside them so the same hardware remains recognizable across the two languages.
1.1 Read HDL as connected hardware
An HDL describes a circuit's interface, connections, and behavior. Verilog and VHDL can describe the same circuit, even though their syntax differs. Verilog is maintained within the IEEE 1800 SystemVerilog standard; VHDL follows IEEE 1076. Start by asking what hardware a description builds and which signals connect it.
Separate hardware activity from statement order
These two assignments operate continuously:
assign y = a & b;
assign z = a | b;
Changing a can affect both outputs. Swapping the lines changes neither circuit. Each module instance and each procedural block also operates alongside the others. Statements within one procedural block have an evaluation order, but a new line does not mean that another clock cycle has passed.
Simulation evaluates a description with chosen inputs. Synthesis translates its buildable parts into a netlist of gates and flip-flops, or equivalent FPGA resources. A delay such as #5 tells the simulator to wait; it does not build a five-nanosecond timer. Write the specification, describe RTL, simulate and repair it, then synthesize and implement it. Clock timing still needs its own check.
Give a block a clear interface
A Verilog module declares its ports and the logic that drives them:
module and_or (
input wire a, b, c,
output wire y
);
assign y = (a & b) | c;
endmodule
The ports are the block's connections. input receives a signal; output drives one; inout allows a bidirectional connection. Placing this module inside another module creates an instance, a separate piece of hardware.
VHDL puts the interface in an entity and the implementation in an architecture:
library ieee;
use ieee.std_logic_1164.all;
entity and_or is
port (a, b, c : in std_logic; y : out std_logic);
end entity;
architecture rtl of and_or is
begin
y <= (a and b) or c;
end architecture;
Verilog names are case-sensitive; VHDL names are not. VHDL also checks types and assignment lengths more strictly.
Read declarations and literals before expressions
wire [7:0] d; declares eight bits. d[7] is the high bit; d[3:0] selects the low four. VHDL writes std_logic_vector(7 downto 0). A Verilog wire is driven by an assignment or instance output. A reg is assigned procedurally; its name alone does not mean that storage is built. SystemVerilog often uses logic for these roles.
In 8'hA5, the width is eight, the base is hexadecimal, and the digits represent decimal 165. 4'b1010 represents decimal 10 in four bits; 12'd100 stores decimal 100 in twelve bits. Underscores only separate digits for readability. An unsized integer such as 5 is at least 32 bits, which can affect an expression's width. VHDL uses x"A5" for a hexadecimal vector, "1010" for a binary vector, and '1' for a single bit.
Verilog simulation tracks 0, 1, x, and z. Unknown x means the simulator cannot determine a value; high-impedance z represents a released connection. VHDL's nine-valued std_logic also distinguishes uninitialized 'U'. Trace unexpected unknowns to uninitialized storage, missing drivers, or conflicting drivers; an x is not a physical voltage level.
Key Takeaways
- HDL blocks operate concurrently; statement order applies within a procedural block.
- Simulation checks behavior; synthesis builds a netlist from synthesizable constructs.
- A module instance is a separate hardware block with connected ports.
- Read vector widths, types, and literal sizes explicitly.
- Unknown and high-impedance values describe simulation states.
1.2 Connect and reuse hardware blocks
A structural description names components and connects their ports with signals. It is a textual schematic. Use it to combine blocks whose behavior has already been checked, then follow each internal connection as you would follow a wire on paper.
Build a full adder from smaller blocks
Verilog gate primitives put the output first: and g1(y, a, b); drives y. A half adder needs XOR for the sum and AND for the carry. Two half adders make a full adder:
module half_adder(input wire a, b, output wire s, c);
xor (s, a, b);
and (c, a, b);
endmodule
module full_adder(input wire a, b, cin,
output wire sum, cout);
wire s1, c1, c2;
half_adder ha1(.a(a), .b(b), .s(s1), .c(c1));
half_adder ha2(.a(s1), .b(cin), .s(sum), .c(c2));
or g3(cout, c1, c2);
endmodule
With all three inputs equal to 1, ha1 produces s1=0 and c1=1. The second half adder receives 0 and 1, so sum=1 and c2=0. The OR gate gives cout=1. The combined two-bit result is 11, decimal 3.
In .a(s1), a is the child module's port and s1 is the parent's signal. Named port connections remain clear when the declaration order changes. Positional connections instead depend on that order. Declare internal signals explicitly: an undeclared Verilog name can silently become a one-bit wire. The directive `default_nettype none makes accidental implicit nets an error.
Repeat a tested stage
A ripple-carry adder connects each stage's carry-out to the next stage's carry-in. A parameter chooses how many stages are built:
module ripple #(parameter N = 4)(
input wire [N-1:0] a, b,
input wire cin,
output wire [N-1:0] sum,
output wire cout
);
wire [N:0] c;
assign c[0] = cin;
assign cout = c[N];
genvar i;
generate
for (i=0; i<N; i=i+1) begin : stage
full_adder fa(.a(a[i]), .b(b[i]), .cin(c[i]),
.sum(sum[i]), .cout(c[i+1]));
end
endgenerate
endmodule
An instance ripple #(.N(8)) add8(...) selects eight stages. The generate loop runs during elaboration, when the hardware structure is established. It does not run once per clock. For four-bit operands 1011 and 0110, the chain yields carry 1 and sum 0001, representing 17.
Express the same hierarchy in VHDL
Declare internal wires as architecture signals. An instance uses a label and a port map:
ha1: entity work.half_adder
port map (a => a, b => b, s => s1, c => c1);
A generic, such as generic (N : integer := 4), plays the parameter's role. generic map (N => 8) selects a value for an instance. Repetition uses for i in 0 to N-1 generate ... end generate;.
Give each signal one driver in these designs and match every connection's width. Two conflicting equal-strength wire drivers resolve to x; agreeing drivers do not. A vector connected to a narrower port loses high bits, while a narrower unsigned connection is extended. A width warning can therefore identify a real wiring error even when simulation continues.
Key Takeaways
- Gate primitives list their output first; named module connections identify each port explicitly.
- Each module instance builds a separate hardware copy.
- Parameters and generics select a reusable block’s configuration.
- Generate loops establish repeated hardware during elaboration.
- Carry wires connect adjacent full-adder stages.
- Declare internal signals, match widths, and keep one driver per signal.
1.3 Choose operators and preserve every needed bit
A continuous assignment describes combinational logic that follows its inputs. Its expression determines both the operation and the result's width. Read those together: a correct arithmetic operation can still produce the wrong circuit when a needed bit is discarded.
Distinguish three uses of Boolean operators
A binary bitwise operator works in corresponding bit positions. For example, 4'b1100 & 4'b1010 gives 4'b1000. A logical operator treats each whole operand as true or false and returns one bit: 4'b1100 && 4'b1010 gives 1'b1. Unary reduction combines all bits of one vector: for d=4'b1011, &d gives 0, |d gives 1, and ^d gives 1 because three bits are set.
Likewise, ~4'b0001 gives 1110, while !4'b0001 gives a single 0. Write parentheses around intended comparisons: a & b == c parses as a & (b == c), not (a & b) == c.
Select, join, and move bits
assign y = sel ? d1 : d0; describes a multiplexer. When sel is 1 it selects d1; when 0 it selects d0. Nesting selections gives a four-way mux:
assign y = s[1] ? (s[0] ? d3 : d2)
: (s[0] ? d1 : d0);
For s=2'b10, the outer selection enters its true branch and the inner selection picks d2. Concatenation joins fields: {2'b10,3'b011} gives 5'b10011. Replication repeats a field: {4{1'b1}} gives 1111. Extending a signed four-bit x to eight bits uses {{4{x[3]}},x}, preserving the sign bit.
Logical shifts fill with zeros and discard bits shifted out. 8'b1001_0110 >> 2 gives 0010_0101; shifting the same value left once gives 0010_1100. For a signed eight-bit operand s, s >>> 2 copies the sign bit. If s holds −106, this gives −27, division by four rounded down. The signed declaration is essential to that interpretation.
Keep carry and width visible
With four-bit a, b, and sum, a one-bit cin, and a one-bit cout:
assign {cout, sum} = a + b + cin;
The five-bit destination supplies a five-bit context for the addition. For 11 plus 6 plus 1, the result is 1_0010: carry 1 and sum 2. Assigning only to four-bit sum discards the carry. Similarly, 4'd12 + 4'd7 stored in four bits becomes 0011, decimal 3. Use sized values and deliberate extensions when the intended width needs to be obvious.
VHDL uses concurrent assignments such as y <= d1 when sel = '1' else d0;, or a selected assignment with with s select. Arithmetic uses unsigned or signed from ieee.numeric_std. Addition returns the longer operand length, so first widen four-bit unsigned operands when retaining carry:
sum5 <= resize(a, 5) + resize(b, 5);
Here sum5 is five-bit unsigned. Making only the destination wider does not widen a VHDL addition's operands. Ordinary Verilog equality can return x when unknown bits prevent a decision, but a known mismatch establishes false. Testbench case equality, ===, compares unknown and high-impedance bits literally.
Key Takeaways
- Bitwise operators act per bit; logical and reduction operators produce one-bit results.
- The conditional operator builds selection logic.
- Concatenation, replication, and signed shifts control bit placement.
- Keep carry by choosing an adequate expression width.
- Widen VHDL numeric_std operands before adding when an extra carry bit is needed.
2Describe combinational logic with procedural blocks
Combinational behavior often needs more than one expression. A procedural block lets you describe a priority decision, decode a value, or select an ALU operation in a readable way. The circuit still responds to current inputs without waiting for a clock. You will follow each assignment path and distinguish an unintended latch from a simulation that failed to rerun, then use defaults, automatic sensitivity, and clear signal ownership to prevent both problems.
2.1 Describe decisions in a combinational block
A behavioral description states the result a circuit must produce. Synthesis chooses the gates. A combinational procedural block is useful when that result needs several decisions, as in an encoder, decoder, or arithmetic logic unit.
Run the block when any input changes
Use always @(*) so simulation responds to every signal read by the block. Declare its assigned variables as reg and use blocking = assignments. Within one execution, later statements see earlier blocking results; a later assignment can override a default. No clock edge is implied.
An if chain gives priority to the first true condition:
module priority4(input wire [3:0] r,
output reg [1:0] code,
output reg valid);
always @(*) begin
valid = 1'b1;
if (r[3]) code = 2'd3;
else if (r[2]) code = 2'd2;
else if (r[1]) code = 2'd1;
else if (r[0]) code = 2'd0;
else begin code = 2'd0; valid = 1'b0; end
end
endmodule
For r=0110, request bits 2 and 1 are set. The test for bit 2 succeeds first, so code=2 and valid=1. For no requests, code=0 and valid=0; the valid flag distinguishes this from a request on bit 0.
Select a branch by value
A case statement matches a selector to a branch. A decoder can begin with y=4'b0000, then, only when enabled, select 0001, 0010, 0100, or 1000 for addresses 00, 01, 10, or 11. The default at the top supplies the disabled result.
A four-bit ALU applies the same pattern to operations:
module alu4(input wire [3:0] a, b,
input wire [1:0] op,
output reg [3:0] y);
always @(*) begin
y = 4'd0;
case (op)
2'b00: y = a + b;
2'b01: y = a - b;
2'b10: y = a & b;
2'b11: y = a | b;
default: y = 4'd0;
endcase
end
endmodule
For a=1001 and b=0101, addition gives 1110, subtraction gives 0100, AND gives 0001, and OR gives 1101. These are four possible combinational functions selected by op, not four operations scheduled over time. Arithmetic results are stored in four bits.
Use loops and VHDL processes deliberately
A constant-bound for loop inside combinational logic is unrolled into hardware. For a population count, start a wide-enough temporary count at zero and add each input bit. Eight input bits can have a count of eight, so the result needs four bits. The loop's iterations do not consume clock cycles.
VHDL-2008 writes process(all). Its decisions use if ... elsif ... else ... end if; or case op is ... end case;. A selector with type std_logic_vector also admits values such as 'X', so include when others =>. Use a process variable with := when a calculated intermediate must be read immediately within that process. SystemVerilog's always_comb expresses the same combinational intent and enables additional tool checks.
Key Takeaways
- Use always @(*) and blocking assignments for combinational procedural logic.
- An if/else-if chain gives the first true condition priority.
- A case statement selects behavior by the selector value.
- Constant-bound combinational loops are unrolled into hardware.
2.2 Remove unintended storage and mismatched simulation
Combinational outputs must be determined by current inputs on every path. When a path needs an old output, the description requests storage. Checking assignment paths is therefore a hardware design task, not just a style check.
Find the path that keeps an old value
This block has no assignment when en is 0:
always @(*)
if (en) y = d;
If y was 1 before en fell, it must remain 1; if it was 0, it must remain 0. A level-sensitive latch supplies that memory. To specify combinational logic with a zero disabled output, write:
always @(*) begin
y = 1'b0;
if (en) y = d;
end
Now en=0 always produces zero. An explicit else works too. For a case, assign all outputs in every branch, add a suitable default, or give every output a default before the case. A default for one output does not cover a different output. Nor does listing only the expected input codes cover an omitted binary code.
A useful audit is to choose each branch and record the last assignment to every output. A blank entry identifies a path needing the previous value. VHDL combinational processes follow exactly this assignment-coverage rule.
Distinguish a latch from a missing event
A manually written sensitivity list can make simulation appear to store a value even when synthesis builds gates:
always @(a) y = a & b;
When only b changes, this simulated block does not run. The synthesized AND gate still responds to b. Replacing the header with always @(*) fixes the event coverage. It does not fix missing assignments inside the block; both checks are necessary. VHDL-2008 process(all) supplies automatic sensitivity.
Use blocking assignments for intermediates:
always @(*) begin
t = a ^ b;
y = t & c;
end
The second statement uses the newly computed t. Nonblocking assignment defers a target update, so a later read in that execution can see an old intermediate. Repeated simulator activity is a poor substitute for an explicit combinational dependency.
Check feedback, ownership, and buildability
An assignment such as assign x = x + 1; has no stable value. It feeds a combinational result back without a register; simulation can fail to settle and physical logic can oscillate. Put synchronous feedback through a clocked register.
Assign each signal in one block. Two procedural writers can race and can fail synthesis; multiple equal-strength wire drivers resolve to x when their driven values conflict. Do not use an extra block to patch an output that already has an owner.
Keep delays and printing in testbenches. A simulation delay does not set implemented gate timing. Power-up handling of initial differs across synthesis targets, so use reset when the design requires a known starting state. Read the synthesis report for inferred latches and multiple-driver messages. SystemVerilog always_comb lets tools check combinational intent, while always_latch marks deliberately requested latch behavior.
Key Takeaways
- A missing assignment path in combinational logic can infer a latch.
- Default assignments or complete branches must cover every output.
- Automatic sensitivity fixes missed input events, not incomplete output assignments.
- Use blocking assignments for combinational intermediates.
- Give signals one owner and put synchronous feedback through registers.
- Simulation delays and printing do not build functional datapath hardware.
3Describe sequential circuits and state machines
Sequential logic gives the circuit memory. Registers sample at clock edges, while reset and enable determine when values are cleared or kept. You will describe counters and shifts, trace nonblocking assignments from old values, and assemble state machines with explicit next-state and output logic. The examples connect the code to flip-flops and show how a change in assignment or output placement changes the cycle in which a result becomes visible.
3.1 Store and update values at clock edges
Clocked logic changes stored values at a specified edge. Between edges, the registers hold their values while combinational logic computes possible next values. This distinction lets one short block describe a flip-flop, a wide register, or a counter.
Write the clock, reset, and enable rules
always @(posedge clk) q <= d; samples d on rising edges. An eight-bit target describes eight flip-flops sharing that clock. A falling-edge design uses negedge clk. SystemVerilog’s always_ff marks a block’s clocked register intent.
A synchronous reset is checked only at the active edge:
module counter #(parameter N=4)(
input wire clk, rst, en,
output reg [N-1:0] q
);
always @(posedge clk)
if (rst) q <= 0;
else if (en) q <= q + 1'b1;
endmodule
Reset has priority over enable. With both high at an edge, q becomes zero. With both low, no assignment executes and the flip-flops hold their values. This omitted final else is intentional clocked storage; it is not an inferred level-sensitive latch.
For an asynchronous reset, use always @(posedge clk or posedge rst) with the reset branch first. Raising rst then clears the register without waiting for a clock edge. For an active-low asynchronous reset, use negedge rst_n and if (!rst_n). A synchronous reset would keep only posedge clk in the header even if its active level were low.
Set the count range and data path
An N-bit binary counter wraps after its maximum value, . The four-bit count 1111 increments to 0000. A mod-10 counter instead tests the current value and explicitly wraps after nine:
if (q == 4'd9) q <= 4'd0;
else q <= q + 1'b1;
This body belongs inside the enabled branch of a clocked counter. The comparison uses the old count at the edge. When the old count is 9, the new count becomes 0.
A four-bit shift register moves bits with q <= {q[2:0],sin};. Starting at 0000, serial bits 1, 0, 1, 1 give successive values 0001, 0010, 0101, 1011. The input enters the low bit. For a right shift, q <= {sin,q[3:1]}; puts the input at the high bit. If a register can load or shift, an if (load) ... else if (shift) ... chain gives loading priority when both are asserted.
Recognize the VHDL form
Declare a numeric counter as unsigned using ieee.numeric_std. This process uses asynchronous reset:
process(clk, rst)
begin
if rst = '1' then
q <= (others => '0');
elsif rising_edge(clk) then
if en = '1' then
q <= q + 1;
end if;
end if;
end process;
Moving the reset test inside if rising_edge(clk) makes it synchronous and the process then needs only clk in its sensitivity list. VHDL expresses the left shift with q <= q(2 downto 0) & sin;.
An uninitialized register appears unknown until some assignment establishes a known value. Reset control registers before using them. Keep enable in the data-update condition; a raw clk & en expression can create unwanted clock edges and skew. Using one clock edge across the design also preserves the full cycle for the logic between registers.
Key Takeaways
- An edge-sensitive block describes flip-flops and their next-value logic.
- Synchronous reset waits for an edge; asynchronous reset also reacts to its assertion event.
- An inactive enable means a clocked register holds its value.
- Choose binary wrap-around or an explicit modulus.
- Concatenation specifies exactly which bit enters a shift register.
- Reset and load priority follow the order of conditions.
- Keep enable in the data path instead of forming a clock with ordinary logic.
3.2 Predict simultaneous register updates
The assignment operator determines when another statement can observe a new value. For register logic, this affects both the simulated result and the hardware inferred. Work from the values present before the edge before calculating any new register value.
Compare immediate and deferred updates
A blocking assignment, =, updates its target before the next statement. A nonblocking assignment, <=, evaluates its right side when executed and schedules the target update for the nonblocking update region of the current simulation time. Separate clocked blocks can therefore sample old register values before those scheduled updates occur.
Consider two registers initially holding a=3 and b=5:
always @(posedge clk) begin
a <= b;
b <= a;
end
At the edge, the first right side is 5 and the second is 3. After the updates, a=5 and b=3: the registers swap. Reversing these two assignments to distinct targets leaves that result unchanged. If both used blocking assignment in the displayed order, a would become 5 before b read it, so both would become 5.
Trace a pipeline one edge at a time
always @(posedge clk) begin
b <= a;
c <= b;
end
With b=c=0 initially and sampled a values 1, 0, 1:
- At the first edge,
breceives 1 andcreceives oldb, which is 0. - At the second edge,
breceives 0 andcreceives oldb, now 1. - At the third edge,
breceives 1 andcreceives oldb, now 0.
Each input sample moves through one register stage per edge. Substituting b=a; c=b; collapses the two-stage behavior because c reads the newly assigned b. Blocking statements in the reverse order can happen to preserve the delay, but reordering them then changes behavior.
Prevent races between blocks
If one rising-edge block writes b=a and another writes c=b, the simulator can execute them in either order. The result at c then depends on that choice: a race condition. Nonblocking updates in both blocks ensure that c reads old b. Data still needs to be driven away from the sampling edge, and each register needs one writer.
Use blocking assignments in combinational logic, where an intermediate is meant to feed the next expression immediately:
always @(*) begin
t = a ^ b;
y = t & c;
end
Use nonblocking assignments in clocked register logic. Keep those roles in separate blocks and give each target one owner.
Match signals and variables in VHDL
A VHDL signal assignment with <= schedules an update after the process suspends. In a clocked process, b <= a; c <= b; therefore transfers old values through register stages. A process variable assigned with := changes immediately, so it can hold a temporary calculation. The assignment symbols belong to different kinds of objects in VHDL; they are not interchangeable choices for the same signal.
Key Takeaways
- Blocking assignment makes its new value visible to the next statement.
- Nonblocking assignment samples a right side before applying the scheduled target update.
- Clocked nonblocking transfers use old register values, enabling swaps and pipelines.
- Separate blocking writers at the same edge can race.
- VHDL signals defer updates; process variables update immediately.
3.3 Build an FSM with explicit state and output timing
A finite state machine stores progress through a task. Its state register changes at clock edges; its next-state and output logic evaluate the current state and inputs. Keep these responsibilities visible when translating a state diagram into HDL.
Separate the three parts
The state register holds the encoded state. Next-state logic decides the state to enter at the next edge. Output logic determines the visible signals. A Moore output depends on current state; a Mealy output depends on current state and current inputs.
For an overlapping detector of the sequence 1-0-1, use four Moore states: S0 has no useful prefix, S1 has a final 1, S2 has a final 1-0, and S3 has just completed 1-0-1. Only S3 asserts z.
module detect101(input wire clk, rst, x, output wire z);
localparam S0=2'd0, S1=2'd1, S2=2'd2, S3=2'd3;
reg [1:0] state, next;
always @(posedge clk or posedge rst)
if (rst) state <= S0;
else state <= next;
always @(*) begin
next = state;
case (state)
S0: next = x ? S1 : S0;
S1: next = x ? S1 : S2;
S2: next = x ? S3 : S0;
S3: next = x ? S1 : S2;
default: next = S0;
endcase
end
assign z = (state == S3);
endmodule
The transition from S3 on input 0 goes to S2: the final 1 of one detection can start another. Resetting to S0 after every detection would discard that overlap.
Trace state before judging output
For sampled inputs 1, 1, 0, 1, 0, 1, 1, the states after the edges are S1, S1, S2, S3, S2, S3, S1. Thus z after those edges is 0, 0, 0, 1, 0, 1, 0. Both detections include the 1 sampled on edge four.
The Mealy version needs S0, S1, and S2, with z=(state==S2) & x. It asserts while the final 1 is present, before the edge that samples it. The Moore result appears after that edge. A Mealy output can change between clock edges when its input changes; registering it makes the observation clocked and adds a cycle of latency.
Choose state representation and complete every path
Binary encoding needs bits for n states: five states need three. One-hot encoding uses five flip-flops for five states, exactly one asserted, and can simplify next-state logic. Gray encoding changes one bit per step along its chosen sequence. Synthesis may select a different encoding.
A combinational default such as next=state covers hold paths; complete branch assignments can do the same. Assign every combinational output on every path, too. For a three-state binary machine, provide recovery from the unused code. Reset supplies the intended starting state. Registering an expression based on the old state can delay its output relative to a combinational state decode.
VHDL can declare type state_t is (S0,S1,S2,S3); and signals state,next_state : state_t;. A resettable clocked process updates state; process(all) with case state is calculates next_state; a concurrent assignment decodes a Moore output. SystemVerilog expresses named state types with typedef enum.
Key Takeaways
- An FSM separates its state register, next-state logic, and output logic.
- Moore outputs depend on state; Mealy outputs also depend on inputs.
- Preserve useful sequence suffixes to allow overlapping detections.
- Binary and one-hot encodings use different storage and logic trade-offs.
- Complete combinational paths and define reset and recovery behavior.
- Registering an output changes its timing.
4Verify designs by simulation with testbenches
A simulation is useful when it checks a specified behavior at the right time. This chapter follows the simulator’s events, then builds testbenches that drive inputs and compare outputs with independent expectations. You will choose exhaustive tests for small input spaces, directed and random tests for larger ones, and a clocked driving schedule that avoids races. Reset, hold, transitions, wrap-around, and completion timing all become explicit checks.
4.1 Follow events and read settled waveforms
An HDL simulator advances through scheduled signal events. It does not continuously solve a physical circuit at every instant. Knowing when evaluations and updates occur helps explain unknown values, output changes, and testbench races.
Follow the event queue
When an input changes, a sensitive assignment or block runs and may schedule further changes. The simulator settles the work at the current time before moving to the next scheduled time. Zero-delay logic can require several evaluations without advancing physical simulation time. VHDL calls these zero-time settling steps delta cycles.
Blocking assignments update during execution. A nonblocking assignment evaluates its right side during execution but applies its target in a later update region. That update can trigger additional combinational work. A test that reads a register in the same active-edge event can therefore see the old value, even though its clocked block is about to update it.
Establish time and starting values
The directive `timescale 1ns/1ps sets a 1 ns time unit and 1 ps precision. #5 waits 5 ns and #2.5 waits 2.5 ns. An initial block starts once at time zero; an always block repeats.
`timescale 1ns/1ps
module tb_clock;
reg clk;
initial clk = 1'b0;
always #5 clk = ~clk;
initial begin
#32;
$finish;
end
endmodule
The clock rises at 5 ns, falls at 10 ns, and repeats with a 10 ns period. Without its initial zero, ~x remains x; toggling an unknown does not establish a clock. The delays describe testbench stimulus, not synthesizable timer hardware.
Interpret unknowns through the operation
An unknown does not contaminate every expression. x & 0 is 0 because either possible input produces zero. x & 1 stays unknown. Similarly, x | 1 is 1, but x | 0 is unknown. A single-bit unknown condition in if (sel) takes the else branch, so a seemingly orderly output can conceal an unknown control signal. Inspect the controls as well as the outputs.
An uninitialized register starts unknown and can later become known through a reset, load, or other known assignment. Conflicting wire drivers are another cause. Follow the first unexpected unknown backward through its input drivers.
Observe the right part of a cycle
Read a waveform after the active edge and the resulting logic has settled, before the next edge. A narrow cursor placed exactly on the edge can make the old value look like the new one. $display prints when called; $monitor prints on changes to listed signals; $time supplies the current time. $finish ends the run and $stop pauses it. VHDL uses report, assert ... report ... severity ..., and VHDL-2008 std.env.finish.
A passing RTL simulation establishes functional results for the applied cases. It leaves unvisited states and transitions untested. Zero-delay RTL also does not measure the implemented circuit's setup and hold limits; use implementation timing checks to decide whether the clock period is achievable.
Key Takeaways
- Simulators process signal events and settle work at a simulation time.
- Nonblocking target updates happen after their right sides are sampled.
- Initialize testbench clocks and state the time unit.
- Unknown propagation depends on the logic operation.
- Read settled values and distinguish functional tests from timing checks.
4.2 Make a combinational testbench check its own answers
A testbench surrounds the design with stimulus and checks. It has no external ports, instantiates the design under test, and compares observed outputs with independently obtained expectations. A clear failure count makes the same checks useful after every change.
Enumerate a small input space
A four-bit adder with two operands and carry-in has nine independent input bits. That gives combinations. A loop can assign the low nine bits of an integer to the concatenated inputs:
`timescale 1ns/1ps
module tb_adder4;
reg [3:0] a, b;
reg cin;
wire [3:0] sum;
wire cout;
reg [4:0] expected;
integer i, errors;
adder4 dut(.a(a), .b(b), .cin(cin),
.sum(sum), .cout(cout));
initial begin
errors = 0;
for (i=0; i<512; i=i+1) begin
{a,b,cin} = i;
expected = {1'b0,a} + {1'b0,b} + cin;
#10;
if ({cout,sum} !== expected) begin
errors = errors + 1;
$display("FAIL a=%d b=%d cin=%b got=%b expected=%b",
a,b,cin,{cout,sum},expected);
end
end
$display("%0d errors",errors);
$finish;
end
endmodule
adder4 is the module being tested, with the displayed port names. The stimulus variables are reg because the testbench assigns them procedurally; the DUT outputs connect to wire. expected is explicitly five bits, including carry. The delay allows the input change to propagate before comparison. It is simulation stimulus, not an adder timing guarantee.
Case inequality !== makes any unexpected x or z a definite mismatch. Ordinary != can produce x; an if with that result may skip the failure branch. The final count is therefore more reliable than simply printing a list of apparent results.
Choose an independent reference and useful cases
The reference uses arithmetic even if the DUT uses chained full adders. Copying the DUT's logic into the checker can copy its bug. Hand-calculated expectations or a test-vector file provide other reference forms. $readmemb and $readmemh can load binary or hexadecimal vectors into a testbench memory.
Exhaustive testing grows exponentially. A 32-bit adder with carry-in has 65 input bits, or roughly combinations. At a billion tests per second it would take about 1,170 years. For wider blocks, combine directed corner cases with many random cases. Test zero, maximum values, carry-in, a carry propagating across all bits, and relevant operation selections. Verilog's $random supplies random test values; random testing does not replace deliberate boundary cases.
Translate the checking pattern to VHDL
A VHDL testbench uses an entity with no ports and an architecture containing the DUT instance. A stimulus process drives signals, waits for settling, and checks them:
wait for 10 ns;
assert actual = expected
report "mismatch" severity error;
The surrounding process updates expected independently for each input. End with std.env.finish in VHDL-2008, or suspend with a final wait; when no other process keeps producing events. Include enough failure details to reproduce the input that caused a mismatch.
Key Takeaways
- A self-checking testbench drives the DUT and compares results with independent expectations.
- Enumerate all combinations when the input space is small.
- Wait for combinational results to settle before checking.
- Use case inequality to catch unexpected unknown or high-impedance outputs.
- Combine directed boundaries and random tests for wide input spaces.
- Report failures with reproducible inputs and a final result count.
4.3 Drive and check a clocked design without races
A sequential testbench must coordinate three timelines: stimulus, sampling edges, and settled outputs. Choose a consistent driving and checking schedule before writing the test loop. Then a failure can be traced to a specific input and clock cycle.
Generate clock and reset
With a 1 ns time unit, initialize clk=0 and use always #5 clk=~clk;. The signal toggles every 5 ns, so its full period is 10 ns and its frequency is 100 MHz. A 50 MHz clock needs a 20 ns period and a 10 ns toggle delay.
Hold reset for several edges, then release it away from the active edge:
initial begin
rst = 1'b1;
en = 1'b0;
repeat (2) @(posedge clk);
@(negedge clk) rst = 1'b0;
end
Changing reset or data exactly when flip-flops sample can race with the DUT. For rising-edge logic, falling-edge stimulus gives half a cycle of separation. After a rising edge, allow nonblocking updates and combinational results to settle before checking. A small testbench delay is one way to do that for a zero-delay RTL model.
Maintain a cycle-by-cycle expectation
For a mod-10 counter starting at zero, twelve enabled edges give values 1 through 9, then 0, 1, 2. Maintain a separate expected count, update it for each enabled edge, and compare every cycle. A final count alone could miss a wrong intermediate value that later returns to the expected result.
A reusable test sequence also includes disabled edges: the expected count stays unchanged while en=0. Apply reset partway through a run to check that it clears the count and defeats enable. Include wrap-around explicitly; random enable sequences may never reach it.
For a Moore 1-0-1 detector, drive one bit at each falling edge. From reset, inputs 1, 1, 0, 1, 0, 1, 1 give post-rising-edge outputs 0, 0, 0, 1, 0, 1, 0. Test failed prefixes, repeated bits, overlapping detections, and reset during a partial match. The checker must use Moore output timing; checking a Mealy output in the same way can compare different parts of the input cycle.
Wait for the intended event and guarantee termination
@(posedge clk) waits for an edge; repeat (n) @(posedge clk) waits for n edges. wait (done); waits until a condition is true and returns immediately if it is already true. Before waiting for completion, ensure the new request has actually started and the ready/done protocol identifies its response.
A separate timeout prevents a broken DUT from hanging the test:
initial begin
#100000;
$display("TIMEOUT");
$finish;
end
In VHDL, initialize clk to '0' and use clk <= not clk after 5 ns;. A stimulus process can use wait until rising_edge(clk);, wait until falling_edge(clk);, and wait until done = '1';. Assertions check settled outputs. Build a test plan that visits every state and transition, checks reset in several states, and exercises both operation and hold behavior.
Key Takeaways
- A toggle delay is half a clock period.
- Apply stimulus away from the sampling edge and check after updates settle.
- Compare every cycle with an independently maintained expected state.
- Test reset, hold behavior, wrap-around, and all FSM transitions.
- Wait for the correct transaction and add a timeout.
5Specify operations at the register transfer level
Register transfer notation and ASM charts describe a design before the HDL details. They state which operations share a clock edge, which conditions select a path, and which state comes next. You will translate these descriptions into register inputs and control logic. A counting example makes the time boundary concrete: a decision observes current contents, while the increment is applied at the edge that ends the state, which determines the final count.
5.1 Specify transfers that happen together
Register transfer notation describes what stored data becomes at an active clock edge. It names registers, operations, and the conditions that enable them. Read every right side from the same pre-edge snapshot.
Read the arrow and the control condition
R2 ← R1 means that R2 receives R1's contents at the next active edge. R1 is unchanged by the copy. T1: R2 ← R1 adds an enabling condition: the transfer occurs at an edge when T1 is 1. The arrow is an update action, not an equality between a register and a different expression.
A comma groups simultaneous operations. With R1=5 and R2=3:
T1: R1 ← R1 + R2, R2 ← R1
When T1 is active at the edge, calculate both new values from the old pair. R1 receives 5+3=8, and R2 receives 5. It does not receive the newly computed 8. The related pair R1 ← R2, R2 ← R1 swaps registers without an intermediate register.
Identify the operation and its bit behavior
Micro-operations include a copy, arithmetic, logic, shifts, and memory transfers. For example:
R3 ← R1 + R2adds;R1 ← R1 + 1increments.R3 ← R1 + R2' + 1subtracts R2 by adding its two's complement; the prime means bitwise complement.R1 ← R1 ∧ R2applies AND;∨means OR and⊕means XOR.R1 ← shl R1shifts left;R1 ← shr R1shifts right.DR ← M[AR]reads the word at address AR;M[AR] ← DRwrites it.
Widths determine which bits remain. On four-bit 1011, logical right shift gives 0101, logical left shift gives 0110, and circular right shift gives 1101. A circular shift brings the low bit back at the high end; a logical shift inserts zero. R1(0) names one bit, while R1(7:0) names a range.
Translate the notation into hardware and HDL
A conditional copy requires wires from the source register to the destination and a load enable. If R2 can receive either R1 or R3, a mux must choose the source. Specify which control wins or ensure that the controls are mutually exclusive; two requested different next values cannot both occupy R2.
Nonblocking assignments express simultaneous transfers directly:
always @(posedge clk)
if (t1) begin
r1 <= r1 + r2;
r2 <= r1;
end
Here the registers and addition have the declared width. VHDL uses signal assignments inside a clocked process:
process(clk)
begin
if rising_edge(clk) then
if t1 = '1' then
r1 <= r1 + r2;
r2 <= r1;
end if;
end if;
end process;
For this arithmetic, r1 and r2 are compatible unsigned signals. Both languages preserve old-value sampling. A trace with separate before-edge and after-edge columns exposes an accidental sequential reading of the comma immediately.
Key Takeaways
- A transfer arrow specifies a destination update at an active edge.
- A control condition enables an update; a comma groups simultaneous updates.
- All simultaneous right sides use the pre-edge register values.
- Copies, arithmetic, logic, shifts, and memory accesses are micro-operations.
- Alternative sources for one register need selection and nonconflicting control.
5.2 Read an ASM block as one clock cycle
An algorithmic state machine chart combines states, decisions, and conditional operations. Its paths describe what happens during a clock cycle and where the machine goes next. The boundary between state boxes supplies the timing.
Recognize the three elements
A rectangular state box names a state and lists its unconditional outputs or operations. A diamond decision box tests an input or status condition and has exits for 1 and 0. An oval or rounded conditional output box lists outputs or operations active only along that decision path.
An ASM block contains one state box and all decisions and conditional output boxes reached before another state box. One block occupies one clock cycle. Outputs listed in a reached box are asserted; unlisted outputs are zero. Decisions consume combinational evaluation time, not extra clock cycles. Several decisions in one block can therefore impose priority within the same cycle.
Every path must reach a next state box. A loop through decisions with no state boundary is invalid. A state box has one exit, a decision has exactly two, and each input combination must select one complete path. Register operations belong in state or conditional output boxes, not inside a decision diamond.
Keep decisions and edge updates in order
Consider this ASMD chart, an ASM chart with register operations:
| State | Operations and decision | Next state |
|---|---|---|
| IDLE | Ready; if Start, clear A | COUNT if Start, else IDLE |
| COUNT | Increment A; test current A=9 | DONE if true, else COUNT |
| DONE | Done | IDLE |
The Start path clears A at the edge leaving IDLE. COUNT therefore begins with A=0. Each COUNT cycle tests its current A, then increments at the ending edge. It sees 0 through 9, taking ten cycles. On the cycle that sees 9, the machine chooses DONE and the ending edge loads A=10. DONE contains 10, not 9.
To finish with A=9 while still incrementing on the exit edge, test A=8. Moving the increment text before the diamond on paper does not make the register update earlier.
Turn chart paths into HDL
A next-state case contains one branch per state. Decision diamonds become if statements. Combinational defaults set every output to zero and supply a next-state value before branch-specific overrides. Clocked logic performs the enabled register operations:
// In the combinational next-state case:
COUNT: if (a == 4'd9) next = DONE;
else next = COUNT;
// In the datapath's clocked block:
if (state == COUNT) a <= a + 1'b1;
An equivalent state diagram has one node per ASM block and one arc per complete path to a next state. Conditional outputs move onto the corresponding arcs. VHDL follows the same translation using case state is and if ... then, with register operations in a rising-edge process.
Key Takeaways
- A state box, decision box, and conditional output box have distinct roles.
- One ASM block lasts one cycle, however many decisions it contains.
- Register operations take effect at the edge ending the block.
- Decisions normally test current register contents during the state.
- Every input combination must select a path to a next state.
- An ASMD chart adds datapath operations to the state-machine description.
6Design datapath and controller systems
A multi-cycle algorithm becomes manageable when its data operations and sequencing have a clear interface. You will derive a datapath and controller from an ASMD chart, identify control and status signals, and use one-hot or binary state representation. A four-bit unsigned multiplier brings the pieces together: choose register widths, retain carry, trace each add and shift, and check complete requests against an independent product before reviewing synthesis results.
6.1 Separate data operations from their controller
A datapath stores and processes values. A controller chooses which operations happen in each cycle. Designing their interface makes a multi-cycle algorithm easier to implement, trace, and test.
Derive components and interface signals
Start with the inputs, outputs, and required algorithm. Draw an ASMD chart before deciding the module split. List each register's width and operations, then choose adders, counters, comparators, and muxes to support them.
A distinct register action gets a control signal from the controller to the datapath: clear, load, increment, shift, or source select. A tested condition gets a status signal from the datapath to the controller: zero, low bit, or a comparison. External request inputs enter the controller; ready or done outputs report its progress.
For the IDLE/COUNT/DONE design, the datapath has a four-bit A register with clear and increment operations. A comparator returns a9, true when current A is 9. The controller sends clr_a on IDLE's Start path and inc_a throughout COUNT. It asserts Ready in IDLE and Done in DONE.
always @(posedge clk) begin
if (clr_a) a <= 4'd0;
else if (inc_a) a <= a + 1'b1;
end
assign a9 = (a == 4'd9);
The controller's chart ensures these two controls do not conflict. The datapath owns A; the controller reads status and never assigns A in a second block. a9 reports the current register, so the exit increment still gives A=10. A deliberately computed next-value comparison would be a different status definition whose timing must be specified.
Derive a one-hot controller from incoming arcs
Use one flip-flop for each state: IDLE, COUNT, and DONE. The next value of a state bit is the OR of all paths entering it. Each path is its source state AND the conditions along that path.
- IDLE can stay active when Start is 0 or be entered from DONE.
- COUNT can be entered from IDLE with Start, or stay active when
a9is 0. - DONE is entered from COUNT when
a9is 1.
Writing a prime for NOT, a dot for AND, and a plus for OR gives:
Reset sets IDLE to 1 and the other state bits to 0. All three flip-flops update together. Output and operation controls follow the chart: inc_a=COUNT and clr_a=IDLE AND Start.
Choose the representation and verify the split
A binary controller for three states needs two state bits; synthesis derives the next-state equations from its HDL case. One-hot uses three bits and often simpler decoding. Either form must produce the same controls and external behavior.
VHDL can use an enumerated controller state and std_logic control/status ports, with an unsigned A register in a separate datapath entity. Connect them with named port map associations. Test the datapath's individual operations, then the controller's reactions to status, then their complete cycle-by-cycle behavior.
Key Takeaways
- The datapath owns data registers and arithmetic components.
- The controller sequences operations using state, requests, and status.
- Control flows toward the datapath; status flows toward the controller.
- Derive control assertions from the chart paths where operations occur.
- A one-hot next-state bit ORs the conditions on all incoming arcs.
6.2 Trace a shift-and-add multiplier
A sequential multiplier reuses one adder across several cycles. For unsigned n-bit operands, it examines multiplier bits from the low end, adds when needed, and shifts a combined partial product. The complete product needs 2n bits.
Assign a job to each register
For n=4, B holds the four-bit multiplicand and Q starts with the four-bit multiplier. A is a four-bit accumulator, C holds one carry bit, and P counts remaining steps. P must represent 4 as well as 0 through 3, so it needs three bits: . The final product is the eight-bit concatenation A followed by Q.
The ASMD has three states:
- IDLE: Ready is 1. On Start, load B and Q, clear A and C, load P=4, and enter ADD.
- ADD: decrement P. If Q0 is 1, load the five-bit sum A+B into C and A. Enter SHIFT.
- SHIFT: shift the whole C/A/Q group right, inserting zero at C. If current P is zero, return to IDLE; otherwise enter ADD.
The decrement happens at the edge ending ADD. SHIFT therefore sees the decremented count. Even when P is zero, the last shift must still occur at the edge leaving SHIFT.
Follow every carry and shifted bit
For B=1101 and initial Q=1011, initialize A=0000, C=0, P=4. Each row shows the values after the named state's ending edge:
| Operation | C | A | Q | P |
|---|---|---|---|---|
| First ADD | 0 | 1101 | 1011 | 3 |
| First SHIFT | 0 | 0110 | 1101 | 3 |
| Second ADD | 1 | 0011 | 1101 | 2 |
| Second SHIFT | 0 | 1001 | 1110 | 2 |
| Third ADD, Q0=0 | 0 | 1001 | 1110 | 1 |
| Third SHIFT | 0 | 0100 | 1111 | 1 |
| Fourth ADD | 1 | 0001 | 1111 | 0 |
| Fourth SHIFT | 0 | 1000 | 1111 | 0 |
The second addition is 0110 + 1101 = 1_0011. C keeps the leading 1. The next shift brings it into A's high bit; A's low bit moves into Q's high bit. Dropping C would corrupt every later partial product. The third ADD skips the addition but still decrements P, because a zero multiplier bit still occupies one step.
At completion, A/Q is 1000_1111, decimal 143, which is 13 times 11. B never shifted; shifting the combined C/A/Q group supplies the needed place-value movement.
Derive control and evaluate the trade-off
Load is active in IDLE with Start; decrement is active throughout ADD; add is active in ADD with Q0=1; shift is active throughout SHIFT. Q0 and the zero detector on P return status to the controller.
A one-hot controller obtains each next state from its incoming paths:
Here Z means P is zero, the prime means NOT, the dot means AND, and plus means OR. For four-bit operands, there are eight ADD/SHIFT work cycles after acceptance. Merging add and shift into one cycle can reduce this to four work cycles, but the datapath must compute the sum and place its bits into the shifted next value in that cycle. A combinational array multiplier uses more parallel addition hardware to produce a product without this eight-cycle sequence. Choose the architecture by the required throughput, latency, and hardware budget.
Key Takeaways
- B holds the multiplicand; C/A/Q hold the evolving partial product.
- Keep the adder’s carry in C before shifting.
- A zero Q0 skips addition but does not skip decrement or shift.
- P must represent n, so its width is the ceiling of log2(n+1).
- Perform the final shift even when P is already zero.
- The separate ADD and SHIFT architecture uses 2n work cycles.
- Reusing one adder exchanges hardware area for operation time.
6.3 Connect and verify the complete multiplier
Build the multiplier from three modules: a controller that owns state, a datapath that owns the partial-product registers, and a top level connecting their control and status ports. The complete four-bit implementation below follows the IDLE, ADD, and SHIFT chart.
Implement the controller, datapath, and connections
The controller resets to IDLE. Its defaults assign every combinational output on every path. Load, add, and shift are mutually exclusive; add and decrement can be asserted together because they write different registers.
module mult_ctrl(
input wire clk, rst, start, q0, zero,
output reg ready, load_regs, add_regs, decr_p, shift_regs
);
localparam S_IDLE=2'd0, S_ADD=2'd1, S_SHIFT=2'd2;
reg [1:0] state, next;
always @(posedge clk or posedge rst)
if (rst) state <= S_IDLE;
else state <= next;
always @(*) begin
next = state;
ready=0; load_regs=0; add_regs=0; decr_p=0; shift_regs=0;
case (state)
S_IDLE: begin
ready=1;
if (start) begin load_regs=1; next=S_ADD; end
end
S_ADD: begin
decr_p=1; add_regs=q0; next=S_SHIFT;
end
S_SHIFT: begin
shift_regs=1;
next=zero ? S_IDLE : S_ADD;
end
default: next=S_IDLE;
endcase
end
endmodule
module mult_data(
input wire clk, load_regs, add_regs, decr_p, shift_regs,
input wire [3:0] multiplicand, multiplier,
output wire q0, zero,
output wire [7:0] product
);
reg [3:0] A, B, Q;
reg C;
reg [2:0] P;
always @(posedge clk) begin
if (load_regs) begin
A<=4'd0; C<=1'b0; P<=3'd4;
B<=multiplicand; Q<=multiplier;
end
if (add_regs) {C,A}<={1'b0,A}+{1'b0,B};
if (decr_p) P<=P-1'b1;
if (shift_regs) {C,A,Q}<={1'b0,C,A,Q[3:1]};
end
assign q0=Q[0];
assign zero=(P==0);
assign product={A,Q};
endmodule
module multiplier4(
input wire clk, rst, start,
input wire [3:0] multiplicand, multiplier,
output wire ready,
output wire [7:0] product
);
wire load_regs, add_regs, decr_p, shift_regs, q0, zero;
mult_ctrl ctrl(.clk(clk), .rst(rst), .start(start),
.q0(q0), .zero(zero), .ready(ready), .load_regs(load_regs),
.add_regs(add_regs), .decr_p(decr_p), .shift_regs(shift_regs));
mult_data data(.clk(clk), .load_regs(load_regs),
.add_regs(add_regs), .decr_p(decr_p), .shift_regs(shift_regs),
.multiplicand(multiplicand), .multiplier(multiplier),
.q0(q0), .zero(zero), .product(product));
endmodule
The five-bit addition preserves carry in C. Both sides of the combined shift are nine bits: zero enters C, old C enters A’s high position, and old A’s low bit enters Q’s high position. Nonblocking assignments make all those transfers use old values.
Reset returns the controller to IDLE. The datapath receives known data on the next accepted request, so Product is meaningful after completion of that request. Keep Start low during reset and issue a fresh one-cycle request after reset; an interrupted operation is discarded.
VHDL uses enumerated controller states, control/status ports, and unsigned data registers. A process variable sum5 : unsigned(4 downto 0) computes sum5 := ('0' & a) + ('0' & b);. Clocked signal assignments then load its carry and low bits. The equivalent shift is c <= '0'; a <= c & a(3 downto 1); q <= a(0) & q(3 downto 1);: all read old signals.
Test every operand pair through the interface
Drive operands and Start at a falling edge while Ready is high. The next rising edge accepts them and leaves IDLE. Lower Start at the following falling edge, check the busy indication, then wait for Ready and settled Product. Independent arithmetic supplies the expected result.
`timescale 1ns/1ps
module tb_multiplier4;
reg clk=0, rst=1, start=0;
reg [3:0] multiplicand=0, multiplier=0;
wire ready;
wire [7:0] product;
reg [7:0] expected;
integer a, b, errors=0;
multiplier4 dut(.clk(clk), .rst(rst), .start(start),
.multiplicand(multiplicand), .multiplier(multiplier),
.ready(ready), .product(product));
always #5 clk=~clk;
initial begin
repeat (2) @(posedge clk);
@(negedge clk) rst=0;
for (a=0; a<16; a=a+1)
for (b=0; b<16; b=b+1) begin
@(negedge clk);
multiplicand=a; multiplier=b; expected=a*b; start=1;
@(negedge clk) start=0;
if (ready !== 1'b0) begin
$display("Request was not accepted");
$finish;
end
wait (ready === 1'b1);
#1;
if (product !== expected) begin
errors=errors+1;
$display("FAIL %0d * %0d: got %0d expected %0d",
a,b,product,expected);
end
end
$display("%0d errors",errors);
$finish;
end
initial begin
#100000;
$display("TIMEOUT");
$finish;
end
endmodule
Acceptance is labeled edge one; the fourth SHIFT completes on labeled edge nine, eight full clock periods later. With a 10 ns clock this is 80 ns from acceptance. The request is driven before acceptance, so measuring from that earlier event includes extra time. Holding Start high after completion would request a second multiplication on the next edge.
On failure, compare state, C, A, Q, and P with a hand trace and find the first differing edge. Also test reset during activity, then issue a new request and verify that no old partial product leaks into it. Before optimization, the binary controller and datapath use 18 storage bits: four each for A, B, and Q, one for C, three for P, and two for state. Re-encoding or optimization can alter that count; investigate unexpected changes and any inferred latch.
Key Takeaways
- Each data register has one owner in the datapath.
- Controller defaults cover every next-state and control path.
- The sum needs five bits and the combined shift needs nine.
- Pulse Start, observe the busy interval, and check the completed transaction.
- Four ADD/SHIFT pairs finish eight periods after acceptance.
- Compare all operand pairs, inspect the first divergent cycle, and review synthesis storage.
HDL and RTL Design examples
1Read the circuit behind the HDL
13 steps
- 1IntroductionStart with the hardware
An HDL describes connected hardware. Two assignments can react to the same input change because they operate concurrently. Moving a line up or down does not add a clock cycle.
We will follow one design from its interface to repeated instances and expressions. At each step, identify the signal’s driver, the operation it performs, and the number of bits that must reach the next connection.
- 2ExampleGive the circuit ports
This module has three inputs and one output:
module select2(input wire p, q, sel, output wire y); assign y = sel ? q : p; endmoduleThe output continuously selects
qwhensel=1andpwhensel=0. The module does not wait to be called. An instance creates this hardware and wires its ports to signals in a surrounding module. VHDL puts the ports in an entity and the selection in an architecture. - 3ExplanationRead the bit range and literal
wire [5:0] d;declares six bits, not five: the endpoints are inclusive.d[5]selects the high bit andd[2:0]selects three low bits.The literal
6'b10_1101specifies six binary bits and represents 45. The underscore changes no bits. VHDL writesstd_logic_vector(5 downto 0)and"101101". Verilog can silently convert widths, so check declarations before trusting a result. - 4ChallengeWould swapping the lines change the result?
A module contains
assign y = a ^ b;andassign z = a & b;. Both use the same inputs. If you exchange their positions, does one output now wait for the other?---reveal---
No. They still describe an XOR and an AND operating concurrently. Neither depends on the other’s output or introduces storage. Simulation evaluates signal changes, while synthesis builds the described logic; neither treats source order here as a sequence of clock cycles.
- 5ExampleFollow a named connection
An instance can connect
.a(u),.b(v), and.sum(result). The names after the dots belong to the child module; the names in parentheses are signals in the parent.Follow
.sum(result)from the child’s output to the parent’s wire. Named associations keep that meaning when the child’s port list is reordered. In VHDL,port map (a => u, b => v, sum => result)expresses the same connections. - 6ExampleTrace two half adders
A full adder uses one half adder for
aandb, another for its intermediate sum andcin, then ORs their carries.Take
a=1,b=0,cin=1. The first half adder gives sum 1 and carry 0. The second adds 1 and 1, giving sum 0 and carry 1. The final OR gives carry 1, so the full result is10, decimal 2. Both half adders exist together; they are separate hardware instances. - 7Key InsightA generate loop builds copies
A parameter
Ncan choose the width of a ripple-carry adder. Its generate loop creates N full-adder stages and connects adjacent carries.Elaboration establishes that structure before the simulator runs it. With N=6, six stages exist; the loop does not perform one addition bit per clock. VHDL calls the configuration value a generic and uses a generate statement for repetition. A clocked algorithm needs explicit state or registers to sequence work over time.
- 8ChallengeFind the connection error
A parent connects the outputs of two different module instances to one wire. One drives 0 and the other drives 1 with equal strength. What does simulation report, and what connection rule prevents this error?
---reveal---
The conflicting wire drivers resolve to
x. Give each signal one driver in these designs and combine intended alternatives through selection logic. If both drivers happened to agree, the wire could look known; that would not establish clear ownership of the connection. - 9ExampleCompare bitwise and logical results
Let
a=4'b1010andb=4'b1001. Bitwise AND compares corresponding positions and produces1000. Logical AND treats each entire nonzero vector as true and produces the single bit 1.Unary reduction XOR,
^a, also produces one bit: 0 here because a contains two set bits. The position and number of operands distinguish binary bitwise XOR from unary reduction XOR even though both use the^symbol. - 10ExampleKeep the fifth bit of a sum
Two four-bit operands hold 10 and 9. Their true sum is 19, or
1_0011. A four-bit destination retains only0011, decimal 3.A five-bit destination keeps the carry:
assign total = {1'b0,a} + {1'b0,b};Here
totalis five bits. The explicit leading zeros make the intended unsigned widths visible before addition. For a signed operand, use sign extension instead of inserting a zero that would change a negative value. - 11ConnectionMatch the VHDL arithmetic width
For VHDL
unsignedoperands, a wider destination alone does not supply an extra arithmetic result bit.numeric_stdaddition returns the longer operand width.With four-bit
aandb, usetotal <= resize(a,5) + resize(b,5);for five-bittotal. Widening before addition preserves the carry. Resizing the four-bit result afterward only adds a leading zero to a value that has already lost its overflow. - 12ChallengeCheck the interface as well as the expression
A six-stage ripple adder has a six-bit
sumand a separatecout. A parent wants every result bit but connects onlysumto a seven-bit wire. Is the full result preserved?---reveal---
No. Extending the six-bit sum cannot recover the carry that leaves through
cout. Connect the carry as the high bit and the sum as the low six bits. The generated stage count establishes the hardware width, while the top-level connection must preserve the complete result. - 13RecapCheck each connection in three ways
Read the description as hardware: separate blocks operate concurrently and each instance is a distinct copy. Parameters and generate constructs establish a configured structure at elaboration.
For every connection, ask who drives it, which operation produces it, and how wide it must be. Those questions expose conflicting drivers, wrong operator families, and discarded carry before a passing simulation encourages confidence in the wrong circuit.
2Write combinational decisions without hidden memory
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake every current input determine an output
- 2ExplanationGive requests an explicit priority
- 3ExampleUse a default and one override
- 4ChallengeWould two true tests both matter?
- 5ExplanationLook for an unassigned path
- 6ExampleAudit every output through a case
- 7TipCheck event coverage separately
- 8ChallengeFix both problems
- 9ChallengeCompute a temporary without adding a cycle
- 10RecapTrace triggers and values separately
3Trace registers and sequence detection
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate a cycle from its ending edge
- 2ExplanationChoose what can cause reset
- 3ExampleHold a count when enable is low
- 4ExamplePlace the incoming shift bit
- 5ChallengePredict reset and enable together
- 6ExampleSample both sides before swapping
- 7ExampleMove a sample through two stages
- 8ConnectionUse a temporary when immediate reuse is intended
- 9ChallengeRead a delayed dependency
- 10ExplanationStore how much of the sequence is useful
- 11ExampleTrace a new input stream
- 12Key InsightSeparate output dependency from encoding
- 13ChallengeKeep an overlapping match
- 14TipComplete the combinational FSM paths
- 15ChallengeWould registering the detection change observation time?
- 16RecapTrace storage before interpreting outputs
4Build a test that can catch a real failure
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the expected behavior observable
- 2ExplanationLet the current time settle
- 3ExampleUse the logic operation to interpret x
- 4ChallengeFind a clock that never starts
- 5ExampleSize an exhaustive adder test
- 6ExampleCompare the complete result
- 7Key InsightDo not copy the implementation into its checker
- 8ChallengeCatch a hidden unknown result
- 9ExplanationDrive at one edge and sample after the other
- 10ExampleCheck a counter after every enabled edge
- 11TipMake condition waits identify the new operation
- 12ChallengeTest a hold bug that reset hides
- 13ChallengeSeparate a functional pass from a timing claim
- 14RecapA checker needs three independent choices
5Read register transfers and ASM timing
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionUse a specification with visible time boundaries
- 2ExplanationRead the destination and condition
- 3ExampleCalculate both new registers from the old pair
- 4ExampleDistinguish a logical shift from a circular shift
- 5ChallengeRecognize one-edge exchange hardware
- 6ExplanationKeep the three box meanings distinct
- 7ExampleFollow a counter through its last state cycle
- 8Key InsightA box below an operation does not read an updated register
- 9ConnectionTranslate the chart in two parts
- 10ChallengeChange the stopping test
- 11RecapUse the edge as the boundary
6Build and verify a sequential multiplier
19 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionReuse one adder across an algorithm
- 2ExplanationAssign data and decisions to their owners
- 3ExampleDerive a control from an operation’s chart position
- 4ExampleCollect paths entering a one-hot state
- 5ChallengeName the right interface signal
- 6ExplanationChoose storage that preserves the whole calculation
- 7ExampleLoad 9 times 6
- 8ExampleProcess the first zero multiplier bit
- 9ExampleAdd and shift the second bit
- 10ExampleAdd and shift the third bit
- 11ExampleComplete the last shift
- 12ChallengePreserve an overflowing addition
- 13Key InsightCounter zero selects exit without canceling work
- 14ExampleGive every control a combinational default
- 15ExampleWrite the nine-bit shift from old fields
- 16TipObserve the transaction that actually started
- 17ExampleCheck results and cycle counts independently
- 18ChallengeFind the first broken operation
- 19RecapVerify the interface and the algorithm together
HDL and RTL Design practice questions
Set 1: Modules, connections, and combinational logic10 Practice Questions
Question 1 of 10
p. What changes if their lines are swapped?Show answerHide answer
Question 2 of 10
wire [10:3] bus;?Show answerHide answer
Question 3 of 10
data and output valid. Its instance contains .data(sample). What does this connect?Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
4'b0101 & 4'b0011?Show answerHide answer
Question 6 of 10
v holds 8'b1110_1100. What bit pattern does v >>> 2 produce?Show answerHide answer
Question 7 of 10
a and b are four-bit unsigned signals holding 14 and 5. s is five-bit unsigned. The code uses s <= resize(a+b,5);. What edit preserves the true sum?Show answerHide answer
Question 8 of 10
r=6'b101100, which request index does it report?Show answerHide answer
Question 9 of 10
y=0;, then executes if (a) y=2; and if (b) y=3;. What is y when a=b=1?Show answerHide answer
Question 10 of 10
y=0; and has case(sel) branches only for 00 and 01. Each branch assigns y. What happens when sel=10?Show answerHide answer
Set 2: Register timing and state-machine behavior10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
always @(*) if (enable) flag=data;, what hardware is needed to preserve flag while enable is low?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
always @(u) y=u^v;. Only v changes, and y stays unchanged. What edit makes the simulation respond as the synthesized XOR does?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
posedge rst in its event control?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
10110. At the next edge, load=shift=1, d=10001, and sin=1. Its code tests load before else if (shift). What is q after the edge?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
p<=q; q<=p+1;. What are p and q after the edge?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
p<=p+1; q<=p; r<=q;. What are p, q, r after two edges?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
1,0,1,1,0,1,0. How many detection cycles occur, and what useful prefix remains after the last edge?Show answerHide answer
Save this lesson to see this answer.
Set 3: Events, independent checks, and clocked tests10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
always #4 clk=~clk; with a 1 ns time unit. What is its full period?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
q<=1 at a rising edge. A testbench reads q immediately on that same edge, before nonblocking updates. Why can it observe the old q?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
w & 1'b0 and w | 1'b0?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
011 for a=110, b=101, cin=0. Its checker zero-extends its own 3-bit addition and reports a pass. What change correctly checks the full result?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
4'b0x10, while expected is 4'b0010. Which testbench condition definitely enters the failure branch?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
wait(ready);, then checks the result. Why can it check an old transaction?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
1,1,0,1,0,1, with reset low. A faulty implementation clears when disabled instead of holding. On which edge does it first differ from the specification, and what should the final count be?Show answerHide answer
Save this lesson to see this answer.
Set 4: Simultaneous transfers and controller design10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
A ← B+C, B ← A, C ← A−B. What values do they hold afterward?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
A ← A−B, B ← A. What are A and B afterward?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
R7 ← R4 executes?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
last=(A==5). The controller increments A throughout RUN and exits RUN when last=1. RUN begins at A=1. How many RUN cycles occur, and what A enters DONE?Show answerHide answer
Save this lesson to see this answer.
Set 5: Multiplier traces, interfaces, and fault diagnosis10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
1001, C=0, A=0111, Q=0101, P=3. What are C, A, Q, P after ADD and the following SHIFT?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
1010, C=0, A=0110, Q=1100, P=2. What are A, Q, P after this ADD/SHIFT pair?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
1011, Q=0111, A=0, C=0, P=4. What are C, A, Q, P immediately before its third ADD state?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
1100 and C/A/Q/P=0/0110/1101/2. After ADD it shows 1/0010/1101/1; after SHIFT it shows 0/0001/0110/1. Which transfer first fails, and what should the post-SHIFT tuple be?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
t receives a+b, then signal q receives t. What does q receive at that edge?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Arithmetic logic unit
Arithmetic right shift
ASM block
ASMD chart
Asynchronous reset
B
Behavioral description
Binary state encoding
Bitwise operator
1010 and 0110 produced 0010, keeping only their shared set position."Blocking assignment
C
Carry register
Case inequality
!== comparison, which treats unknown and high-impedance bits literally and returns a definite mismatch result.Case statement
Circular shift
1001 into 1100, preserving the outgoing low bit at the high end."Clock period
Combinational loop
Concatenation
Conditional output box
Continuous assignment
Control signal
Controller
D
D flip-flop
Datapath
Decision box
Default assignment
Delta cycle
Design under test
Directed test
E
Elaboration
Entity and architecture
Event-driven simulation
Exhaustive test
F
Finite state machine
G
Gray state encoding
H
Hardware description language
Hardware sharing
High impedance
z in Verilog.I
Inferred latch
Instance
L
Latency
Load enable
Logical operator
M
Mealy output
Micro-operation
Module
Modulus
Moore output
Multiple drivers
N
Named port connection
.sum(result) connects the child’s sum port to the parent’s result signal."Net
wire.Next-state logic
Nonblocking assignment
O
One-hot encoding
P
Parameter and generic
Partial product
Priority chain
Process variable
:= takes effect immediately within that process’s execution.R
Race condition
Reduction operator
Reference model
Register pipeline
Register transfer notation
R2 ← R1 specified a copy into R2 at the next active edge without clearing R1."Regression test
Reset sequence
Ripple-carry adder
S
Sensitivity list
Shift register
Shift-and-add multiplication
Sign extension
Simulation
Simultaneous transfer
State box
Status signal
Structural description
Synchronous reset
Synthesis
Synthesis report
T
Testbench
Time precision
Timeout
Top-level module
Transaction
Transition coverage
Truncation
U
Unknown value
x in Verilog.V
Vector
W
Waveform
Z
Zero detector
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.