Untitled

 avatar
unknown
verilog
2 years ago
1.6 kB
7
Indexable
`timescale 1ns/1ps
module Parameterized_Ping_Pong_Counter (
    input clk, 
    input rst_n, 
    input enable, 
    input flip, 
    input [3:0] max, 
    input [3:0] min, 
    output reg direction, 
    output reg [3:0] out
);

reg [3:0] next_out;
reg [3:0] next_dir;

// reset and updare
always @(posedge clk) begin
    if(rst_n == 1'b0) begin
        out <= min;
        next_out <= min;
        direction <= 1'b1;
        next_dir <= 1'b1;
    end
    else begin
        if(enable == 1'b1) begin
            out <= next_out;
            direction <= next_dir;
        end
        else begin
            out <= out;
            direction <= next_dir;
        end
    end
end

// update the value of next_out
always @(*) begin
    if(out > min && out < max) begin
        if(next_dir == 1'b1)
            next_out = out + 1;
        else if(next_dir == 1'b0)
            next_out = out - 1;
        else 
            next_out = out;
    end
    else if(out == min && next_dir == 1'b1)
        next_out = out + 1;
    else if(out == max && next_dir == 1'b0)
        next_out = out - 1;
    else
        next_out = out;
end

// change the value of next_dir
always @(*) begin
    if(out == max && direction == 1'b1) begin
        next_dir = 1'b0;
    end
    else if(out == min && direction == 1'b0) begin
        next_dir = 1'b1;
    end
    else begin
        if(flip == 1'b1) begin
            if(direction == 1'b1) next_dir = 1'b0;
            else next_dir = 1'b1;
        end
        else begin
            next_dir = direction;
        end
    end
end

endmodule
Editor is loading...