本人在使用Scomm控件时,发生了一些使用问题,并进行解决。相关说明如下:
1、在页面增加spcomm控件(命名:comm1),memo控件(命名:memo1),timer控件(命名:timer2)
2、在 public 定义全局变量
rbuf:array[1..9] of byte; // 接收
iputBufferLength:word; // 缓冲区字符长度
c1,c2,c3,c4,c5,c6,c7,c8,c9:integer // 返回结果存放
sbuf:array[1..9] of byte;:// 发送
3、源代码(串口设置及打开串口)
procedure TFORM1.commset(comname:string);
begin
Comm1.CommName:=comname; // 如:comm1
comm1.BaudRate:=9600;
comm1.ByteSize:=_8;
comm1.StopBits:=_1;
comm1.Parity:=None;
comm1.OnReceiveData:=Comm1ReceiveData;
comm1.StopComm;
comm1.startcomm;
comm1.Inx_XonXoffFlow:=false;
comm1.Outx_XonXoffFlow:=false;
comm1.Outx_CtsFlow:=false;
comm1.Outx_DsrFlow:=false;
Memo1.lines.Clear;
end;
{本人在测试(串口调测工具)时,发现可以接收到数据返回,但发出去的数据、对方未接收到,故本人对INX、OUTX等参数进行设置后,串口测试工具才接收并显示发送信息}
4、源代码(数据发送)
procedure TFORM1.comport_sendbyte(sendbuf:byte;sleeptime:integer);
begin
sbuf[1]:=sendbuf;
comm1.writecommdata(@sbuf[1],1) ;
sleep(sleeptime);
end;
{本人采用单BYTE发送方式;另外,由于和串口设备通信时、会根据需要需要进行暂停,故本人将发送、暂停进行封转(传送字节信息、暂时时长),以减少代码冗余}
5、源代码(数据接收1--数据接收到缓存)
procedure TFORM1.Comm1ReceiveData(Sender: TObject; Buffer: Pointer; BufferLength: Word);
var i:integer;
begin
sleep(100);
move(buffer^, pchar(@rbuf)^, bufferlength);
for i:=1 to bufferlength do
begin
memo1.lines.add(inttohex(rbuf[i],2));
end;
end;
{1、在串口设置及打开串口(commset),定义了Comm1ReceiveData负责自动接收数据
2、为便于调测,本人将数据接收后存放到了memo1里面}
6、源代码(数据接收1--取出结果数据)
procedure TFORM1.Timer2Timer(Sender: TObject);
begin
if memo1.Lines.Count>=9 then
begin
c1:=strtoint('$'+memo1.Lines[0]);
c2:=strtoint('$'+memo1.Lines[1]);
c3:=strtoint('$'+memo1.Lines[2]);
c4:=strtoint('$'+memo1.Lines[3]);
c5:=strtoint('$'+memo1.Lines[4]);
c6:=strtoint('$'+memo1.Lines[5]);
c7:=strtoint('$'+memo1.Lines[6]);
c8:=strtoint('$'+memo1.Lines[7]);
c9:=strtoint('$'+memo1.Lines[8]);
end;
memo1.Lines.Clear;
end;
{1、利用定时器,将数据取出到结果中
2、根据需要判断接收数据是否已经全部接收到(本文控制是接收9个byte)
3、注意:由于memo是临时存放数据,在取出后需要清除}