Delphi中串行通信的实现
(2012-02-13 21:34:10)Delphi的强大功能和支持多线程的面向对象编程技术,使得实现串行通信非常简单方便。它通过调用外部的API函数来实现,主要步骤如下:首先,利用CreateFile函数打开串行口,以确定本应用程序对此串行口的占有权,并封锁其它应用程序对此串口的操作;其次,通过GetCommState函数填充设备控制块DCB,再通过调用SetCommState函数配置串行口的波特率、数据位、校验位和停止位。然后,创建串行口监视线程监视串行口事件。在此基础上就可以在相应的串口上操作数据的传输;最后,用CloseHandle函数关闭串行口。具体的程序如下:
程序:
unit comdemou;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
Cons
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); //设置输入,输出缓冲区皆为4096字节
getcommstate(hcom,lpdcb); //获取串行口当前默认设置
lpdcb.baudrate:=2400;
lpdcb.StopBits:=1;
lpdcb.ByteSize:=8;
lpdcb.Parity:=EvenParity; //偶校验
Setcommstate(hcom,lpdcb);
setcommMask(hcom,ev_rxchar);
//指定串行口事件为接收到字符;
end;
Procedure TForm1.MsgcommProcess(Var Message:Tmessage);
Var
Clear:Boolean;
Coms:Tcomstat;
cbNum,ReadNumber,lpErrors: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.

加载中…