INCLUDE rtcu.inc
VAR_INPUT
SerialPort : SINT;
MyNodeID : SINT;
DestNodeID : SINT;
END_VAR;
VAR_OUTPUT
RXLed : BOOL;
END_VAR;
VAR
xAI : ARRAY[1..4] OF INT;
xDI : ARRAY[1..12] OF BOOL;
xAO : ARRAY[1..4] OF INT;
xDO : ARRAY[1..12] OF BOOL;
END_VAR;
FUNCTION getINT:INT;
VAR_INPUT
adr : ptr;
END_VAR;
memcpy(dst:=ADDR(getInt),src:=adr,len:=SIZEOF(getINT));
END_FUNCTION;
FUNCTION setINT;
VAR_INPUT
adr : ptr;
v : INT;
END_VAR;
memcpy(dst:=adr,src:=ADDR(v),len:=SIZEOF(v));
END_FUNCTION;
PROGRAM Master;
VAR
RX : serFrameReceiver;
Len : SINT;
RxBuffer : ARRAY[0..63] of SINT;
TxBuffer : ARRAY[0..63] of SINT;
Index : SINT;
tAnswer : TON;
str : STRING;
END_VAR;
serOpen(Port:=SerialPort, Baud:=57600, bit:=8, Parity:=0, RS485:=TRUE);
RX(port:=SerialPort, enable:=TRUE, frame:=ADDR(rxbuffer), maxsize:=SINT(SIZEOF(rxbuffer)), stuffch:=16#10, sof:=16#02, eof:=16#03);
DebugMsg(message:="Master running");
tAnswer.pt:=1000;
xAO[1]:=128;
xAO[2]:=256;
xAO[3]:=512;
xAO[4]:=1023;
FOR index:=1 TO 12 BY 2 DO
xDO[index]:=TRUE;
END_FOR;
BEGIN
tAnswer();
Sleep(delay:=100);
TXBuffer[0]:=MyNodeID;
TXBuffer[1]:=DestNodeID;
TXBuffer[2]:=0;
TXBuffer[3]:=0;
FOR index:=0 TO 7 DO
IF xDO[index+1] THEN
TXBuffer[2]:=TXBuffer[2] OR shl8(in:=1, n:=index);
END_IF;
END_FOR;
FOR index:=0 TO 3 DO
IF xDO[index+9] THEN
TXBuffer[3]:=TXBuffer[3] OR shl8(in:=1, n:=index);
END_IF;
END_FOR;
setInt(adr:=ADDR(TXBuffer[4]), v:=xAO[1]);
setInt(adr:=ADDR(TXBuffer[6]), v:=xAO[2]);
setInt(adr:=ADDR(TXBuffer[8]), v:=xAO[3]);
setInt(adr:=ADDR(TXBuffer[10]),v:=xAO[4]);
serSendData(port:=SerialPort, data:=ADDR(TXBuffer), size:=12, stuffch:=16#10, sof:=16#02, eof:=16#03);
tAnswer.trig:=TRUE;
WHILE NOT RX.ready AND NOT tAnswer.q DO
RX();
tAnswer();
END_WHILE;
tAnswer.trig:=FALSE;
IF RX.Ready THEN
RXLed:=NOT RXLed;
IF MyNodeID = RXBuffer[1] THEN
xAI[1]:=getINT(adr:=ADDR(RXBuffer[4]));
xAI[2]:=getINT(adr:=ADDR(RXBuffer[6]));
xAI[3]:=getINT(adr:=ADDR(RXBuffer[8]));
xAI[4]:=getINT(adr:=ADDR(RXBuffer[10]));
FOR index:=0 TO 7 DO
xDI[index+1]:=(RXBuffer[2] AND shl8(in:=1, n:=index)) <> 0;
END_FOR;
FOR index:=0 TO 3 DO
xDI[index+9]:=(RXBuffer[3] AND shl8(in:=1, n:=index)) <> 0;
END_FOR;
DebugFmt(message:="Analog inputs: \1,\2,\3,\4", v1:=xAI[1], v2:=xAI[2], v3:=xAI[3], v4:=xAI[4]);
str:="";
FOR index:=1 to 12 DO
str:=strConcat(str1:=str, str2:=intToStr(v:=INT(xDI[index])));
END_FOR;
DebugMsg(message:=strConcat(str1:="Digital inputs: ", str2:=str));
ELSE
DebugMsg(message:="Message not for this node !");
END_IF;
serFrameReceiveDone(port:=SerialPort);
ELSE
DebugMsg(message:="Timeout waiting for response !");
END_IF;
END;
END_PROGRAM;
|