Analog and Digital Electronics

Chapter 10
Hardware Description Languages and Programmable Logic

Bachelor Program in Mechatronics Engineering
Analog and Digital Electronics   •   Bachelor

Hardware Description Languages and Programmable Logic

Introduction and Context

Digital systems were once constructed primarily from discrete logic gates and fixed-function integrated circuits. Modern mechatronic products—motor controllers, robotic interfaces, industrial communication units, imaging systems, and safety controllers—often require hardware that is fast, parallel, configurable, and capable of deterministic response. Hardware description languages (HDLs) and programmable logic devices provide this capability.

An HDL is not merely a programming language for instructing a processor. It describes the structure and behaviour of digital hardware so that software tools can simulate it, synthesize it into logic, place and route it in a device, and verify its operation. The designer must therefore understand both the intended algorithm and the physical consequences of the description: flip-flop count, combinational depth, routing delay, clock-domain crossings, reset behaviour, and input/output timing.

Field-programmable gate arrays (FPGAs) and complex programmable logic devices (CPLDs) implement HDL descriptions using configurable logic resources. Their flexibility makes them valuable in prototyping and production, but successful design requires disciplined modelling and verification.

Learning Objectives

After studying this chapter, a student should be able to:

  1. Explain the relationship between HDL descriptions, simulation, synthesis, implementation, and hardware verification.
  2. Distinguish combinational, sequential, structural, and behavioural HDL models.
  3. Write synthesizable SystemVerilog-style descriptions of datapaths and finite-state machines.
  4. Analyze clock frequency, setup time, hold time, latency, throughput, and resource use.
  5. Design and verify a small FPGA-based control system.
  6. Identify common HDL errors, including inferred latches, multiple drivers, unsafe clock-domain crossings, and simulation–synthesis mismatches.
  7. Apply timing-closure, testability, reliability, and responsible-design practices.

1. HDL as a Hardware-Modelling Discipline

1.1 Description rather than instruction

A software statement normally specifies a sequence of operations executed by a processor. An HDL statement may instead specify gates, registers, multiplexers, and their concurrent relationships. For example, the assignment

assign y = (a & b) | c;

describes combinational logic. Whenever a, b, or c changes, the hardware output y changes after the physical propagation delay. It does not describe a subroutine that runs once.

A clocked process describes storage elements. In synthesizable SystemVerilog:

always_ff @(posedge clk) begin
  if (reset)
    q <= 1'b0;
  else
    q <= d;
end

This convention describes a bank of flip-flops whose output changes on the active clock edge. The nonblocking assignment <= models simultaneous state update and is the appropriate form for clocked sequential logic.

1.2 Main stages of an HDL design flow

A professional flow normally contains the following stages:

  1. Specification: Define interfaces, clock assumptions, functionality, performance, safety, and verification criteria.
  2. Architecture: Partition the design into datapath, control, memories, interfaces, and clock/reset structures.
  3. RTL coding: Write register-transfer-level (RTL) descriptions showing how data moves between registers and how combinational functions are calculated.
  4. Functional simulation: Apply testbench stimuli and compare outputs with expected results.
  5. Synthesis: Convert synthesizable HDL into a technology-independent logic network, then map it to FPGA or CPLD primitives.
  6. Implementation: Place logic resources and route connections on the target device.
  7. Timing analysis: Verify that all relevant timing constraints are satisfied.
  8. Programming and hardware test: Configure the device and test with instruments, embedded logic analyzers, or external test equipment.

Simulation validates the model under tested conditions; synthesis creates hardware; timing analysis evaluates whether the hardware can operate at the required speed. None of these stages alone proves complete correctness.

1.3 Design abstraction levels

LevelMain concernTypical use
BehaviouralWhat the system doesAlgorithm modelling and testbenches
RTLData transfers on clock edgesSynthesizable digital design
StructuralExplicit module and gate interconnectionReusable architectures and netlists
PhysicalPlacement, routing, pins, delaysImplementation and timing closure

