See exerpt attached PLCopen document with a FIFO example in ST. Page 46. (You will have to add the tabs back in).
or Follow the following link:
click me
Variable Declaration:
FUNCTION_BLOCK MC_LREAL_FIFO32
(* Function: The FB is a first in first out (FIFO) type Buffer for DINT Values with the size
of 32 Elements. *)
VAR_INPUT
Enable: BOOL; (* Inits the FIFO buffer on pos. edge *)
Put: BOOL; (* Writes value into FIFO on positive edge *)
Get: BOOL; (* Reads value into FIFO on positive edge *)
PutValue: LREAL; (* Value for Put *)
END_VAR
VAR_OUTPUT
Active: BOOL; (* Goes high with Enable *)
NoOfElementsInFIFO: DINT; (* Shows the number of elements in Buffer *)
GetValue: LREAL; (* Value for Get *)
Error: BOOL; (* is set at Error in FB *)
ErrorId: DINT; (* -1 = FIFO empty, -2 = FIFO full *)
END_VAR
VAR CONSTANT
MaxElements: DINT:= 32;
FIFO_Empty: DINT:= -1;
FIFO_Full: DINT:= -2;
END_VAR
VAR (* local variables *)
FIFOARRAY: ARRAY[1..MaxElements] OF LREAL;
EnableFlag: BOOL;
GetFlag: BOOL;
PutFlag: BOOL;
GetIndex: DINT;
PutIndex: DINT;
END_VAR
Code sequence:
IF Enable AND NOT EnableFlag THEN (* Initialisation at pos.edge of Enable *)
EnableFlag:= TRUE;
Active:= TRUE;
ErrorId:= 0;
Error:= FALSE;
GetIndex:= 1;
PutIndex:= 1;
NoOfElementsInFIFO:= 0;
PutFlag:= FALSE;
GetFlag:= FALSE;
ELSIF NOT Enable AND EnableFlag THEN (* Disable FB at neg.edge of Enable *)
EnableFlag:= FALSE;
Active:= FALSE;
END_IF
IF Enable AND NOT Error THEN
IF Put AND NOT PutFlag THEN (* pos.edge at Put *)
PutFlag:= TRUE;
IF NoOfElementsInFIFO >= MaxElements THEN
ErrorId:= FIFO_Full;
Error:= TRUE;
ELSE
NoOfElementsInFIFO:= NoOfElementsInFIFO + 1;
FIFOARRAY[PutIndex]:= PutValue;
PutIndex:= PutIndex + 1;
IF PutIndex > MaxElements THEN
PutIndex:= 1;
END_IF
END_IF
ELSIF NOT Put AND PutFlag THEN (* neg.edge at Put *)
PutFlag:= FALSE;
END_IF
IF Get AND NOT GetFlag THEN (* pos.Edge of Get *)
GetFlag:= TRUE;
IF NoOfElementsInFIFO < 1 THEN
ErrorId:= FIFO_Empty;
Error:= TRUE;
ELSE
NoOfElementsInFIFO:= NoOfElementsInFIFO - 1;
GetValue:= FIFOARRAY[GetIndex];
GetIndex:= GetIndex + 1;
IF GetIndex > MaxElements THEN
GetIndex:= 1;
END_IF
END_IF
ELSIF NOT Get AND GetFlag THEN (* neg.edge at Get *)
GetFlag:= FALSE;
END_IF
END_IF