[r13]: / trunk / I2C_Template.library.md  Maximize  Restore  History

Download this file

76 lines (66 with data), 1.2 kB


FUNCTION_BLOCK I2CTemplate EXTENDS i2c
VAR_INPUT
    lrMinDistance: LREAL;
    lrMaxDistance: LREAL;
END_VAR
VAR_OUTPUT
    lrDistance: LREAL;
    xValid: BOOL;
    xNewMeasurement: BOOL;
END_VAR
VAR
    timer: TON;
END_VAR
xNewMeasurement := FALSE;

SUPER^();

CASE _iState OF
0:
    IF usiAddress = 0 THEN
        usiAddress := 16#70;
    END_IF
    IF SUPER^.init() THEN
        _iState := 5;
    END_IF  

5:  
    Timer.pt := T#70MS;
    _iState := 10;  
    xValid := FALSE;
END_CASE

METHOD AfterReadInputs: INT
VAR
    Buffer: ARRAY [..] OF ;
    len: DINT;
END_VAR
SUPER^.AfterReadInputs();

IF _iState = 10 THEN
    timer(IN:=TRUE);
    IF timer.Q THEN 
        len := Read(ADR(Buffer), 4);
        IF len = 4 THEN
            lrDistance := BYTE_TO_LREAL(Buffer[2])*0.01 + BYTE_TO_LREAL(Buffer[3]) * 2.56;
            xValid := (lrDistance >= lrMinDistance AND lrDistance <= lrMaxDistance);
            xNewMeasurement := TRUE;
        ELSE
            xValid := FALSE;
        END_IF
        Write8(0, 16#51);   //new measurement
        timer(IN:=FALSE);
    END_IF      
END_IF

METHOD BeforeWriteOutputs: INT
SUPER^.BeforeWriteOutputs();