Sequential Logic Circuits

On this page

Similarly, when the input is 1, the sequence detector might be waiting for the first 1, or it might have just received 10 and is preparing to confirm 101. It must save information from history that is relevant to future decisions; this is state. The core of sequential logic is state retention; the clock is the method by which synchronous designs organize state changes, but not all sequential circuits require a clock.

Question to UnderstandEntry Point in This ArticleKey Distinction
When can data pass through storage elementsLatches and Flip-FlopsTransparent windows and sampling edges
Why errors can still occur even when slowed downSetup, Hold, and SkewLongest paths and shortest paths
How to remember input historyRegisters, Counters, FSMsState meaning and update conditions
How asynchronous inputs are integratedMetastability and CDCSignal level reliability and message integrity
How to enter a defined state upon power-upReset and StartupReset assertion and de-assertion timing

From Feedback Storage to D Flip-Flops

Cross-coupled gate circuits can form two stable states. Taking the active-high NOR-based SR latch as an example, the equations are and . When , it forces first; feedback then makes . After returns to 0, the feedback maintains this state.

SRNOR-based SR Latch Behavior
00Hold previous state
10Set, Q=1
01Reset, Q=0
11Both outputs become 0, losing complementarity; result is indeterminate upon simultaneous release

NAND-based latches typically use active-low inputs, and the forbidden combination is the opposite of the table above. Do not mix input polarities. Power-up does not naturally determine which state the feedback latch will settle into; if a system requires a defined initial value, an explicit initialization or reset mechanism should be used.

The D latch uses data D and enable E to avoid the SR forbidden combination during normal operation. With active-high enable, Q follows D after propagation delay while E=1, and holds the last latched value after E=0. This "transparency" is a feature, not a bug; however, if the connection allows data to propagate through multiple stages within the same transparent window, you must analyze latch-through and latch timing, rather than directly applying edge-triggered pipeline rules.

The positive-edge D flip-flop samples at the rising clock edge and updates Q after . During the rest of the time, it holds its state unless asynchronous set/clear controls are active. Devices also come in negative-edge variants; the clock symbol, inversion bubble, and truth table in the datasheet determine the specific behavior. TI: SN74HC74 Positive-Edge D Flip-Flop

−tsetup+tholdCLKDQtCQSampled value: 1Sampling is not instant magic: D must cover the sampling window, then Q updatesThe window illustrates setup/hold times; parameters should be checked against the specific device, supply voltage, and temperature. The width in the figure does not represent scale.

Setup time requires D to be stable before the sampling edge, and hold time requires it to remain stable after the edge. Violating these requirements means the result no longer has normal timing guarantees: it might capture an old value, a new value, or enter metastability. You cannot assert that metastability occurs every time a violation happens, nor can you define metastability as inevitable oscillation. It may manifest as the output failing to reach a valid logic level in time, or subsequent receiving elements making different judgments.

The JK flip-flop performs hold, set, reset, or toggle operations at the active edge based on J/K; it toggles when J=K=1. The T flip-flop update equation is , which can be implemented using a D flip-flop plus XOR logic. The "toggle once" behavior here depends on the specific triggering structure and timing; do not directly apply edge-triggered conclusions to arbitrary transparent feedback circuits.

Registers and Counters: Using Old State Every Cycle

n flip-flops sharing a clock form an n-bit register. A register with enable loads new data when en=1, otherwise it holds; implementing hold using a multiplexer is usually easier to constrain correctly than arbitrarily ANDing en with the clock. True clock gating requires glitch-free gating structures or device-specific resources.

A synchronous binary counter can be written as en ? Q+1 : Q, where the bit width determines the modulus. Synchronous means all bits are sampled by the same clock; it does not mean the physical changes of all Q outputs are absolutely simultaneous. A ripple counter uses the output of the previous stage to drive the clock of the next stage, introducing cumulative delay, which makes intermediate codes more visible during decoding.

BCD (Binary-Coded Decimal) uses four bits to encode decimal digits 0000–1001; a three-bit binary increment sequence is not BCD. A modulo-10 counter must also define the behavior for invalid states 1010–1111, for example, returning to 0000 in the next cycle. Gray code ensures that adjacent valid counts differ by only one bit, but it still requires proper registration, synchronization, and routing constraints; you cannot deduce absolute safety across domains solely from "only one bit changes."

Shift registers simultaneously sample old adjacent bits. Taking a 4-bit register with serial input at the right end as an example, . Inputting 1, 0, 1, 1 sequentially results in states 0001, 0010, 0101, 1011. Parallel output updates the entire register at once per cycle; it is not a cascading result of changing bits one by one in a software loop.