A good design moves deliberately between levels. High-level behavioural code may be easy to write but may synthesize into excessive hardware. RTL exposes enough structure to reason about clocks, registers, latency, and resource consumption.

2. Synthesizable HDL Constructs

2.1 Combinational logic

Combinational output depends only on current inputs. A complete combinational process assigns every output on every execution:

always_comb begin
  y = 1'b0;
  if (sel)
    y = a;
  else
    y = b;
end

The default assignment prevents an unintended latch. A latch is inferred when a signal must retain its previous value because some path through a combinational process does not assign it. Latches are sometimes intentional, but accidental latches complicate timing and are usually a design error in synchronous FPGA systems.

A combinational arithmetic expression must also account for width and signedness. If two unsigned 8-bit values are added, the mathematical result may require 9 bits. In general, for unsigned operands with widths n and m, the sum may require up to max(n,m)+1 bits. Truncating the result can silently discard a carry.

2.2 Sequential logic

Sequential logic stores state. A synchronous register updates only at a clock edge. A synchronous reset is sampled at that edge, whereas an asynchronous reset can affect the register independently of the clock. Both approaches are used in industry; the choice must be consistent with the FPGA technology, reset distribution, safety requirements, and verification strategy.

A basic synchronous design can be represented as:

statek+1 = F(statek, inputk)

Here state_k is the register state immediately after clock edge k, input_k is the sampled input information, and F is the next-state function. Outputs may be defined as:

outputk = G(statek, inputk)

If outputs depend only on state, the machine is Moore-type. If they depend on state and current inputs, it is Mealy-type. Moore outputs often simplify timing and avoid input glitches, while Mealy machines can reduce latency but require careful output qualification.

2.3 Blocking and nonblocking assignments

Blocking assignment = updates immediately within procedural execution and is commonly used for temporary calculations in combinational blocks. Nonblocking assignment <= schedules updates for the end of the current simulation time step and is normally used in clocked blocks. Mixing the two without a clear reason can create simulation behaviour that does not represent the intended hardware.

2.4 Parameters, packages, and modularity

Reusable modules should expose parameters for widths, address ranges, and operating modes rather than duplicating source code. Interfaces should document signal direction, active level, clock domain, reset assumptions, and valid-data conditions. Clear module boundaries support independent simulation, synthesis reuse, and formal or assertion-based verification.

3. FPGA and CPLD Architecture

An FPGA commonly contains configurable logic blocks, programmable routing, input/output cells, block RAM, clock-management resources, and sometimes DSP multipliers, processors, and high-speed transceivers. A logic block often combines a lookup table (LUT) with one or more flip-flops. A LUT implements a Boolean function by storing its truth-table values; it is not limited to a single elementary gate.

CPLDs generally use larger, predictable programmable macrocells and nonvolatile configuration technologies. They are useful for glue logic, simple controllers, boot interfaces, and applications requiring rapid startup. FPGAs provide substantially greater capacity and specialized resources for datapaths, parallel processing, and embedded systems.

CharacteristicFPGACPLD
Typical capacityMedium to very largeSmall to medium
Logic organizationLUTs and programmable routingMacrocells and product terms
Memory/DSP resourcesCommonLimited
ConfigurationOften volatile external or internal memoryFrequently nonvolatile
Best useParallel datapaths, controllers, signal processingGlue logic, compact control, predictable small designs

HDL source does not map identically to every device. An inferred multiplier may use dedicated DSP blocks in one FPGA and general logic in another. Therefore, synthesis reports and implementation reports must be examined rather than assuming that concise HDL always produces efficient hardware.

4. Finite-State Machine Design

