一个关于使用Windows API实现串口通讯的问题(100分)

  • 主题发起人 主题发起人 ycj
  • 开始时间 开始时间
Y

ycj

Unregistered / Unconfirmed
GUEST, unregistred user!
如何将readfile函数中缓冲区中的数据读出来?
我每次读出来的数据不是空的就是乱码,是什么原因?
 
源程序提供如下:
unit comcode;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
const
Wm_commNotify=Wm_user+12;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
procedure comminitialize;
procedure msgcommprocess(var message:tmessage);message wm_commnotify;
{ Private declarations }
public
{ Public declarations }
end;
Tcomm=class(tthread)
protected
procedure Execute;override;
end;

var
Form1: TForm1;
hcom,post_event:Thandle;
lpol:poverlapped;

implementation

{$R *.DFM}
procedure Tcomm.Execute;
var
dwevtmask:dword;
wait:boolean;
begin
fillchar(lpol,sizeof(toverlapped),0);
while true do begin
dwevtmask:=0;
wait:=waitcommevent(hcom,dwevtmask,lpol);
if wait then begin
waitforsingleobject(post_event,infinite);
resetevent(post_event);
postmessage(form1.handle,wm_commnotify,0,0);
end;
end;
end;
procedure Tform1.comminitialize;
var
lpdcb:tdcb;
begin
hcom:=createfile('com2',generic_read or generic_write,0,nil,open_existing,
file_attribute_normal or file_flag_overlapped,0);
if hcom=invalid_handle_value then
else
setupcomm(hcom,4096,4096);
getcommstate(hcom,lpdcb);
lpdcb.BaudRate:=2400;
lpdcb.StopBits:=1;
lpdcb.ByteSize:=8;
lpdcb.Parity:=noparity;
setcommstate(hcom,lpdcb);
setcommmask(hcom,ev_rxchar);
end;
procedure TForm1.msgcommprocess(var message: tmessage);
var
clear:boolean;
coms:tcomstat;
readnumber,lperrors:dword;
cbnum:integer;
read_buffer:array[1..100]of char;
begin
clear:=clearcommerror(hcom,lperrors,@coms);
if clear then begin
cbnum:=coms.cbInQue;
readfile(hcom,read_buffer,cbnum,readnumber,lpol);
setevent(post_event);
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
comminitialize;
post_event:=createevent(nil,true,true,nil);
tcomm.create(false);
end;

end.
请各位高手各抒己见,不吝赐教,谢谢。。。。。
 
各位大虾,如有好的主意请帮帮我,事情紧急,要钱可以商量。
 
应该有输出格式吧。
 
procedure TMainFrm.Initialize;
var
TimeOut:CommTimeOuts;
begin
if ParaMeter.ComNo=0 then [h1][/h1]
begin
HCom := CreateFile('COM1',GENERIC_READ or GENERIC_WRITE,
0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
end
else if ParaMeter.ComNo=1 then
HCom := CreateFile('COM2',GENERIC_READ or GENERIC_WRITE,
0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0)
else ShowMessage('请选择COM端口号!');
GetCommState(HCom,Comm_DCB);

Comm_DCB.BaudRate := 1200+Bandrate*1200 ;
Comm_DCB.StopBits := 0;
Comm_DCB.Parity := NoParity;
Comm_DCB.ByteSize := 8 ;
SetupComm(HCom,3000,3000);
Comm_DCB.Flags:=Comm_DCB.Flags and (not $3c);
SetCommState(HCom,Comm_DCB);
GetCommTimeouts(HCom,TimeOut);
TimeOut.ReadTotalTimeoutConstant:=240;
SetCommTimeOuts(Hcom,TimeOut);
end;
我认为问题出在串口初始化。这段程序是我用来初始化串口的,之后就可以用 ReadFile 和 WriteFile 来读写了,我的
程序运行正常,你不妨试一下。
 
你是想接收到字节数据吧.
你的问题在于你是按字符传送的,所以系统把接收的数据全部转化为Ascill码。
所以你收到的是乱吗。
 

Similar threads

D
回复
0
查看
1K
DelphiTeacher的专栏
D
D
回复
0
查看
864
DelphiTeacher的专栏
D
后退
顶部