Untitled

 avatar
unknown
verilog
2 years ago
1.5 kB
6
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
);

// Output signals can be reg or wire
// add your design here

parameter UP = 1'b1;
parameter DOWN = 1'b0;

reg [3:0] nxt_out;

// Reset signal
always @(posedge clk) begin
    if(!rst_n)begin
        nxt_out <= min;
        direction = UP;
    end
end

// Deal with Cnt
always @(*) begin
    case (direction)
        UP: begin
            nxt_out = out + 1;
        end 
        DOWN: begin
            nxt_out = out - 1;
        end
        default: nxt_out = out;
    endcase
end

// Deal with output
always @(posedge clk) begin
    if(enable)begin
        if(max <= min) begin
            out <= out;
            direction = direction;
        end
        else if(min <= nxt_out && nxt_out <= max) begin
            out <= nxt_out;
        end
        else if(nxt_out < min || nxt_out > max) begin
            direction = !direction;
            case (direction)
                UP : begin
                    out <= out + 1;
                end
                DOWN: begin
                    out <= out - 1;
                end 
                default: out <= out;
            endcase
        end
    end
end

// Deal with flip
always @(posedge clk) begin
    if(flip)begin
        direction <= !direction;
    end
end

endmodule
Editor is loading...