Creating a simple Delay

ray1981
2022-04-21
2022-04-28
  • ray1981 - 2022-04-21

    Hello All,

    Im new to the forum and to CoDeSYS.

    Im trying to create a function block which needs a timer unfortunately all examples I have found do not work I guess I make a beginner error. I hope someone want to help me

    FOR vCount := 0 TO 1999 DO
    
    vVsample[vCount] := INT_TO_REAL(WORD_TO_INT(vVin));
    
    Delay(IN:=TRUE, PT:=T#1S);
    IF NOT(Delay.Q) THEN
       RETURN;
    END_IF
    Delay(IN:=FALSE);
    vCount := vCount + 1;
    
    
    END_FOR
    

    I use here a delay of 1s for testing purposes at the end it should sample faster. This code I placed in a function block which is inside a loop that should run each 2s which I setup in the taskconfiguration.

    I hope someone could help me understand why the counter doesn't count up, infact Delay.Q never seems to get True.

    Thanks in advance

     
  • oguzemretombul - 2022-04-28

    FOR vCount := 0 TO 1999 DO something ; end_for
    vCount already increase 0 to 1999 on every each task sample time.
    why you add INT_TO_REAL(WORD_TO_INT(vVin));
    and why you need this vCount + 1;
    what you wanna do i couldnt understand but check your vCount value.

     
  • tvm - 2022-04-28

    some notes on your code

    FOR vCount := 0 TO 1999 DO    
    

    NOTE: vCount gets reset to 0 on every scan of the PLC

        vVsample[vCount] := INT_TO_REAL(WORD_TO_INT(vVin));
    
        Delay(IN:=TRUE, PT:=T#1S);
    

    It's usually best to put timers outside of loops

        IF NOT(Delay.Q) THEN  
    

    this condition will only be true once per second. On every other scan cycle of the PLC, Delay.Q will be false.

           RETURN;
    

    RETURN exits the whole function block, not the loop itself.
    To exit a loop, use EXIT
    this RETURN will happen on every scan except once/second

    END_IF
        Delay(IN:=FALSE);
    

    this will only be scanned once/second, because of the above RETURN statement

    vCount := vCount + 1;  
    

    this would cause vCount to count by twos, because the FOR loop already increments vCount every time it loops (if you want to count up my multiples, you could use FOR vCount:= 0 TO 1999 BY 2 DO, for example). If you want to manually increment your loop counter, use WHILE, or use a different variable. But, it's not actually being scanned most of the time, for the same reason as the previous line

    END_FOR
    
     

    Last edit: tvm 2022-04-28

Log in to post a comment.