A finite-state machine (FSM) comprises a finite set of states, state registers, next-state logic, and output logic. A systematic design method is:

  1. Define states in terms of externally observable system conditions.
  2. Specify inputs, outputs, reset state, and legal transitions.
  3. Draw a state diagram or write a transition table.
  4. Encode the states.
  5. Implement state storage, next-state logic, and output logic separately or in a carefully structured combined process.
  6. Specify recovery behaviour for illegal states.
  7. Verify every transition, including reset and timeout paths.

For N states, binary encoding needs at least:

w = ⌈log₂(N)⌉

state bits, where w is an integer and unused encodings may exist. One-hot encoding uses approximately one flip-flop per state and can simplify next-state logic, especially in FPGAs. Gray encoding changes one state bit between adjacent states and may reduce transitions in selected applications. The best encoding depends on speed, area, power, safety, and tool behaviour.

A robust SystemVerilog pattern is:

typedef enum logic [1:0] {IDLE, LOAD, RUN, DONE} state_t;
state_t state, next_state;

always_ff @(posedge clk) begin
  if (reset)
    state <= IDLE;
  else
    state <= next_state;
end

always_comb begin
  next_state = IDLE;
  case (state)
    IDLE: if (start) next_state = LOAD;
    LOAD: next_state = RUN;
    RUN:  if (finished) next_state = DONE;
    DONE: next_state = IDLE;
    default: next_state = IDLE;
  endcase
end

The default transition provides a recovery path. In safety-critical systems, illegal-state recovery should be analyzed explicitly rather than treated as a substitute for fault detection.

5. Datapaths and Control

A datapath performs operations on data; control logic determines when those operations occur. Typical datapath elements include registers, adders, subtractors, comparators, multiplexers, counters, shifters, memories, and DSP blocks.

Suppose a controller must acquire eight samples, accumulate them, and assert done. The datapath requires a sample register, an accumulator, and a counter. The controller sequences IDLE, ACCUMULATE, and DONE. If the accumulator has width W and each unsigned sample has maximum value X_max, the maximum sum is:

Smax = 8 × Xmax

The number of bits required is the smallest integer B satisfying:

2B > Smax

For 8-bit samples, X_max = 255, so S_max = 2040; since 2^10 = 1024 and 2^11 = 2048, an 11-bit accumulator is required to represent every possible sum. This calculation assumes eight samples, unsigned values, and no saturation. A signed datapath requires a separate two's-complement range analysis.

Pipelining inserts registers between combinational stages. It usually increases latency but can increase maximum clock frequency because each stage has less logic delay. If a path contains combinational delay t_comb, clock-to-output delay t_cq, setup time t_setup, and clock uncertainty t_skew, a simplified setup constraint is:

tcq + tcomb + tsetup + tskew ≤ Tclk

where T_clk is the clock period. The corresponding approximate maximum frequency is:

fmax ≈ 1 ÷ Tmin

These relationships are simplified; actual static timing analysis also considers routing, clock insertion, uncertainty, generated clocks, and device-specific timing models.

6. Timing, Clocks, and Clock-Domain Crossing

6.1 Setup and hold

A receiving flip-flop requires its input to be stable for a setup interval before the active clock edge and a hold interval after it. Violating either condition can cause metastability, in which the output temporarily takes an unpredictable analogue value before resolving to a logic level. Metastability cannot be eliminated entirely in an asynchronous interface, but its probability can be reduced.

A common single-bit synchronizer uses two flip-flops in the receiving clock domain:

always_ff @(posedge clk_b) begin
  sync1 <= async_signal;
  sync2 <= sync1;
end

The first stage may become metastable; the second stage provides additional resolution time. This technique is not sufficient for multi-bit buses, where independent bit synchronization can produce incoherent words. Multi-bit transfers require a handshake, asynchronous FIFO, Gray-coded pointer method, or another protocol designed for clock-domain crossing.

6.2 Timing constraints

The timing tool must know clock frequency, input arrival time, output required time, false paths, and multicycle paths where justified. A false-path constraint must be based on a genuine functional impossibility, not used to hide a failing path. A multicycle constraint changes the permitted timing relationship and requires corresponding design and verification evidence.

