FB having single input but initialized with Array

mxj262
2024-05-03
2024-05-07
  • mxj262 - 2024-05-03

    I am adding elements of an ARRAY using pointer to access each element inside a FOR loop and the FOR loop does not stop!

    What is the right way to use pointers in such case??

    I have another loop that is not using pointer and it stops but the loop using pointer keep on adding.

    METHOD FB_Init: BOOL
    VAR_INPUT
        bInitRetains: BOOL; // TRUE: the retain variables are initialized (reset warm / reset cold)
        bInCopyCode: BOOL;  // TRUE: the instance will be copied to the copy code afterward (online change)   
    END_VAR
    
    VAR_IN_OUT // basically REFERENCE TO
        window_buffer: ARRAY [*] OF INT; // array of any size
    END_VAR
    THIS^.windowPtr := ADR(window_buffer[0]);
    THIS^.windowSize := UPPER_BOUND(window_buffer, 1) - LOWER_BOUND(window_buffer, 1) + 1;
    
    
    FUNCTION_BLOCK FB500
    VAR_INPUT
    END_VAR
    VAR_OUTPUT
    END_VAR
    VAR
        windowPtr: POINTER TO INT;                    
        windowSize: DINT;
        currentIndex: UINT;
        element1:INT;
        element2:INT;
        i:INT;
        j:INT;
        sum:DINT:=0;
    
    END_VAR
    
    element1:=windowPtr[0]; // read the first element of the Array dynamic memorry 
    element2:=windowPtr[1];
    
    FOR i:=0 TO (TO_INT(windowSize-1)) BY 1 DO   // this loop does not stop
    Sum:=sum + windowPtr[i];
    END_FOR
    
    
    FOR j:=0 TO 5 BY 1 DO  // this loop stops 
        j:=j+1;
    
    END_FOR
    


    https://ibb.co/k3DhkZT

     
    πŸ‘
    1

    Related

    Talk.ru: 1


    Last edit: mxj262 2024-05-06
  • mxj262 - 2024-05-04
     

    Last edit: mxj262 2024-05-04
  • Fless

    Fless - 2024-05-06

    with every call of the FB500 it keeps adding the INTs of the array to the sum variable.
    set sum to 0 before you start the loop.

     
  • mxj262 - 2024-05-06

    works

     

    Last edit: mxj262 2024-05-06
  • mxj262 - 2024-05-06

    Ok yes now the loop has stopped when I set sum to zero before the for loop.
    Why will it retain the sum value from the last call?

     
    • Fless

      Fless - 2024-05-07

      Why will it retain the sum value from the last call?

      This is how PLC work. Usually variables only get initialized after a download or a reset (i.e. power loss).

      RETAIN variables are saved in a special kind of RAM and keep their value after a power loss.

      To initialize variables on every call of your FB use the VAR TEMP block.

      VAR_TEMP
          sum : INT;
      END_VAR
      
       

Log in to post a comment.