Verilog实现移位寄存器

Verilog实现8位环形移位寄存器

左移: 环形就是首尾相连

module shift_regist (
    input  wire clk,
    input wire rstn,
    input wire [7:0]D,
    output reg [7:0]Q
);
always @(posedge  clk  or  negedge  rstn) begin
    if(!rstn)
        Q<=8'b000000;
    else
         Q<={D[6:0],D[7]} ;    
end
endmodule //shift_regist 

右移:

module shift_regist (
    input  wire clk,
    input wire [7:0]D,
    input wire rstn,
    output reg [7:0]Q
);
always @(posedge  clk ) begin
        if(!rstn)
        Q<=8'b000000;
    else
         Q<={D[0],D[7:1]} ;    
end
endmodule //shift_regist  

普通的移位寄存器用for语句实现:

module shift_regist2(Q,D,rst,clk);
    output [7:0] Q;
    input D,rst,clk;
    reg [7:0] Q;
    integer i;
always @(posedge clk)
    if (!rst) 
        Q<=8'b000000;
    else
      	for (i=7;i>0;i=i-1)
        begin
            Q[i]<=Q[i-1];  
                Q[0]<=D;
            end
endmodule 

普通左移:

//8 bit shift register
module shift_regist(
  input d,
  input rstn,
  input clk,
  output reg [7:0]q
);
  always@(posedge clk or negedge rstn)begin
    if(!rstn)
      q <=8'b0;
    else
      q <={q[6:0],d};
  end
endmodule

tb测试:

module tb;
  reg d,rstn,clk;
  wire [7:0]q;

  shift_regist u_shift(d,rstn,clk,q);

  initial begin
    rstn=0;
    clk=0;
    #5
    rstn=1;
  end

  always #5 clk=~clk;

  initial begin
    d=0;
    #10 d=0; //00
    #10 d=1; //001
    #10 d=1; //0011
    #10 d=0; //00110
    #10 d=0;
    #10 d=1;
    #10 d=1;
    #10 d=0;
    #10 d=1;
    #10 $finish;
  end
endmodule

图形分析:
Verilog实现移位寄存器_第1张图片

双向shift:就是加个判断

always@(posedge clk)begin
	if(dir==0)
		sf<={sf[2:0],din};
	else
		sf<={din,sf[3:1]};
end

你可能感兴趣的:(数字IC,fpga开发,硬件工程)