Modbus-Ascii注意事项

1:消息以冒号 : 字符开头(ASCII表示为 0x3A),以回车换行对 \r\n (ASCII表示为 0x0D和 0x0A)结尾;所有其他字段传输的数据所允许的十六进制表示字符为的 0-9A-F,所以除了头和尾其他数据都是10进制的表现形式。

2:数据每个8位的字节被拆分为两个ASCII字符进行发送,所以收到数据后两个字符组成一个16机制字符串,这个字符串转10进制后就是实际收到的数值

3:同样因8位的字节被拆分为两个ASCII字符,在计算LRC时候数据去两个字符组成16进制数据,进行叠加,之后取反加1

4:举例子:消息“:010420C1000218<CRLF>”应该用ascii码的形式发送出去,收到数据后进行解码LRC计算为:

function LJK_LRC(data:string):string;
var
  iLoop:Integer;
  iLen:Integer;
  iResult:Byte;
begin
  iResult:=0;
  iLen:=Length(data) div 2;
  for iLoop:=0 to iLen - 1 do
  begin
   iResult:=iResult+StrToInt( '0X'+data[iLoop*2+1]+data[iLoop*2+2] );
  end;
  iResult := not(iResult)+1;
  Result:=':'+data+IntToHex(iResult,2)+Chr(13)+Chr(10);
end;

procedure TForm1.Button3Click(Sender: TObject);
var Ssend:string;
begin
   Ssend:='010420C10002';
   Ssend:=LJK_LRC(Ssend);
   self.Memo1.Lines.Add(Ssend);
   self.Comm1.WriteCommData( PChar(Ssend),Length(Ssend) );
end;

猜你喜欢

转载自blog.csdn.net/ljklxlj/article/details/141163803