串口控件spcomm使用的问题(100分)

青梅

Unregistered / Unconfirmed
GUEST, unregistred user!
现在我想写串口主从通信。。
我用循环来实现。。可是总也不对,
我是这样想的,先把需要通信的所有人设备选出来,然后循环去呼叫。。然后从设备应答,
可是不知道怎么回事,我测试时总是发完了所有的设备信息才触发收到从设备的信息,也就
是程序中标记为//ERROR的部分不对。。
程序循环部分如下:
//取出设备编码
File_today('开始执行串口通讯');
with AdoQuery_s do
begin
close;
Sql.Clear ;
Sql.Add('select wid from watch');
open;
lsi:=1;
while not eofdo
begin
wids[lsi]:=Fields[0].AsString ;
lsi:=lsi+1;
next
end;
count:=RecordCount;
close;
end;
File_today('运行设备:'+IntTostr(count));
if count>0 then
//设备>0
begin
Wi:=0 ;
While wi=0do
begin
for Fi:=1 to count do
begin
sleep(200);
try
strTobyte('53'+wids[fi]);
//'R'=83
Comm1.WriteCommData(@lsBS,5) ;
Edit1.Text:=wids[fi]+'发送成功信号';
File_today(wids[fi]+'发送成功R');
except
File_today(wids[fi]+'发送成功信号失败,请检测串口状态!') ;
endini(fi);
//初始化变量
end;
{判断是否收到数据}
ti:=0;
//ERROR的部分
while ti<500do
begin
if viewstring='' then
ti:=ti+1
else
ti:=500;
end;

if viewstring='' then
ei[fi]:= ei[fi]+1;
//错误次数加1
//判断是否收到数据
if ei[fi]>=5 then
File_today(wids[fi]+'发送数据接收失败5次,请检测设备状态!')
else
begin
if copy(viewstring,1,2)='59' then
//'Y'='59'
begin
if length(viewstring)=18 then
//判断收到是不是位长正确
begin
if (Compute_xor(copy(viewstring,3,length(viewstring)-2))='00') then
begin
try
Insert_devt(wids[fi],copy(viewstring,3,length(viewstring)-4));
lsBS[1]:=82;
//'R'=82
Comm1.WriteCommData(@lsBS,1) ;
Edit1.Text:=wids[fi]+'发送成功信号';
File_today(wids[fi]+'发送成功R');
except
File_today(wids[fi]+'发送成功信号失败,请检测串口状态!') ;
end;
endini(Fi);
//初始化变量
end
else
begin
try
lsBS[1]:=69;
//'E'=69
Comm1.WriteCommData(@lsBS,1) ;
Edit1.Text:=wids[fi]+'发送失败信号';
File_today(wids[fi]+'发送失败E');
except
File_today(wids[fi]+'发送失败信号失败,请检测串口状态!') ;
endini(fi);
//初始化变量
end;
end;
end;
end
else
if copy(viewstring,1,2)='4E' then
//'N'='4E'
begin
File_today(wids[fi]+'设备无记录!') ;
endini(fi);
//初始化变量
end;
end;
end;

end;
end;
spcomm的ReceiveData()事件代码如下:
begin
viewstring:='' ;
move(buffer^,pchar(@rbuf)^,bufferlength);
for i:=1 to bufferlengthdo
begin
viewstring:=viewstring+inttohex(rbuf,2);
//16进制
end;
File_today('收到数据'+viewString);
Edit1.Text :='串口正在接收数据';
end;

我是想串口向一个从设备发出从设备的编码后,就等待从设备的回应,也就是应该
可以触发到ReceiveData()事件,可是不知道怎么搞的,总是在等待时收不到,等主机
发了好多个,ReceiveData()才收到多机发过来的数据。。
到底怎么回事??
 
呵呵,是这样的.
你循环的发命令,在所有命令发完前,所有的返回都被塞在那里了,似乎没有TCP通讯那种接收可以在另一个线程里的效果.
我上次也碰到过类似问题,找不到多线程的串口访问办法.我听说过有多线程的串口控件,但在下愚笨,只有用笨办法,发一个后就开始听,在指定时间内没听到就当他不在.然后再发下一个.呵呵,这方法有够笨吧
 
LeeChange
方法再笨只要有效就是好方法
你的做法其实是单线程通信程序的标准做法
 
TO:LeeChange
“发一个后就开始听,在指定时间内没听到就当他不在.然后再发下一个”;
怎么去听,是去触发接收吗??具体应该怎么做??
 
不用OnReceive事件读,而用Read方法读(不知道在spcomm里叫什么名字,但肯定有类似方法)
 
我也想用read,可是没有找到。。。请顺你用的是什么控件??
 
类名是: TCommPortDriver
在vcl.vclxx.org上找的.
 
没找到。。你能不能给我发一个。。。还有你的例子。。谢谢你
aliyan@163.com
 
接受答案了.
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
顶部