0
mirror of https://gitlab.com/hyperglitch/jellyfish.git synced 2025-11-09 21:27:59 +00:00

50 lines
1.5 KiB
Verilog

// SPDX-FileCopyrightText: 2025 Igor Brkic <igor@hyperglitch.com>
// SPDX-License-Identifier: GPL-3.0-or-later
module mavg #(
parameter WIDTH = 16,
parameter DEPTH = 16
)(
input wire clk,
input wire rst,
input wire trig, // trigger signal
input wire signed [WIDTH-1:0] in_sample,
output reg signed [WIDTH-1:0] out_avg
);
// Internal parameters
localparam SUM_WIDTH = WIDTH + $clog2(DEPTH);
// Circular buffer to hold last 16 samples
reg signed [WIDTH-1:0] buffer [0:DEPTH-1];
reg [3:0] ptr; // buffer index 0..15
// Running sum of the DEPTH samples
reg signed [SUM_WIDTH-1:0] sum;
integer i;
// Sequential logic: sample and compute when triggered
always @(posedge clk) begin
if (rst) begin
sum <= 0;
ptr <= 0;
out_avg <= 0;
for (i = 0; i < DEPTH; i = i + 1)
buffer[i] <= 0;
end else if (trig) begin
// Update running sum: remove oldest, add new
sum <= sum - buffer[ptr] + in_sample;
// Store new sample
buffer[ptr] <= in_sample;
// Advance pointer with wrap-around
ptr <= ptr + 1;
// Compute and register moving average
out_avg <= sum >> 4;
end
// if not triggered, retain previous state
end
endmodule