// Synchronous active-high reset; reset and en are both in the clk clock domain.
always_ff @(posedge clk) begin
    if (reset)
        q <= '0;
    else if (en)
        q <= {q[2:0], serial_in};
end

Non-blocking assignments describe calculating and updating registers based on old values at the edge. Here, serial_in must also meet the sampling requirements of this clock domain; using always_ff alone does not automatically synchronize asynchronous inputs.

Setup and Hold: One Limits the Upper Bound, One Limits the Lower Bound

Assume the sending clock edge arrives at 0, and the receiving clock edge arrives later by s; s>0 indicates the receiving clock is later. For a single-cycle, positive-edge-to-positive-edge path, ignoring separately listed jitter and uncertainty:

CheckSimplified ConstraintPhysical Meaning
SetupData sent in the old cycle must catch the next receiving edge
HoldNew data must not overwrite the current sampled value too early

The receiving clock arriving later provides more time for the setup check but makes hold harder to satisfy. Actual tools also distinguish between different edges, clock paths, and process corners, and account for corresponding uncertainties; you cannot replace worst-case analysis with a set of typical delays. MIT: Sequential Logic and Constraints

Taking the teaching example ns, ns, ns, ns, ns, the setup slack is ns. If the fastest path has ns, ns, and ns, the hold slack is ns, which still fails.

Increasing the period from 10 ns to 20 ns improves setup but does not change this same-edge hold constraint. Fixing hold usually involves shortest path delay, clock skew, and layout; blindly increasing all data path delays may break setup. Pipelining can shorten the longest combinational path per segment but increases the number of cycles for processing delay, and requires re-checking hold and control alignment for each segment.

Why does a slower clock not fix hold?

Defaults give +1.5 ns setup and −0.4 ns hold slack. Increasing period to 20 ns leaves the hold boundary unchanged. Adding data delay slows both earliest and latest arrivals, so both checks must be repeated.

Preparing the visual
Why does a slower clock not fix hold?

Setup checks the next capture edge; hold checks the current one. Longer periods move only the next edge; positive skew helps setup but hurts hold.

FSM: Explaining State Design with Sequence 101

A synchronous FSM is written as . Moore output is , and Mealy output is . The difference lies in the output dependencies, not in "one never has glitches, the other is always faster." If Moore uses multi-bit state combination decoding, different propagation delays of state bits can also produce glitches; registering the output can change this timing boundary.

Consider an overlapping 101 detector: S0 means no useful suffix currently, S1 means matched to 1, S2 means matched to 10. When S2 receives 1, it reports a hit and transitions back to S1, because the just-received 1 can also serve as the start of the next 101.

S0No MatchS1Ends with 1S2Ends with 101 / 00 / 01 / 1: Hit0 / 00 / 01 / 0Detecting overlapping sequence 101: State saves 'where we are in matching'Arrows are labeled "Input / Mealy Output"; inputs are synchronized to this clock domain first, and states update at the active clock edge.
Current StateInput 0: Next State / OutputInput 1: Next State / Output
S0S0 / 0S1 / 0
S1S2 / 0S1 / 0
S2S0 / 0S1 / 1

For input 10101, the third and fifth bits should both trigger a hit. If it goes directly back to S0 after a hit, the overlapping second match is lost. This is an example of how "what information the state saves" directly affects functionality. Mealy output can be raised via combinational delay when the current state is still S2 and the input is stable at 1; if the external interface requires a stable pulse for a full cycle, register this result at a clear sampling boundary and record the corresponding delay.

State encoding can be binary or one-hot. One-hot uses more flip-flops and may simplify some decoding, but power, speed, and area still need to be evaluated against the target device. The combinational next-state block must cover all branches; how to recover from invalid states should be explicit; recovery strategies cannot replace correct CDC or power integrity.

Metastability and Synchronizers: Increasing Recovery Time, Not Guaranteeing Deterministic Delay

Asynchronous inputs may fall into the sampling window relative to the target clock and cannot be eliminated by normal synchronous timing constraints. A synchronizer lets the first stage receive the signal first, giving it a recovery time, and then the subsequent stages sample it with the target clock; business logic only uses the output of the last stage. Combinational logic should not be inserted between stages, nor should it fan out to business receivers; layout and dedicated synchronization attributes also affect available recovery time.

Async LevelHolds long enoughFirst Stage DFFMay be metastableSecond DFFTo destination logicsync_outSame Target ClockNo combinational logic between stagesShort routing leaves time for recoveryTwo-stage synchronizer: Give the first stage more recovery time, business logic only uses the last stageReduces failure probability, does not guarantee zero risk; cannot directly guarantee short pulses are captured, nor does it automatically keep multi-bit data consistent.

