0
0
VerilogHow-ToBeginner · 3 min read

Verilog Code for Circular Shift Register: Syntax and Example

A circular shift register in Verilog shifts bits in a register and feeds the last bit back to the first position using always block triggered by a clock. The code uses a register to hold bits and shifts them on each clock cycle, wrapping the last bit to the front to create a circular effect.
📐

Syntax

The circular shift register uses an always @(posedge clk) block to update the register on each clock pulse. Inside, the bits are shifted right or left, and the bit shifted out is fed back to the opposite end to maintain a circular pattern.

Key parts:

  • reg [N-1:0] shift_reg;: declares the register holding bits.
  • always @(posedge clk): triggers update on clock rising edge.
  • shift_reg <= {shift_reg[N-2:0], shift_reg[N-1]};: shifts bits left and wraps the last bit to the first position.
verilog
reg [3:0] shift_reg;
always @(posedge clk) begin
    shift_reg <= {shift_reg[2:0], shift_reg[3]};
end
💻

Example

This example shows a 4-bit circular shift register that shifts bits left on each clock pulse. The initial value is set to 4'b1001. On each clock, the bits rotate left, wrapping the leftmost bit to the right end.

verilog
module circular_shift_register(
    input wire clk,
    input wire rst,
    output reg [3:0] shift_reg
);

always @(posedge clk or posedge rst) begin
    if (rst) begin
        shift_reg <= 4'b1001; // Initial value
    end else begin
        shift_reg <= {shift_reg[2:0], shift_reg[3]}; // Circular left shift
    end
end

endmodule
⚠️

Common Pitfalls

Common mistakes include:

  • Not using non-blocking assignment <= inside always block, which can cause incorrect simulation behavior.
  • Forgetting to wrap the shifted bit back to the register, which breaks the circular behavior.
  • Not resetting the register, leading to unknown initial values.

Example of wrong and right shift:

verilog
// Wrong: breaks circular shift
always @(posedge clk) begin
    shift_reg <= shift_reg << 1; // shifts left but loses leftmost bit
end

// Right: circular shift
always @(posedge clk) begin
    shift_reg <= {shift_reg[2:0], shift_reg[3]};
end
📊

Quick Reference

ConceptDescription
reg [N-1:0] shift_regRegister holding N bits to shift
always @(posedge clk)Update register on clock rising edge
shift_reg <= {shift_reg[N-2:0], shift_reg[N-1]}Circular left shift by wrapping last bit to front
Non-blocking assignment <=Use inside always block for correct timing
Reset logicInitialize register to known value

Key Takeaways

Use non-blocking assignment (<=) inside always blocks for registers.
Wrap the shifted out bit back to the opposite end to create circular behavior.
Initialize the shift register with a reset to avoid unknown states.
Use bit slicing and concatenation to perform circular shifts efficiently.
Test your design with a clock and reset to verify correct shifting.