读书人

关于串口中提取数据的有关问题应怎样

发布时间: 2012-03-22 17:43:57 作者: rapoo

关于串口中提取数据的问题,应怎样的处理?
现想从串中读取数据并从里面取出来,现已作到能从串口读出数据(使用的是API函数的方式),但是不知怎样的取其中的数据,数据协议如下:

客户系统 RS232 无线PDA系统

客户系统-> 系统(发信请求通信协议)
Baud rate Parity Word length Stop bits
波特率 奇偶校验位 数据长度 数据停止位
1200 none 8 1

28HPDA号(6byte右对齐)(用空格补足6byte)20H任务内容(不超过100 byte)54H

无线PDA系统-> 客户系统(收到发信请求反馈信息, 注:当寻呼接口收到后)

05H (ACK)

注: 28H , 54H , 20H(空格) , 05H 为 ASCII 码 ,其他为字符。

数据信息数据读出代码如下:(采用了一个listview作表显示相应的提取数据)

//数据接收消息处理函数
procedure tform1.wmcommnotify(var message:tmessage);
var
titem:tlistitem;
commstate:comstat;
dwnumberofbytesread:dword;
errorflag:dword;
inputbuffer:array[0..1024] of char; //静态数组
recvstring:string;
recstr,recno,recinfo,recmes:string;
begin
if not clearcommerror(hrecv,errorflag,@commstate) then
begin
messagebox(0, 'clearcommerror ! ', 'notice ',mb_ok);
purgecomm(hrecv,purge_rxabort or purge_rxclear);
exit;
end;
if (commstate.cbInQue> 0) then
begin
fillchar(inputbuffer,commstate.cbInQue,#0);
if (not readfile(hrecv,inputbuffer,commstate.cbInQue,dwnumberofbytesread,@read_os)) then
begin
errorflag:=getlasterror();
if (errorflag <> 0)and (errorflag <> error_io_pending) then
begin
receive:=false;
raise exception.Create( '读串口数据出错!! ');
end
else
begin
waitforsingleobject(hrecv,infinite);


getoverlappedresult(hrecv,read_os,dwnumberofbytesread,false);
end;
end;
if dwnumberofbytesread> 0 then
begin
read_os.Offset:=read_os.Offset+dwnumberofbytesread;
inputbuffer[dwnumberofbytesread]:=#0;//其中inputbuffer即是接收的包,就在这里提取内容

//开始提取数据
recstr:=copy(inputbuffer,1,pos(05H,inputbuffer));
recinfo:=copy(recstr,pos(#28H,recstr),pos(#54H,recstr));
recno:=copy(recinfo,pos(#28H,recinfo)+1,pos(#03H,recinfo)-1);
recmes:=copy(recinfo,pos(#03H,recinfo)+1,pos(#54H,recinfo)-7);
titem:=listview1.Items.Add;
titem.caption:=strpas(recno);
titem.SubItems.Add(strpas(recmes));
end;
end;
setevent(post_event);
end;

以上的数据的提取是否写的正确,里面有没有什么要注意的,
1、比如是不是可能出现复的提取着一条数据,因为数据在提取之后在内存是否已删除,



[解决办法]
我没有用过aip,不过我觉得spcomm或者apro还是比api使用起来方便。


procedure Tfrm_icread.Comm1ReceiveData(Sender: TObject; Buffer: Pointer;
BufferLength: Word);

var

tmpArray:array[0..256] of Byte;
ArraySize: DWORD;
Count:DWORD;
tmpStr:string;
i:integer;
pStr:PChar;
begin //-------------接受返回串口返回数据-----------
pStr:=Buffer;
tmpStr:=string(pStr);
Dec(PStr);
tempb:= ' ';
for i:=0 to bufferlength-1 do
begin
inc(PStr);
tmpArray[i]:=Byte(PSTR^);
tempb:=tempb+IntToHEX(Ord(tmpArray[i]),2);

end;
end;

读书人网 >.NET

热点推荐