Two stages are a common starting point; the actual number of stages required should be calculated based on device characteristics, target clock, input transition frequency, and reliability requirements. The typical model shows a trend of , but the constant and must come from device characterization; you cannot calculate a credible lifespan using an arbitrary . Failure rates for multiple cross-domain links also accumulate; the MTBF of a single link is not a guarantee for the entire system. Intel: Metastability and Synchronizer Analysis

The synchronized result may lag behind the asynchronous change by a different number of cycles. Synchronizers reduce the probability of metastability propagation but do not guarantee that every short pulse will be sampled: for example, if the target clock samples every 20 ns, a 5 ns pulse that falls completely between two sampling instants will disappear, even if the receiving flip-flop is not metastable.

Events can vanish without metastability

The default 5–10 ns pulse lies between edges, giving four zeros. Move it across 20 ns and a high is captured. Metastability is deliberately absent: even ideal samplers can miss short pulses, and more synchronization stages cannot recover them.

Preparing the visual
Events can vanish without metastability

A synchronizer cannot recover a pulse never sampled by its first stage; event preservation needs suitable encoding or handshake.

CDC: First Determine if Transferring Level, Event, or Data

Transferred ObjectCommon MethodConditions to Ensure
Single-bit state held for a long timeTarget domain sync chainLevel has enough visibility time, allowing sampling delay
Events that must be preserved every timeRequest/Ack, or toggle with rate constraintPrevious event not observed before overwrite; reset state consistent
A set of data that must be consistentHandshake fixed data, or Async FIFOData held until reception complete, throughput and backpressure defined
Monotonically adjacent changing pointersRegister Gray pointer then cross domainBit skew/max delay constraints, sync chain, correct full/empty detection

If multi-bit data bits are each flopped twice, you may get a mixed value that is neither the old word nor the new word. For example, when binary 0111 transitions to 1000, all four bits change, and the receiver might see any combination. In handshake schemes, the sender first stabilizes the data, then notifies the receiver; after the notification crosses domains, the receiver samples, and the sender holds the data until the acknowledgment returns, constraining the relative arrival time of control and data. Async FIFO separates data storage from read/write domain pointer management, suitable for continuous traffic.

Gray coding is not a universal multi-bit synchronization method: arbitrary pairs of Gray words can still differ by multiple bits. Only when the source advances by adjacent counting, the output is registered, and the cross-domain path constraints are correct, can the property of changing one bit at a time be utilized; the receiver might skip intermediate counts, so you cannot assume it sees only adjacent values every cycle.

Reset De-assertion Also Requires Timing

Synchronous reset takes effect at the active clock edge, requiring the clock to be working and the pulse to cover the sampling window. Asynchronous reset can take effect immediately without waiting for the clock, but if de-assertion is close to the active edge, it involves recovery/removal requirements. A common strategy is to assert reset asynchronously in each clock domain and de-assert synchronously, waiting for the clock to stabilize; specific devices also consider reset pulse width, power-on initialization, and dedicated resources. AMD: Synchronous vs. Asynchronous Reset

Different domains may leave reset at different times. Cross-domain handshakes and FIFOs must define which signals are valid during this time to avoid treating default bit changes as new events. Button synchronization is not equal to debouncing: synchronization handles sampling timing, while debouncing handles mechanical contact bouncing, usually requiring stable time counting or other filtering strategies.

Verify Behavior Using State Trajectories

The following checks sequence detection overlap, BCD invalid state recovery, Gray adjacency, and setup/hold examples. It is a discrete model check; it does not simulate analog metastability, nor does it replace HDL simulation, synthesis reports, static timing analysis, and CDC analysis.

from fractions import Fraction as F

state, hits = 0, []
for pos, bit in enumerate(map(int, '10101'), 1):
    hit = state == 2 and bit == 1
    if hit:
        hits.append(pos)
    state = ((0, 1), (2, 1), (0, 1))[state][bit]
assert hits == [3, 5]

for q in range(16):
    nxt = q+1 if q < 9 else 0
    assert 0 <= nxt <= 9
    assert nxt == ((q+1) % 10 if q <= 9 else 0)

gray = lambda n: n ^ (n >> 1)
for n in range(16):
    assert (gray(n) ^ gray((n+1) % 16)).bit_count() == 1

setup_slack = F(10)+F('0.5')-1-7-1
hold_slack = F('0.2')+F('0.1')-F('0.5')-F('0.2')
assert setup_slack == F('1.5') and hold_slack == F('-0.4')
assert F(20)+F('0.5')-1-7-1 > setup_slack
print('Overlap detection, BCD recovery, Gray adjacency, and setup/hold budget checks passed')

Continue Reading