Timing closure is an iterative engineering activity. Remedies include reducing combinational depth, adding pipeline registers, improving placement, using dedicated carry/DSP/RAM resources, reducing fan-out, changing state encoding, and revising the clock architecture. Raising the target clock frequency without architectural changes is rarely a reliable solution.

7. Verification and Testability

Verification should begin with the specification, not after coding. A useful verification plan identifies requirements, interfaces, legal and illegal conditions, corner cases, coverage goals, and the evidence needed for acceptance.

A testbench provides clocks, resets, transactions, and expected-result checking. A self-checking testbench is superior to visual waveform inspection because it can report failures automatically. Assertions can express properties such as “a request must eventually receive an acknowledgment” or “a counter never exceeds its configured maximum.” Constrained-random stimuli explore combinations that directed tests may miss, while functional coverage indicates which behaviours have been exercised.

Simulation models may contain constructs that cannot synthesize, such as arbitrary delays, file operations, and testbench-only classes. The design-under-test should be clearly separated from verification code. After synthesis, post-synthesis or post-place-and-route simulation can reveal initialization, reset, and delay effects not visible in ideal RTL simulation.

Hardware testability benefits from:

  • accessible reset and clock diagnostics;
  • internal status registers;
  • loopback modes;
  • built-in self-test where justified;
  • boundary-scan or JTAG access;
  • on-chip logic analyzers;
  • error detection such as parity, CRC, watchdog timers, or range checks.

Observability and controllability are central principles: faults are easier to diagnose when internal states can be stimulated and observed without disturbing normal operation.

8. Worked Example: A Timed Motor-Enable Controller

Consider a small FPGA controller for a motor drive. Inputs are start, fault, and speed_ok; outputs are enable and alarm. After reset, the motor is disabled. A valid start request causes a two-cycle qualification interval. If fault occurs at any time, the motor is disabled and the alarm is asserted until reset.

Specification analysis

The states are:

  • SAFE: motor disabled, no alarm;
  • QUALIFY: waiting for two valid clock cycles;
  • RUN: motor enabled;
  • FAULT: motor disabled and alarm asserted.

The transition rules are:

  • SAFE → QUALIFY when start is asserted;
  • QUALIFY → RUN after two cycles with speed_ok = 1 and no fault;
  • any non-fault state → FAULT when fault = 1;
  • RUN → SAFE when start = 0;
  • FAULT remains until reset.

The qualification counter needs to represent values 0, 1, and 2. Two bits are sufficient because 2² = 4, although the design must prevent values 3 from being interpreted as a valid count. The counter is reset when leaving QUALIFY.

A simplified implementation separates state and counter registers from next-state logic. The output enable is asserted only in RUN; consequently, a fault causes it to deassert after the state register updates on the next active edge. If immediate fault shutdown is required by the motor-safety analysis, a separately justified hardware interlock—not merely an HDL state transition—may be necessary.

Verification strategy

Directed tests should cover reset, a valid start, loss of speed_ok, a fault in each state, start release, repeated start pulses, and reset recovery. Assertions can check that enable is never high in SAFE, QUALIFY, or FAULT, and that FAULT is absorbing until reset. Timing analysis must verify the clock constraint and input synchronization. If fault originates outside the FPGA clock domain, it must be synchronized or connected to an independently analyzed emergency shutdown path.

Engineering outcome

This architecture separates safety-relevant control from datapath timing, makes state behaviour reviewable, and permits resource reports to be interpreted. A practical implementation would also specify the electrical interface, fault polarity, watchdog behaviour, power-up state, and evidence required before deployment.

9. Limitations, Professional Practice, and Contemporary Developments

