我这有个Cport的,测试和PLC的通讯,用的是MOBUS,好简单的:
procedure TForm1.btn1Click(Sender: TObject);
var
crc,adr,v:Word;
plcadr:Byte;
i,n:Integer;
dv,rv:array [0..7] of Byte;
wb:TWordRec;
s:string;
begin
adr:=StrToInt(edtwa1.Text);
v:=StrToInt(edtwv1.Text);
plcadr:=StrToInt(edtPLCAdr.Text);
dv[0]:=plcadr;
dv[1]:=$06;
dv[2]:=HiByte(adr);
dv[3]:=adr;
dv[4]:=HiByte(v);
dv[5]:=v;
crc:=CalCRC16(dv,0,5);
lblcrc1.Caption:=IntToStr(crc);
dv[6]:=crc;
dv[7]:=HiByte(crc);
lblb1.Caption:=IntToHex(dv[0],2);
lblb2.Caption:=IntToHex(dv[1],2);
lblb3.Caption:=IntToHex(dv[2],2);
lblb4.Caption:=IntToHex(dv[3],2);
lblb5.Caption:=IntToHex(dv[4],2);
lblb6.Caption:=IntToHex(dv[5],2);
lblb7.Caption:=IntToHex(dv[6],2);
lblb8.Caption:=IntToHex(dv[7],2);
if not comprt1.Connected then
comprt1.Open;
comprt1.ClearBuffer(True,True);
try
comprt1.Write(dv,8);
Sleep(100);
n:=comprt1.Read(rv,8);
if n >= 8 then
begin
for i := 0 to 7 do
lstrv.Items.Add(IntToHex(rv
,2));
lblplc.Caption:=IntToStr(rv[0]);
lblFun.Caption:=IntToStr(rv[1]);
wb.bh:=rv[2];
wb.bl:=rv[3];
lbladr.Caption:=IntToStr(wb.w);
wb.bh:=rv[4];
wb.bl:=rv[5];
lblValue.Caption:=IntToStr(wb.w);
wb.bh:=rv[7];
wb.bl:=rv[6];
lblcrc.Caption:=IntToStr(wb.w);
end
else
begin
s:='返回值错误! 返回值字节数:'+ IntToStr;
stat1.SimpleText:=s;
end;
except
Application.MessageBox('写PLC错误!','错误',MB_OK);
end;
end;