Problem with FT_AVG Codesys3.5

Begonnen von hejhopp1, 28. Januar 2026, 09:32:35

Vorheriges Thema - Nächstes Thema

0 Mitglieder und 1 Gast betrachten dieses Thema.

hejhopp1

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 := in; END_FOR;
out := in;
i := 0;
ELSIF stop < 0 THEN
out := in;
ELSE
out := buf;
buf := in;
i := INC1(i, N);
END_IF;