HDLs can hide physical complexity. Two descriptions with identical simulation results may differ greatly in area, power, timing, and susceptibility to routing congestion. Vendor-specific primitives can improve performance but reduce portability. Aggressive optimization can make debugging difficult, and an apparently harmless change in reset or arithmetic width can alter resource use substantially.

Best practice includes:

  1. Use a single, clearly defined clock for each synchronous domain where possible.
  2. Synchronize asynchronous inputs and document every clock-domain crossing.
  3. Use explicit widths, signedness, saturation, and overflow behaviour.
  4. Avoid inferred latches and unintended combinational feedback.
  5. Keep reset strategy consistent and verify power-up behaviour.
  6. Treat timing constraints as part of the design, not as an afterthought.
  7. Review synthesis and implementation reports for inferred RAMs, DSPs, registers, warnings, and critical paths.
  8. Use version control, coding standards, peer review, regression simulation, and reproducible tool settings.
  9. Protect configuration images and debug interfaces against unauthorized modification.
  10. Preserve traceability between requirements, HDL, tests, and verification results.

Contemporary FPGA development increasingly uses high-level synthesis, model-based design, embedded processors, machine-learning accelerators, and partial reconfiguration. These tools can improve productivity but do not remove the need to understand latency, numerical precision, memory bandwidth, concurrency, and timing. AI-assisted code generation may suggest HDL, but generated code must undergo the same simulation, linting, synthesis, security review, and hardware verification as human-written code. Safety-critical or regulated products require documented evidence, controlled tool qualification where applicable, and compliance with the relevant sector standards.

Chapter Summary

HDLs provide executable descriptions of digital hardware at behavioural, RTL, structural, and physical abstraction levels. The design flow proceeds from specification and architecture through RTL coding, simulation, synthesis, implementation, timing analysis, programming, and hardware verification. FPGA and CPLD architectures offer configurable logic, but the same HDL can consume different resources on different devices.

Combinational logic must assign outputs completely, while clocked logic uses registers and carefully selected reset and assignment conventions. Datapaths and finite-state controllers should be designed together, with explicit attention to width, signedness, overflow, latency, and resource use. Setup and hold requirements, clock-domain crossings, synchronizers, and timing constraints determine whether a logically correct design will operate reliably in hardware.

Verification requires self-checking testbenches, assertions, coverage, corner-case analysis, and hardware observability. Timing closure and testability are architectural concerns. Professional practice also includes traceability, configuration security, disciplined version control, and critical evaluation of high-level and AI-assisted design tools.

Key Terms

Hardware description language: A language for modelling digital hardware structure and behaviour.

RTL: Register-transfer level; a description of data movement between clocked registers and combinational logic.

Synthesis: Transformation of synthesizable HDL into an implementation technology’s logic resources.

FPGA: Field-programmable gate array containing configurable logic, routing, and often memory and DSP resources.

CPLD: Complex programmable logic device based on programmable macrocells.

LUT: Lookup table used to implement Boolean functions in an FPGA.

Datapath: Hardware that stores, transforms, and transfers data.

Control path: Logic that sequences operations and generates control signals.

Finite-state machine: Sequential model consisting of states, transitions, state registers, and outputs.

Combinational logic: Logic whose outputs depend only on current inputs.

Sequential logic: Logic containing storage whose outputs depend on previous state.

Latch: Storage element inferred when combinational assignments are incomplete.

Setup time: Required interval for which data is stable before a clock edge.

Hold time: Required interval for which data remains stable after a clock edge.

Metastability: Temporary uncertain state caused by violating a storage element’s timing requirements.

Clock-domain crossing: Transfer of information between unrelated or differently timed clocks.

Timing closure: Achieving all specified implementation timing requirements.

Testbench: HDL verification environment that stimulates and checks a design.

Synthesis report: Tool-generated record of inferred resources, warnings, and mapped logic.

Review Questions

