Verilog
Verilog
module up_down_counter (
input clk,
input reset,
input up_down, // High for up, Low for down
output reg [n-1:0] count // Size of counter (n bits)
);
// Instantiate two n-bit synchronous counters (one for up, one for down)
counter #(N) up_counter (.clk(clk), .reset(reset), .enable(up_down), .q(count));
counter #(N) down_counter (.clk(clk), .reset(reset), .enable(~up_down), .q(n'b1 -
count));
endmodule
module counter (
input clk,
input reset,
input enable,
output reg [n-1:0] q
);
parameter integer N = 4;
endmodule
Use code with caution.
Explanation:
Module Definition:
up_down_counter:
clk: Clock signal.
reset: Active high reset signal to initialize the counter to 0.
up_down: Controls the counting direction (high - up, low - down).
count: Output register holding the current counter value.
counter:
clk, reset: Same as up_down_counter.
enable: Enables counting for this specific counter.
q: Output register holding the counter value (internal to the sub-module).
Parameterization:
N: Defines the size of the counter (number of bits). You can modify this parameter
in both modules to change the counter width.
Counter Instantiation:
Inside up_down_counter, two counter modules are instantiated:
up_counter: This counter is enabled only when up_down is high, effectively counting
up.
down_counter: This counter is enabled only when up_down is low. It counts down by
using the inverted value of up_down and subtracting 1 from a complemented version
of count. This ensures it reaches 0 when counting down from the maximum value.
Counter Functionality:
The counter module implements a basic synchronous counter using an always block
triggered by the clock and reset signals.
If reset is high, the counter is initialized to 0.
If enable is high, the counter increments its value by 1 on every positive clock
edge.
Note: This code provides a structural model by composing smaller counter modules.
You can further customize this design by adding additional functionalities like
load or maximum count values based on your specific requirements.