0
0
VerilogHow-ToBeginner · 3 min read

Verilog Code for Shift Register: Syntax and Example

A shift register in Verilog is created using a reg array and a clocked always block that shifts data on each clock edge. You define the register size and update its bits by shifting data in or out sequentially.
📐

Syntax

A basic shift register uses a reg array to hold bits and an always @(posedge clk) block to update the register on each clock pulse. The input bit is shifted into the register, and existing bits move one position.

  • clk: Clock signal triggering the shift.
  • reset: Optional signal to clear the register.
  • data_in: New bit shifted into the register.
  • shift_reg: Register holding the shifted bits.
verilog
reg [N-1:0] shift_reg;
always @(posedge clk or posedge reset) begin
  if (reset)
    shift_reg <= 0;
  else
    shift_reg <= {shift_reg[N-2:0], data_in};
end
💻

Example

This example shows a 4-bit shift register that shifts in data_in on each rising clock edge and resets to zero when reset is high.

verilog
module shift_register_4bit(
  input wire clk,
  input wire reset,
  input wire data_in,
  output reg [3:0] shift_reg
);

always @(posedge clk or posedge reset) begin
  if (reset)
    shift_reg <= 4'b0000;
  else
    shift_reg <= {shift_reg[2:0], data_in};
end

endmodule
⚠️

Common Pitfalls

Common mistakes include:

  • Not using a clock edge in the always block, causing combinational logic instead of sequential.
  • Forgetting to reset the register, which can lead to unknown initial values.
  • Incorrect bit slicing when shifting, which can cause data loss or wrong shifting direction.
verilog
/* Wrong: Missing clock edge, causes combinational logic */
always @(*) begin
  shift_reg = {shift_reg[2:0], data_in};
end

/* Right: Use clock edge for sequential shift */
always @(posedge clk or posedge reset) begin
  if (reset)
    shift_reg <= 4'b0000;
  else
    shift_reg <= {shift_reg[2:0], data_in};
end
📊

Quick Reference

Tips for writing shift registers in Verilog:

  • Use always @(posedge clk) for synchronous shifting.
  • Include a reset signal to initialize the register.
  • Use concatenation {} to shift bits easily.
  • Define register width clearly with reg [N-1:0].

Key Takeaways

Use a clocked always block to shift bits sequentially in a register.
Initialize the shift register with a reset signal to avoid unknown states.
Shift bits using concatenation syntax for clear and concise code.
Always define the register size explicitly to match your design needs.