# Problem with FT\_AVG Codesys3.5

**URL:** <https://oscat.discourse.group/t/problem-with-ft-avg-codesys3-5/2500>\
**Category:** Bestehende Module / Existing Modules\
**Created:** [28. Januar 2026 um 08:32 UTC](https://oscat.discourse.group/t/problem-with-ft-avg-codesys3-5/2500 "2026-01-28T08:32:35Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![hejhopp1](https://avatars.discourse-cdn.com/v4/letter/h/e36b37/32.png) [@hejhopp1](https://oscat.discourse.group/u/hejhopp1)\
**Post date:** [28. Januar 2026 um 08:32 UTC](https://oscat.discourse.group/t/problem-with-ft-avg-codesys3-5/2500/1 "2026-01-28T08:32:35Z")

</div>

Hi,

I have a problem with the FT\_AVG, is seems like it does not average correctly when going to 0.

It seems like in the last cycle, the calculation gets incorrect.  
Have you experienced this?

I was not able to upload pictures but the calculation looks like this (bold is actual numbers)

130 input  
avg130 := avg130 + (in130 - buff.out130 ) / INT\_TO\_REAL(N)10;

0 input until last cycle  
avg13 := avg13 + (in0 - buff.out130 ) / INT\_TO\_REAL(N)10;

after last cycle  
avg-9.54E-06 := avg-9.54E-06 + (in0 - buff.out130 ) / INT\_TO\_REAL(N)10;

afterwards  
avg-9.54E-06 := avg-9.54E-06 + (in0 - buff.out0 ) / INT\_TO\_REAL(N)10;

* * *

Attaching code from lib to make discussion easier:

FUNCTION\_BLOCK FT\_AVG  
VAR\_INPUT  
IN : REAL;  
E : BOOL := TRUE;  
N : INT := 32;  
RST : BOOL;  
END\_VAR  
VAR\_OUTPUT  
AVG : REAL;  
END\_VAR  
VAR  
buff : DELAY;  
i: INT;  
init : BOOL;  
END\_VAR

(\* limit n to a max of 32 because delay can do max 32 cycles \*)  
buff.N := LIMIT(0, N, 32);

IF NOT init OR rst THEN  
FOR i := 1 TO N DO  
buff(in := in);  
END\_FOR;  
avg := in;  
init := TRUE;  
ELSIF E THEN  
buff(in := in);  
avg := avg + (in - buff.out ) / INT\_TO\_REAL(N);  
END\_IF;

* * *

FUNCTION\_BLOCK DELAY  
VAR\_INPUT  
IN : REAL;  
N : INT;  
RST : BOOL;  
END\_VAR  
VAR\_OUTPUT  
OUT : REAL;  
END\_VAR  
VAR  
buf : ARRAY[0..31] OF REAL;  
i : INT;  
init: BOOL;  
stop: INT;  
END\_VAR

stop := LIMIT(0,N,32) - 1;  
IF rst OR NOT init THEN  
init := TRUE;  
FOR i := 0 TO stop DO buf[i] := in; END\_FOR;  
out := in;  
i := 0;  
ELSIF stop \< 0 THEN  
out := in;  
ELSE  
out := buf[i];  
buf[i] := in;  
i := INC1(i, N);  
END\_IF;
