Chuyển đến nội dung

Bài 18 · Sequential Logic

Counters and Shift Registers in Verilog

Design the workhorse sequential blocks in Verilog: binary, up/down, modulo and Gray counters, clock dividers, shift registers, ring and Johnson counters and LFSRs, with C models.

Counters and shift registers are the first real sequential circuits most designers build, and they show up everywhere: timers, address generators, clock dividers, serial communication, pseudo-random numbers. In this lesson you write each one in Verilog and check its behavior with a C model of the same logic.

A basic counter

VERILOG
module counter #(parameter W = 8) (
    input  wire         clk,
    input  wire         rst_n,
    input  wire         en,
    output reg  [W-1:0] count
);
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)      count <= {W{1'b0}};
        else if (en)     count <= count + 1'b1;
    end
endmodule

An W-bit counter wraps naturally: after 2^W - 1 comes 0, because the carry out of the top bit is dropped.

Up/down, load and modulo

VERILOG
always @(posedge clk or negedge rst_n) begin
    if (!rst_n)            count <= 0;
    else if (load)         count <= load_value;
    else if (en) begin
        if (up) count <= (count == MAX) ? 0 : count + 1'b1;     // modulo-(MAX+1)
        else    count <= (count == 0)   ? MAX : count - 1'b1;
    end
end

A modulo-N counter counts 0 to N-1 and wraps, with a terminal-count signal for dividers:

VERILOG
localparam N = 10;
wire tc = (count == N - 1);        // terminal count: one cycle per wrap
always @(posedge clk or negedge rst_n)
    if (!rst_n)  count <= 0;
    else         count <= tc ? 0 : count + 1'b1;

Note the priority: reset beats load, load beats count, and each if clause establishes that order.

Clock dividers and ticks

A counter that wraps every N cycles produces a one-cycle enable tick every N clocks. Prefer a tick (used as an enable) over generating a new divided clock: an extra clock needs special routing and complicates timing.

VERILOG
// 1 kHz tick from a 50 MHz clock: 50_000_000 / 1000 = 50_000 cycles
localparam DIV = 50_000;
reg [15:0] divcnt;
wire tick = (divcnt == DIV - 1);
always @(posedge clk or negedge rst_n)
    if (!rst_n) divcnt <= 0;
    else        divcnt <= tick ? 0 : divcnt + 1'b1;

always @(posedge clk)
    if (tick) led <= ~led;     // runs at the full clock but acts once per tick

$clog2(DIV) gives the width needed for the divider register.

Gray-code counters

A binary counter can change many bits at once (0111 to 1000 flips four). A Gray counter changes exactly one bit per step, which is essential when a count crosses between clock domains (for example FIFO pointers). Convert from binary with gray = bin ^ (bin >> 1).

VERILOG
wire [3:0] gray = bin ^ (bin >> 1);

Shift registers

A shift register moves data one position per clock:

VERILOG
module shift8 (
    input  wire       clk, rst_n, en, serial_in,
    output reg  [7:0] q
);
    always @(posedge clk or negedge rst_n)
        if (!rst_n)  q <= 8'd0;
        else if (en) q <= {q[6:0], serial_in};    // shift left, new bit enters at LSB
endmodule
  • SIPO (serial-in, parallel-out): collect incoming bits from a serial line.
  • PISO (parallel-in, serial-out): load a byte with load, then shift it out bit by bit.
  • A shift by one position is a concatenation with the new bit, not a loop.
VERILOG
// PISO: load a byte, then shift out MSB first
always @(posedge clk)
    if (load)        sh <= data;
    else if (en)     sh <= {sh[6:0], 1'b0};
assign serial_out = sh[7];

Ring and Johnson counters

A ring counter circulates a single 1 around a register (one-hot, no decoder needed). A Johnson (twisted-ring) counter feeds back the inverted last bit and has 2N states from N flip-flops.

VERILOG
// Johnson counter, 4 bits: 0000 0001 0011 0111 1111 1110 1100 1000 ...
always @(posedge clk or negedge rst_n)
    if (!rst_n) j <= 4'b0000;
    else        j <= {j[2:0], ~j[3]};

LFSR: pseudo-random numbers

A linear-feedback shift register shifts and feeds back an XOR of selected bits (taps). With good taps it cycles through every non-zero state (a maximal-length sequence): 15 states for 4 bits, with taps at bits 3 and 2.

VERILOG
reg [3:0] lfsr;
always @(posedge clk or negedge rst_n)
    if (!rst_n) lfsr <= 4'b0001;        // never all zeros
    else        lfsr <= {lfsr[2:0], lfsr[3] ^ lfsr[2]};

LFSRs generate test patterns, scramble data and compute CRCs.

Stand-in: counters and Gray code in C

This stand-in (not Verilog) models the modulo counter, the Gray conversion and the Johnson counter, and checks that Gray code changes one bit per step.

C Stand-in: modulo, Gray and Johnson counters (C)

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

Program input · what you'd type while the program runs

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

Stand-in: a 4-bit LFSR (C)

C Stand-in: maximal-length 4-bit LFSR (C)

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

Program input · what you'd type while the program runs

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

The period is 15 and every non-zero state appears exactly once. The all-zero state is a lock-up state, which is why the register must never be reset to 0.

Common mistakes

  • Forgetting a width bit: count + 1'b1 is fine, but comparing a 4-bit counter to 10 works only if the register is wide enough.
  • Generating a slow clock with a flip-flop output instead of an enable tick.
  • Shifting in the wrong direction (check which end is the MSB).
  • Starting an LFSR at all zeros.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does an 8-bit counter do after 8'hFF?

    The carry out is dropped, so the value wraps to zero.
  2. 2. Why use a Gray counter for values crossing clock domains?

    Single-bit changes avoid multi-bit inconsistencies when sampled asynchronously.
  3. 3. How many states does an N-bit Johnson counter have?

    The inverted feedback gives a sequence of 2N distinct states.
  4. 4. What is the best way to get a slow periodic event from a fast clock?

    A tick keeps everything on one clock, which simplifies timing and synthesis.

Summary

  • Counters are registers plus an incrementer; they wrap naturally, and modulo counters compare against a terminal count.
  • Use enable ticks, not derived clocks, for slow events.
  • Gray codes change one bit per step; shift registers move data with {q[N-2:0], in}.
  • Ring, Johnson counters and LFSRs are shift registers with specific feedback.

Next: Registers, Enables and Simple Memories

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.