50MHz 至 1MHz 的时钟分频器 - Verilog

Clock Divider for 50MHz to 1MHz - Verilog

我已经编写了SPI Master的代码,我希望输出SPI频率为1MHz。

但是,当我 运行 行为模拟时,我没有得到 1MHz spi_sclk。有什么建议我的代码有什么问题吗?谢谢!

 module spi_master(
    input wire clk,
    input wire reset,

    input wire [15:0] datain,

    output wire spi_cs_l,
    output wire spi_sclk,
    output wire spi_data,
    output wire [4:0] counter
);

reg [15:0] MOSI;
reg [4:0] count;
reg cs_l;
reg sclk = 1'b0;
reg [2:0] state;

reg [4:0] clk_counter = 0;

// SPI Output Clock frequency = 1MHz

always @(posedge clk) begin
    if (clk_counter == 24) begin
        clk_counter <= 0;
        sclk <= ~sclk;
    end
    else begin
        clk_counter <= clk_counter + 1'd1;
    end
end

always @(posedge clk or posedge reset) begin
    if(reset) begin
        MOSI <= 16'b0;
        count <= 5'd16;
        cs_l <= 1'b1;
    end
    else begin
        case (state)
        0:begin
            cs_l <= 1'b1;
            state <= 1;
        end
        1:begin
            cs_l <= 1'b0;
            MOSI <= datain[count-1];
            count <= count-1;
            state <= 2;
        end
        2:begin
            if(count > 0) begin
                state <= 1;
            end
            else begin
                count <= 16;
                state <= 0;
            end
        end
        default:state<=0;
        endcase
    end
end

assign spi_cs_l = cs_l;
assign spi_sclk = sclk;
assign spi_data = MOSI;
assign counter = count;

endmodule

测试平台

module spi_master_tb;

// Inputs

reg clk;
reg reset;
reg [15:0] datain;

// Outputs

wire spi_cs_l;
wire spi_sclk;
wire spi_data;
wire [4:0] counter;


spi_master dut(
    .clk(clk),
    .reset(reset),
    .counter(counter),
    .datain(datain),
    .spi_cs_l(spi_cs_l),
    .spi_sclk(spi_sclk),
    .spi_data(spi_data)
);


initial begin
    clk = 0;
    reset = 1;
    datain = 0;
end

always #5 clk=~clk;

initial begin
    #10 reset = 1'b0;

    #10 datain = 16'hA569;
    #335 datain = 16'h2563;
    #335 datain = 16'h9B63;
    #335 datain = 16'h6A61;

end

endmodule

波形

创建 Minimal reproducible example 会有帮助。此外,您的波形不包含重要信号 clk_counter

在你的测试台上试试这个,如果它不起作用你至少有最小的可重现示例。

我更改了 clk_counter 的初始化,在增量中我只是添加了 1 而不是 1'b1,如果你想要严格,你可以添加一个 5 位宽的 1 (5'b1).


module spi_master(
    input wire clk,
    input wire reset,
    output wire spi_sclk,
);

reg [4:0] clk_counter;

// SPI Output Clock frequency = 1MHz

always @(posedge clk) begin
  if(reset) begin
    sclk <= 1'b0;
    clk_counter <= 1;
  end
  else begin
    if (clk_counter == 24) begin
        clk_counter <= 0;
        sclk <= ~sclk;
    end
    else begin
        clk_counter <= clk_counter + 1;
    end
  end
end

assign spi_sclk = sclk;
endmodule