0
0
Verilogprogramming~5 mins

Register (multi-bit flip-flop) in Verilog

Choose your learning style9 modes available
Introduction

A register stores multiple bits of data at once. It remembers the data until you change it.

To hold a number temporarily in a digital circuit.
To save the state of a system between clock pulses.
To build memory inside a chip.
To pass data between parts of a circuit in steps.
To create counters or shift data in hardware.
Syntax
Verilog
module register #(parameter WIDTH = 8) (
  input wire clk,
  input wire reset,
  input wire [WIDTH-1:0] d,
  output reg [WIDTH-1:0] q
);

  always @(posedge clk or posedge reset) begin
    if (reset)
      q <= {WIDTH{1'b0}};
    else
      q <= d;
  end

endmodule

WIDTH sets how many bits the register holds.

The always block updates the register on the clock's rising edge or resets it.

Examples
A 4-bit register that resets to 0 and stores 4-bit input data.
Verilog
module reg4bit (
  input wire clk,
  input wire reset,
  input wire [3:0] d,
  output reg [3:0] q
);

  always @(posedge clk or posedge reset) begin
    if (reset)
      q <= 4'b0000;
    else
      q <= d;
  end

endmodule
A 16-bit register example with hexadecimal reset value.
Verilog
module reg16bit (
  input wire clk,
  input wire reset,
  input wire [15:0] d,
  output reg [15:0] q
);

  always @(posedge clk or posedge reset) begin
    if (reset)
      q <= 16'h0000;
    else
      q <= d;
  end

endmodule
Sample Program

This testbench creates an 8-bit register. It resets the register, then changes input data every 10 time units. The output shows how the register stores the data on each clock pulse.

Verilog
module test_register;
  reg clk = 0;
  reg reset;
  reg [7:0] d;
  wire [7:0] q;

  // Instantiate the 8-bit register
  register #(8) myreg (
    .clk(clk),
    .reset(reset),
    .d(d),
    .q(q)
  );

  // Clock generation
  always #5 clk = ~clk;

  initial begin
    $monitor($time, " clk=%b reset=%b d=%b q=%b", clk, reset, d, q);
    reset = 1; d = 8'b00000000;
    #10 reset = 0; d = 8'b10101010;
    #10 d = 8'b11110000;
    #10 d = 8'b00001111;
    #10 $finish;
  end
endmodule
OutputSuccess
Important Notes

Use non-blocking assignment (<=) inside always blocks for registers.

Resetting the register clears stored data to a known state.

Registers update only on clock edges, so timing is important.

Summary

A register holds multiple bits of data and updates on clock edges.

Use parameters to set the register size for flexibility.

Reset input helps start the register with a known value.