Short Answer Questions

  1. Why is an HDL description different from a conventional software program?
  2. What is the purpose of a default assignment in a combinational process?
  3. Distinguish a datapath from a control path.
  4. Why is a two-flip-flop synchronizer used for a single-bit asynchronous input?
  5. What information is provided by static timing analysis?

Long Answer Questions

  1. Explain the complete HDL-to-FPGA design flow and identify the evidence produced at each major stage.
  2. Compare FPGA and CPLD architectures and recommend an appropriate class of device for two contrasting applications.
  3. Describe binary, one-hot, and Gray state encoding, including their advantages and limitations.
  4. Explain how pipelining affects latency, throughput, resource use, and maximum clock frequency.
  5. Develop a verification plan for a controller that communicates across two unrelated clock domains.

Analytical / Application Questions

  1. An accumulator must sum eight unsigned 10-bit samples. Determine the minimum accumulator width and explain the assumptions behind your result.
  2. A critical path has t_cq = 0.8 ns, t_comb = 6.2 ns, t_setup = 1.0 ns, and clock uncertainty of 0.5 ns. Determine the minimum clock period using the simplified setup relationship and calculate the corresponding approximate maximum frequency.
  3. Design the states, transitions, reset behaviour, and verification cases for an FPGA controller that enables a conveyor motor only after three consecutive sensor-valid cycles and permanently enters a fault state when an emergency input is asserted.

Multiple Choice Questions with Answers

Question 1

Which HDL construct most directly describes a bank of flip-flops updated on a rising clock edge?

A. always_ff with a posedge event

B. assign statement only

C. always_comb without storage

D. A synthesis constraint file

Correct Answer: A. always_ff with a posedge event

Question 2

What is the principal purpose of a default assignment in a combinational process?

A. To increase clock frequency

B. To prevent unintended latch inference

C. To create a second clock

D. To force one-hot encoding

Correct Answer: B. To prevent unintended latch inference

Question 3

Which device is generally most suitable for a large parallel datapath containing block RAM and DSP operations?

A. A relay board

B. A small CPLD

C. An FPGA

D. An isolated analog amplifier

Correct Answer: C. An FPGA

Question 4

For eight unsigned 8-bit samples, what is the minimum accumulator width needed to represent every possible sum?

A. 8 bits

B. 9 bits

C. 10 bits

D. 11 bits

Correct Answer: D. 11 bits

Question 5

What is the main limitation of independently synchronizing each bit of a multi-bit asynchronous bus?

A. The bus may be captured as an incoherent word

B. It always increases arithmetic precision

C. It eliminates all metastability

D. It converts the bus into analog data

Correct Answer: A. The bus may be captured as an incoherent word

Question 6

Which assignment is normally preferred for state updates in a clocked SystemVerilog process?

A. Blocking assignment

B. Nonblocking assignment

C. Continuous assignment only

D. A timing-delay assignment

Correct Answer: B. Nonblocking assignment

Question 7

If a simplified critical path requires 10 ns of clock period, what is its approximate maximum frequency?

A. 10 MHz

B. 50 MHz

C. 100 MHz

D. 1 GHz

Correct Answer: C. 100 MHz

Question 8

Which verification feature automatically compares actual outputs with expected behaviour?

A. A self-checking testbench

B. A pin constraint alone

C. A device package

D. A passive heat sink

Correct Answer: A. A self-checking testbench

Question 9

What is the usual effect of inserting pipeline registers into a long combinational path?

A. Lower latency and zero area cost

B. Higher possible clock frequency but additional latency

C. Removal of all clock-domain crossings

D. Guaranteed reduction in flip-flop count

Correct Answer: B. Higher possible clock frequency but additional latency

Question 10

A false-path timing constraint should be used when:

A. A path fails timing and the designer wants to hide the failure

B. The path is functionally impossible under the documented architecture

C. The design has no clock

D. A signal is wider than one bit

Correct Answer: B. The path is functionally impossible under the documented architecture

Analog and Digital Electronics
Chapter 10 of 15