`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 		Churbanov S.
// 
// Create Date:    15:24:31 08/20/2019 
// Design Name: 
// Module Name:  
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.02 - File Modified
// Additional Comments: 16.09.2019 file modified in assotiate with task.
//
//////////////////////////////////////////////////////////////////////////////////
module OverloadDetect
#(	
	parameter	ThresholdWidth	=	24,
	parameter	AdcDataWidth	=	14,
	parameter	MeasPeriod		=	32
)	
(
	input	Rst_i,
	input	Clk_i,	
	input	[AdcDataWidth-1:0]		AdcData_i,
	input	[ThresholdWidth-1:0]	OverThreshold_i,
	output	Overload_o
);

//================================================================================
//  LOG2 FUNCTION
	function integer Log2;
	input integer value;
		begin
			Log2 = 0;
			while (value > 1) begin
				value   = value >> 1;
				Log2    = Log2 + 1;
			end
			
			if	((2**Log2)<MeasPeriod)	begin
				Log2	=	Log2+1;
			end	
		end
	endfunction
//================================================================================
//  LOCALPARAMS
	localparam CntWidth	=	Log2(MeasPeriod);
	localparam SumWidth	=	AdcDataWidth+CntWidth;
//================================================================================
//  REG/WIRE
	reg		overloadReg;
	reg		[CntWidth-1:0]	measCnt;		
	
	reg		[SumWidth-1:0]	adcSum;	
	
	wire	[AdcDataWidth-1:0]	absAdc	=	(AdcData_i[AdcDataWidth-1])?	(~AdcData_i + 1):AdcData_i;
//================================================================================
//  ASSIGNMENTS
	assign	Overload_o	=	overloadReg;
//================================================================================
//  CODING
always	@(posedge	Clk_i)	begin
	if	(!Rst_i)	begin
		if	(measCnt	!= MeasPeriod-1)	begin
			measCnt	<=	measCnt	+	{{{CntWidth-1{1'b0}},1'b1}};	
		end	else	begin
			measCnt	<=	{CntWidth{1'b0}};
		end
	end	else	begin
		measCnt	<=	{CntWidth{1'b0}};
	end
end

always	@(posedge	Clk_i)	begin
	if	(!Rst_i)	begin
		if	(measCnt==MeasPeriod-1)	begin
			adcSum	<=	absAdc;	
		end	else	begin
			adcSum	<=	adcSum	+	absAdc;
		end
	end	else	begin
		adcSum	<=	0;
	end
end
	
always	@(posedge	Clk_i)	begin
	if	(measCnt	==	MeasPeriod-1)	begin
		if	((adcSum>>CntWidth)	>	OverThreshold_i)	begin
			overloadReg	<=	1'b1;
		end	else	begin
			overloadReg	<=	1'b0;
		end
	end
end
endmodule
