CRC Code in VB6.0

L

Thread Starter

Luan Nguyen

Hi!

I'm writing a HMI program to link a PLC and a PC. Using mscomm control in VB I can send a character to PLC and wait to receive a character sent back from the PLC. I entered "a" in a textbox and sent it to PLC which programmed to sent "c" when receive "a". It works.

Now I want to send data from 2 textboxes to the PLC. The protocol used is MODBUS RTU. I wonder if I have to merge the data from the 2 textboxes before change the new data into binary number and send it?

I can write a program to produce the CRC code correlative to a definite code entered. I dont know how to make the program be able to produce CRC code automatically which is correlative to the different data entered from the 2 textboxes?

Would you please show me the way to write a procedure to sent data from PC to PLC and versus, and how to write a procedure to create the CRC code according to the data from the 2 textboxes.

Thank you very much
Luan Nguyen
[email protected]
 
K
<p>CRC Code in Delphi.
<pre>
Function CRC16(data:Array of Byte;EndPos:Integer):String ;
var CRC16Lo,CRC16Hi,CL,CH,SaveHi,SaveLo:byte;
i,Flag:Integer;
begin
CRC16Lo:=$FF;
CRC16Hi:=$FF;
CL:=$1;
CH:=$A0;
For i:=0 To EndPos-1 Do
Begin
CRC16Lo:=CRC16Lo Xor data; For Flag:=0 To 7 Do
Begin
SaveHi:=CRC16Hi;
SaveLo:=CRC16Lo;
CRC16Hi:=CRC16Hi Div 2; CRC16Lo:=CRC16Lo Div 2;
If ((SaveHi And $1)=$1) Then CRC16Lo:=CRC16Lo Or $80; If ((SaveLo And $1)=$1) Then
Begin
CRC16Hi:=CRC16Hi Xor CH;
CRC16Lo:=CRC16Lo Xor CL;
End;
End;
End;
Result:=inttohex(CRC16Lo,2)+inttohex(CRC16Hi,2);
End;
Function GetModbusCommand(DeviceAddress:byte;PointType:byte;RegisterAddress:Array of byte;RegisterLength:Array of byte):string;
var sendBuf:Array[1..8] of byte;
begin
sendbuf[1]:=DeviceAddress;
sendbuf[2]:=PointType;
sendbuf[3]:=RegisterAddress[0];
sendbuf[4]:=RegisterAddress[1];
sendbuf[5]:=RegisterLength[0];
sendbuf[6]:=RegisterLength[1];
sendbuf[7]:=StrtoInt('$'+Copy(CRC16(sendbuf,6),1,2));
sendbuf[8]:=StrtoInt('$'+Copy(CRC16(sendbuf,6),3,2));
result:=inttoHex(sendBuf[1],2)+inttoHex(sendBuf[2],2)+inttoHex(sendBuf[3],2)+inttoHex(sendBuf[4],2)
+inttoHex(sendBuf[5],2)+inttoHex(sendBuf[6],2)+inttoHex(sendBuf[7],2)+inttoHex(sendBuf[8],2);
end;
</pre>

<p>myEmail:[email protected]
 
Top