有高手用api函数写的串口接受和发送数据的函数吗。

解决方案 »

  1.   

    有CreateFile我这有个例子,要得话给我发消息,将Email给我,注明是要串口通讯的api例子,肯定要用多线程来读
      

  2.   

    很简单的,但是用Api有不好的地方,win98和win2000的api是不一样的,
    所以我建议你使用mscomm控件来做,比较简单
      

  3.   

    建议使用mscomm,spcomm,turboPower Async Profession
      

  4.   

    unit comdemou;
    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);
    //设置输入,输出缓冲区皆为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.Msgcomm
    Process(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.